Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
1,400
Given the following text description, write Python code to implement the functionality described below step by step Description: QGrid Interactive pandas dataframes Step1: Github https
Python Code: df = pd.read_csv("../data/coal_prod_cleaned.csv") df.head() df.shape df.columns qgrid_widget = qgrid.show_grid( df[["Year", "Mine_State", "Labor_Hours", "Production_short_tons"]], show_toolbar=True, ) qgrid_widget df2 = df.groupby('Mine_State').sum() df3 = df.groupby('Mine_State').sum() df2.loc['Wy...
1,401
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1"><a href="#Task-1.-Compiling-Ebola-Data"><span class="toc-item-num">Task 1.&nbsp;&nbsp;</span>Compiling Ebola Data</a></div> <div class="lev1"><a href=...
Python Code: # Imports %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import glob import csv import calendar import webbrowser from datetime import datetime # Constants DATA_FOLDER = 'Data/' Explanation: Table of Contents <p><div class="lev1"><a href="#Task-1.-Compiling-Ebola-...
1,402
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 4 - Tensorflow ANN for regression In this lab we will use Tensorflow to build an Artificial Neuron Network (ANN) for a regression task. As opposed to the low-level implementation from th...
Python Code: %matplotlib inline import math import random import seaborn as sns import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston import numpy as np import tensorflow as tf sns.set(style="ticks", color_codes=True) Explanation: Lab 4 - Tensorflow ANN for regression In this lab ...
1,403
Given the following text description, write Python code to implement the functionality described below step by step Description: Customizing IPython - Magics IPython extends Python by adding shell-like commands called magics. Step2: Defining your own magic As we have seen already, IPython has cell and line magics. Yo...
Python Code: %lsmagic import numpy %timeit A=numpy.random.random((1000,1000)) %%timeit -n 1 A=numpy.random.random((1000,1000)) b = A.sum() Explanation: Customizing IPython - Magics IPython extends Python by adding shell-like commands called magics. End of explanation ip = get_ipython() import time def sleep_magic(line)...
1,404
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 1 Imports Step2: Checkerboard Write a Python function that creates a square (size,size) 2d Numpy array with the values 0.0 and 1.0 Step3: Use vizarray to visualize a checker...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import antipackage import github.ellisonbg.misc.vizarray as va Explanation: Numpy Exercise 1 Imports End of explanation def checkerboard(size): Return a 2d checkboard of 0.0 and 1.0 as a NumPy array check = ...
1,405
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras for Text Classification Learning Objectives 1. Learn how to create a text classification datasets using BigQuery 1. Learn how to tokenize and integerize a corpus of text for training i...
Python Code: import os from google.cloud import bigquery import pandas as pd %load_ext google.cloud.bigquery Explanation: Keras for Text Classification Learning Objectives 1. Learn how to create a text classification datasets using BigQuery 1. Learn how to tokenize and integerize a corpus of text for training in Keras ...
1,406
Given the following text description, write Python code to implement the functionality described below step by step Description: Text mining In this task we will use nltk package to recognize named entities and classify in a given text (in this case article about American Revolution from Wikipedia). nltk.ne_chunk func...
Python Code: import nltk import numpy as np import wikipedia import re Explanation: Text mining In this task we will use nltk package to recognize named entities and classify in a given text (in this case article about American Revolution from Wikipedia). nltk.ne_chunk function can be used for both recognition and clas...
1,407
Given the following text description, write Python code to implement the functionality described below step by step Description: Jupyter/IPython Notebook Quick Start Guide The following is partially taken from the offical documentation Step1: This is an equation formatted in LaTeX $y = \sin(x)$ double-click this cell...
Python Code: # press Shit+Enter to execute this cell print('This is a cell containing python code') #we can also make figures import matplotlib.pyplot as plt import numpy as np % matplotlib inline x = np.linspace(-np.pi, np.pi, 100) plt.plot(x, np.sin(x)) # Use `Tab` for completion and `Shift-Tab` for code info Explana...
1,408
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Parameters Step3: Colab-only auth Step4: tf.data.Dataset Step5: Let's have a look at the data Step6: Estimator model If you are not sure what cross-entropy, dropou...
Python Code: import os, re, math, json, shutil, pprint, datetime import PIL.Image, PIL.ImageFont, PIL.ImageDraw import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from tensorflow.python.platform import tf_logging print("Tensorflow version " + tf.__version__) Explanation: <a href="https://co...
1,409
Given the following text description, write Python code to implement the functionality described below step by step Description: How the Length of a Jeopardy Question Relates to its Value? The American television game show Jeopardy is probably one of the most famous shows ever aired on TV. Few years ago IBM's Watson c...
Python Code: # this line is required to see visualizations inline for Jupyter notebook %matplotlib inline # importing modules that we need for analysis import matplotlib.pyplot as plt import pandas as pd import numpy as np import re # read the data from file and print out first few rows jeopardy = pd.read_csv("jeopardy...
1,410
Given the following text description, write Python code to implement the functionality described below step by step Description: Questions/Concerns ======================================= Was/how was the main parachute bag held down for LV2? How many lines were cut during LV2 recovery? What if the drogue gets cut away...
Python Code: # General ######################################## # Gravity (m/sec^2) g = 9.81 # Air density (kg/m^3) p = 1.225 # LV2 given information ####################################### print ("LV2 Given Information\n") # Mass of parachute (kg) # From OpenRocket LV2.3.ork m_p2 = 2.118 # Mass of system (rocket + chu...
1,411
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview This is a generalized notebook for computing grade statistics from the Ted Grade Center. Step1: Load data from exported CSV from Ted Full Grade Center. Some sanitization is perform...
Python Code: #The usual imports import math from collections import OrderedDict from pandas import read_csv import numpy as np from pymatgen.util.plotting_utils import get_publication_quality_plot from monty.string import remove_non_ascii import prettyplotlib as ppl from prettyplotlib import brewer2mpl import matplotli...
1,412
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 14 – Recurrent Neural Networks This notebook contains all the sample code and solutions to the exercises in chapter 14. <table align="left"> <td> <a target="_blank" href="https...
Python Code: # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os try: # %tensorflow_version only exists in Colab. %tensorflow_version 1.x except Exception: pass # to make this notebook's output stable across ...
1,413
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating a Heatmap of Vector Results In this notebook, you'll learn how to use Planet's Analytics API to display a heatmap of vector analytic results, specifically buildng change detections....
Python Code: !pip install cython !pip install https://github.com/SciTools/cartopy/archive/v0.18.0.zip Explanation: Creating a Heatmap of Vector Results In this notebook, you'll learn how to use Planet's Analytics API to display a heatmap of vector analytic results, specifically buildng change detections. This can be us...
1,414
Given the following text description, write Python code to implement the functionality described below step by step Description: &nbsp; Feedforward Neural Network Step1: <script type="text/javascript" src="https Step2: It can be seen from the above figure that as we increase our input the our activation starts to sa...
Python Code: # import feedforward neural net from mlnn import neural_net Explanation: &nbsp; Feedforward Neural Network End of explanation # Visualize tanh and its derivative x = np.linspace(-np.pi, np.pi, 120) plt.figure(figsize=(8, 3)) plt.subplot(1, 2, 1) plt.plot(x, np.tanh(x)) plt.title("tanh(x)") plt.xlim(-3, 3)...
1,415
Given the following text description, write Python code to implement the functionality described below step by step Description: NEST implementation of the aeif models Hans Ekkehard Plesser and Tanguy Fardet, 2016-09-09 This notebook provides a reference solution for the Adaptive Exponential Integrate and Fire (AEIF) ...
Python Code: # Install assimulo package in the current Jupyter kernel import sys !{sys.executable} -m pip install assimulo import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (15, 6) Explanation: NEST implementation of the aeif models...
1,416
Given the following text description, write Python code to implement the functionality described below step by step Description: Words Associated to each Gender (through PMI) In this notebook we compute PMI scores for the vocabulary obtained in the previous notebook. By Eduardo Graells-Garrido. Step1: First, we load ...
Python Code: from __future__ import print_function, unicode_literals, division from cytoolz.dicttoolz import valmap from collections import Counter import pandas as pd import json import gzip import numpy as np import pandas as pd import dbpedia_config target_folder = dbpedia_config.TARGET_FOLDER Explanation: Words As...
1,417
Given the following text description, write Python code to implement the functionality described below step by step Description: Adaptive Filters Real-time Use with Padasip Module This tutorial shows how to use Padasip module for filtering and prediction with adaptive filters in real-time. Lets start with importing pa...
Python Code: import numpy as np import matplotlib.pylab as plt import padasip as pa %matplotlib inline plt.style.use('ggplot') # nicer plots np.random.seed(52102) # always use the same random seed to make results comparable Explanation: Adaptive Filters Real-time Use with Padasip Module This tutorial shows how to use P...
1,418
Given the following text description, write Python code to implement the functionality described below step by step Description: EventVestor Step1: Let's go over the columns Step2: Finally, suppose we want a DataFrame of all earnings calendar releases in February 2012, but we only want the event_headline and the cal...
Python Code: # import the dataset from quantopian.interactive.data.eventvestor import earnings_calendar as dataset # or if you want to import the free dataset, use: # from quantopian.data.eventvestor import earnings_calendar_free # import data operations from odo import odo # import other libraries we will use import p...
1,419
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: 3T_데이터베이스, 테이블 생성하고 데이터 추가하기 우리의 데이터베이스 서버에 "데이터베이스", "테이블", "데이터" 생성하고, 저장하기 데이터베이스 생성하기 ( 각자 이름으로 ) 테이블 생성하기 ( "zigbang" ) 데이터 추가하기 Step9: 실습) 데이터를 어떻게 저장할 것인가? - 확장성이 있는가, ... ( J...
Python Code: zigbang_df = pd.read_csv("zigbang.csv") zigbang_df.head() import pymysql db = pymysql.connect( "db.fastcamp.us", "root", "dkstncks", # "sakila", charset="utf8", ) # cursor 라는 객체를 가져와서 DB에 명령을 실행시킵니다. cursor = db.cursor() # 현재 있는 모든 데이터베이스 이름을 가져오는 명령어 SQL_QUERY = SHOW DATABASES; # ...
1,420
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: The <span style="background-color Step2: Creating placeholders It's a best practice to create placeholders before variable assignments when using TensorFlow. Here we'...
Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) Explanation: <a href="https://www.cognitiveclass.ai"><img src = "https://cognitiveclass.ai/wp-content/themes/bdu3.0/static/images/cc-logo.png" align = left></a> <...
1,421
Given the following text description, write Python code to implement the functionality described below step by step Description: I've implemented the integral of wt in pearce. This notebook verifies it works as I believe it should. Step1: Load up the tptY3 buzzard mocks. Step2: Load up a snapshot at a redshift near ...
Python Code: from pearce.mocks import cat_dict import numpy as np from os import path from astropy.io import fits import matplotlib #matplotlib.use('Agg') from matplotlib import pyplot as plt %matplotlib inline import seaborn as sns sns.set() Explanation: I've implemented the integral of wt in pearce. This notebook ver...
1,422
Given the following text description, write Python code to implement the functionality described below step by step Description: <CENTER> <a href="http Step1: In order to activate the interactive visualisation of the histogram that is later created we can use the JSROOT magic Step2: Next we have to open the data...
Python Code: import ROOT Explanation: <CENTER> <a href="http://opendata.atlas.cern" class="icons"><img src="http://opendata.atlas.cern/DataAndTools/pictures/opendata-top-transblack.png" style="width:40%"></a> </CENTER> A more difficult notebook in python In this notebook you can find a more difficult program that s...
1,423
Given the following text description, write Python code to implement the functionality described below step by step Description: The use of watermark (above) is optional, and we use it to keep track of the changes while developing the tutorial material. (You can install this IPython extension via "pip install watermar...
Python Code: from sklearn.datasets import load_iris iris = load_iris() Explanation: The use of watermark (above) is optional, and we use it to keep track of the changes while developing the tutorial material. (You can install this IPython extension via "pip install watermark". For more information, please see: https://...
1,424
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Recurrent Neural Networks (RNNs) Recurrent Neural Networks (RNNs) are an interesting application of deep learning that allow models to predict the future. While regres...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
1,425
Given the following text description, write Python code to implement the functionality described below step by step Description: Nipype Quickstart Existing documentation Visualizing the evolution of Nipype This notebook is taken from reproducible-imaging repository Import a few things from nipype and external librarie...
Python Code: import os from os.path import abspath from nipype import Workflow, Node, MapNode, Function from nipype.interfaces.fsl import BET, IsotropicSmooth, ApplyMask from nilearn.plotting import plot_anat %matplotlib inline import matplotlib.pyplot as plt Explanation: Nipype Quickstart Existing documentation Visual...
1,426
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', 'miroc', 'nicam16-7s', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MIROC Source ID: NICAM16-7S Topic: Aerosol Sub-Topics: Transport, Emiss...
1,427
Given the following text description, write Python code to implement the functionality described below step by step Description: Suggestions for lab exercises. Variables and assignment Exercise 1 Remember that $n! = n \times (n - 1) \times \dots \times 2 \times 1$. Compute $15!$, assigning the result to a sensible var...
Python Code: fifteen_factorial = 15*14*13*12*11*10*9*8*7*6*5*4*3*2*1 print(fifteen_factorial) Explanation: Suggestions for lab exercises. Variables and assignment Exercise 1 Remember that $n! = n \times (n - 1) \times \dots \times 2 \times 1$. Compute $15!$, assigning the result to a sensible variable name. Solution En...
1,428
Given the following text description, write Python code to implement the functionality described below step by step Description: Unsupervised learning Step1: First, we start with some exploratory clustering, visualizing the clustering dendrogram using SciPy's linkage and dendrogram functions Step2: Next, let's use t...
Python Code: from sklearn.datasets import load_iris iris = load_iris() X = iris.data[:, [2, 3]] y = iris.target n_samples, n_features = X.shape plt.scatter(X[:, 0], X[:, 1], c=y); Explanation: Unsupervised learning: Hierarchical and density-based clustering algorithms In a previous notebook, "08 Unsupervised Learning -...
1,429
Given the following text description, write Python code to implement the functionality described below step by step Description: Inspecting the PubMed Paper Dataset (Adapted from Step1: To make it easier to access the data, we convert here paper entries into named tuples. This will allow us to refer to fields by keyw...
Python Code: import pickle, bz2 Summaries_file = 'data/air__Summaries.pkl.bz2' Summaries = pickle.load( bz2.BZ2File( Summaries_file, 'rb' ) ) Explanation: Inspecting the PubMed Paper Dataset (Adapted from: Inspecting the dataset - Luís F. Simões. Assignments added by J.E. Hoeksema, 2014-10-16. Converted to Python 3 and...
1,430
Given the following text description, write Python code to implement the functionality described below step by step Description: Real World Tutorial 3 Step3: We define a function that computes the sum of all primes below a certain integer n, and don't try to be smart about it; the point is that it needs a lot of comp...
Python Code: %load_ext cython import multiprocessing import threading import queue Explanation: Real World Tutorial 3: Parallel Number crunching using Cython Python was not designed to be very good at parallel processing. There are two major problems at the core of the language that make it hard to implement parallel a...
1,431
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparison of two means (T-test) Step1: In this notebook we demo two equivalent ways of performing a two-sample Bayesian t-test to compare the mean value of two Gaussian populations using B...
Python Code: import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd az.style.use("arviz-darkgrid") np.random.seed(1234) Explanation: Comparison of two means (T-test) End of explanation a = np.random.normal(6, 2.5, 160) b = np.random.normal(8, 2, 120) df = pd.DataFr...
1,432
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Exercise 1 Step2: b. Checking for Normality As an extra all-purpose check, and one that is often done on series, check whether the above series is normally distributed usi...
Python Code: # Useful Functions def check_for_stationarity(X, cutoff=0.01): # H_0 in adfuller is unit root exists (non-stationary) # We must observe significant p-value to convince ourselves that the series is stationary pvalue = adfuller(X)[1] if pvalue < cutoff: print 'p-value = ' + str(pvalue...
1,433
Given the following text description, write Python code to implement the functionality described below step by step Description: Abstract Titel Step1: Einführung in<br/> Software Analytics <b>Markus Harrer</b>, Software Development Analyst @feststelltaste <small>ML Summit 2019, 14. Oktober 2019</small> <img src="../....
Python Code: %matplotlib inline import pandas as pd Explanation: Abstract Titel: Einführung in Software Analytics Beschreibung In Unternehmen werden Datenanalysen intensiv genutzt, um aus Geschäftsdaten wertvolle Einsichten zu gewinnen. Warum nutzen wir als Softwareentwickler Datenanalysen dann nicht auch für unsere ei...
1,434
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-3', 'sandbox-3', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: TEST-INSTITUTE-3 Source ID: SANDBOX-3 Topic: Atmos Sub-Topics: Dy...
1,435
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is an effort to replicate the lessons found here Step1: We're going to fetch the data file we need for this exercise from the following URL Step2: Let's make a plot of the da...
Python Code: import numpy as np import pandas as pd from geostatsmodels import utilities, kriging, variograms, model, geoplot import matplotlib.pyplot as plt from scipy.stats import norm Explanation: This notebook is an effort to replicate the lessons found here: http://people.ku.edu/~gbohling/cpe940/Variograms.pdf We'...
1,436
Given the following text description, write Python code to implement the functionality described below step by step Description: Interpolation Exercise 2 Step1: Sparse 2d interpolation In this example the values of a scalar field $f(x,y)$ are known at a very limited set of points in a square domain Step2: The follow...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set_style('white') from scipy.interpolate import griddata from scipy.interpolate import interp2d Explanation: Interpolation Exercise 2 End of explanation x=np.array([5,5,5,5,5,5,4,3,2,1,0,-1,-2,-3,-4,-5,-5,-5,-5...
1,437
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear Regression and Subset Selection StatML Step2: Recall LinearRegression.fit Throughout let $p < n$ Fit in OLS solves the following, on training set $$ \hat \beta = (X^\top X)^{-1} X^\t...
Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model import scipy as sc Explanation: Linear Regression and Subset Selection StatML: Lecture 3 Prof. James Sharpnack Reading: "The Elements of Statistical Learning," Hastie, Tibshirani, Friedman, Ch. 3 (ESL) End of explanation de...
1,438
Given the following text description, write Python code to implement the functionality described below step by step Description: Pyplot pyplot is a context based functional API offering meaningful defaults. It's a concise API and very similar to matplotlib's pyplot. Users new to bqplot should use pyplot as a starting ...
Python Code: import bqplot.pyplot as plt # first, let's create two vectors x and y to plot using a Lines mark import numpy as np x = np.linspace(-10, 10, 100) y = np.sin(x) # 1. Create the figure object fig = plt.figure(title="Simple Line Chart") # 2. By default axes are created with basic defaults. If you want to cust...
1,439
Given the following text description, write Python code to implement the functionality described below step by step Description: Final Exam Review CSCI 1360E Step1: Another example is Part G, asking you to write a function that reverses the elements of an array. According to the instructions, you were not allowed to ...
Python Code: def dot(arr1, arr2): if arr1.shape[0] != arr2.shape[0]: return None p = arr1 * arr2 # Multiplies corresponding elements of the two arrays...no loops needed! s = p.sum() # Computes the sum of all the elements...still no loops needed! return s Explanation: Final Exam Review CSCI...
1,440
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring Optimizers A Code Along of Kerem Turgutlu's Notebook Step1: This notebook is inspired by Sebastian Ruder's awesome work from http Step2: Training With Different Optimizers Step3:...
Python Code: # Classical import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib # PyTorch import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader from torch import optim # Misc %matplotlib in...
1,441
Given the following text description, write Python code to implement the functionality described below step by step Description: LeNet Lab Source Step1: The MNIST data that TensorFlow pre-loads comes as 28x28x1 images. However, the LeNet architecture only accepts 32x32xC images, where C is the number of color channel...
Python Code: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test = mnist.tes...
1,442
Given the following text description, write Python code to implement the functionality described below step by step Description: ====================================================== Compute source power spectral density (PSD) in a label ====================================================== Returns an STC file conta...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, compute_source_psd print(__doc__) Explanation: ==========================...
1,443
Given the following text description, write Python code to implement the functionality described below step by step Description: Resampling data When performing experiments where timing is critical, a signal with a high sampling rate is desired. However, having a signal with a much higher sampling rate than is necessa...
Python Code: # Authors: Marijn van Vliet <w.m.vanvliet@gmail.com> # # License: BSD (3-clause) from matplotlib import pyplot as plt import mne from mne.datasets import sample Explanation: Resampling data When performing experiments where timing is critical, a signal with a high sampling rate is desired. However, having ...
1,444
Given the following text description, write Python code to implement the functionality described below step by step Description: TFLearn [Participle Phrase] Fragment Detection This notebook is based off the original fragment detection notebook, but specific to detection of participle phrase fragments. As our trainin g...
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical import spacy nlp = spacy.load('en') import re from nltk.util import ngrams, trigrams import csv Explanation: TFLearn [Participle Phrase] Fragment Detection This notebook is based off ...
1,445
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 5 Step1: Example 1 Step2: Example 2 Step3: Example 3 Step4: Example 4 Step5: Example 5
Python Code: # Import relevant modules %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams from NPTFit import psf_correction as pc # Module for determining the PSF correction from __future__ import print_function Explanation: Example 5...
1,446
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. h=(b-a)/N k=np.arange(1,N) I=h*(0.5*f(a)+0....
1,447
Given the following text description, write Python code to implement the functionality described below step by step Description: Randomly Generate A Stock Price & View The Data Here, we create an application which is submitted to a remote host, yet we retrieve its data remotely via views. This way, we can graph remote...
Python Code: from streamsx.topology.topology import Topology from streamsx.topology import context from some_module import jsonRandomWalk #from streamsx import rest import json import logging # Define topology & submit rw = jsonRandomWalk() top = Topology("myTop") stock_data = top.source(rw) # The view object can be us...
1,448
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualización de sistemas mecánicos Dado un sistema masa resorte amortiguador como el de la figura siguiente Step1: Graficas Una vez que tenemos los datos, nos disponemos a graficarlos, aho...
Python Code: from control import step, tf m = 1200 k = 15000 c = 1500 F = 1 G = tf([0, 0, 1/m], [1, c/m, k/m]) G y, t = step(G) Explanation: Visualización de sistemas mecánicos Dado un sistema masa resorte amortiguador como el de la figura siguiente: Graficar la trayectoria del sistema, y animar los componentes fisicos...
1,449
Given the following text description, write Python code to implement the functionality described below step by step Description: Data preprocessing methods Step1: 1. Data preprocessing 1.1. The dataset. A key component of any data processing method or any machine learning algorithm is the dataset, i.e., the set of da...
Python Code: # Some libraries that will be used along the notebook. import numpy as np import matplotlib.pyplot as plt Explanation: Data preprocessing methods: Normalization Notebook version: * 1.0 (Sep 15, 2020) - First version * 1.1 (Sep 15, 2021) - Exercises Authors: Jesús Cid Sueiro (jcid@ing.uc3m.es) End of explan...
1,450
Given the following text description, write Python code to implement the functionality described below step by step Description: Artifact Correction with ICA ICA finds directions in the feature space corresponding to projections with high non-Gaussianity. We thus obtain a decomposition into independent components, and...
Python Code: import numpy as np import mne from mne.datasets import sample from mne.preprocessing import ICA from mne.preprocessing import create_eog_epochs, create_ecg_epochs # getting some data ready data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' raw = mne.io.read...
1,451
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizing time series metabolome profile by Kozo Nishida (Riken, Japan) Software Requirments Please install the following software packages to run this workflow Step1: Load a KGML pathway...
Python Code: import json import requests import pandas as pd PORT_NUMBER = 1234 BASE_URL = "http://localhost:" + str(PORT_NUMBER) + "/v1/" HEADERS = {'Content-Type': 'application/json'} Explanation: Visualizing time series metabolome profile by Kozo Nishida (Riken, Japan) Software Requirments Please install the followi...
1,452
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 4 Work on this before the next lecture on 1 May. We will talk about questions, comments, and solutions during the exercise after the third lecture. Please do form study groups! When...
Python Code: %config InlineBackend.figure_format='retina' %matplotlib inline import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (8, 8) plt.rcParams["font.size"] = 14 from sklearn.utils import check_random_state Explanation: Exercise 4 Work on this before the next lecture on 1 May. We wi...
1,453
Given the following text description, write Python code to implement the functionality described below step by step Description: Stay Alert! The Ford Challenge by Scott Josephson Driving while distracted, fatigued or drowsy may lead to accidents. Activities that divert the driver's attention from the road ahead, such ...
Python Code: import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, classification_report Explanation: Stay Alert! The Ford Challenge by Scott Josephson Driving while distracted, fatigued...
1,454
Given the following text description, write Python code to implement the functionality described below step by step Description: Show noise levels from empty room data This shows how to use Step1: We can plot the absolute noise levels
Python Code: # Author: Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import os.path as op import mne data_path = mne.datasets.sample.data_path() raw_erm = mne.io.read_raw_fif(op.join(data_path, 'MEG', 'sample', 'ernoise_raw.fif'), preload=True) Explanation: Show...
1,455
Given the following text description, write Python code to implement the functionality described below step by step Description: BeautifulSoup 4 Step1: findNext() - Finding e-mail trough its label There are unlimited number of options for matching an e-mail from a page. This time, we will try to find my e-mail by fir...
Python Code: import requests from BeautifulSoup import * url = "https://hrantdavtyan.github.io/" response = requests.get(url) page = response.text soup = BeautifulSoup(page) Explanation: BeautifulSoup 4: Navigation BeautifulSoup is a powerful package mostly due to the abundance of Navigation methods in the package. Bel...
1,456
Given the following text description, write Python code to implement the functionality described below step by step Description: The Hill-Tononi Neuron and Synapse Models Hans Ekkehard Plesser, NMBU/FZ Jülich/U Oslo, 2016-12-01 Background This notebook describes the neuron and synapse model proposed by Hill and Tononi...
Python Code: import sys import math import numpy as np import pandas as pd import scipy.optimize as so import scipy.integrate as si import matplotlib.pyplot as plt import nest %matplotlib inline plt.rcParams['figure.figsize'] = (12, 3) Explanation: The Hill-Tononi Neuron and Synapse Models Hans Ekkehard Plesser, NMBU/F...
1,457
Given the following text description, write Python code to implement the functionality described below step by step Description: syncID Step1: Next, set display preferences so that plots are inline (meaning any images you output from your code will show up below the cell in the notebook) and turn off plot warnings St...
Python Code: import numpy as np import h5py import gdal, osr, os import matplotlib.pyplot as plt Explanation: syncID: 61ad1fc43ddd45b49cad1bca48656bbe title: "NEON AOP Hyperspectral Data in HDF5 format with Python - Tiled Data" description: "Learn how to read NEON AOP hyperspectral flightline data using Python and dev...
1,458
Given the following text description, write Python code to implement the functionality described below step by step Description: You are currently looking at version 1.0 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ...
Python Code: import pandas as pd import numpy as np def blight_model(): # Your code here return # Your answer here df_train = pd.read_csv('train.csv', encoding = "ISO-8859-1") df_test = pd.read_csv('test.csv', encoding = "ISO-8859-1") df_train.columns list_to_remove = ['balance_due', 'collection_stat...
1,459
Given the following text description, write Python code to implement the functionality described below step by step Description: Dynamic Programming and Graph Algorithm Problems Here are what we went over in the class. In addition here are the links to the MIT Course I mentioned and to my repo that has a lot more impl...
Python Code: def fib(n): if n < 0: raise Exception("Index was negative. Cannot have a negative index in a series") if n < 2: return n return fib(n-1) + fib(n-2) fib(25) def fib(n): if n < 0: raise Exception("Index was negative. Cannot have a negative inde...
1,460
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 15 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: So far the systems we have studied have been physical in the sense that they exist in the world, but ...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
1,461
Given the following text description, write Python code to implement the functionality described below step by step Description: Date Step1: Only train on data when the rat is moving Step2: Encoding Model Train model Step3: Get predicted conditional intensities Step4: Plot model fits for each neuron to check fit q...
Python Code: %matplotlib inline %reload_ext autoreload %autoreload 2 %qtconsole import sys import collections import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from tqdm import tqdm_notebook as tqdm import patsy import statsmodels.api as sm import statsmodels.formula.api as sm...
1,462
Given the following text description, write Python code to implement the functionality described below step by step Description: Nonlinear Astro Features This notebook examines whether $w_1 - w_2$ and $w_2 - w_3$ are good features. There are indications that these may be correlated with whether galaxies contain AGNs. ...
Python Code: import h5py, numpy, sklearn.linear_model, sklearn.cross_validation, sklearn.metrics with h5py.File('../data/training.h5') as f: raw_astro_features = f['features'][:, :4] dist_features = f['features'][:, 4] image_features = f['features'][:, 5:] w1_w2 = raw_astro_features[:, 0] - raw_ast...
1,463
Given the following text description, write Python code to implement the functionality described below step by step Description: Competition assay analysis and thoughts Here we will analyze two competition assay conducted as a rough beginning to understand how to best design competition assays to the fluorescent kinas...
Python Code: #import needed libraries import re import os from lxml import etree import pandas as pd import pymc import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Explanation: Competition assay analysis and thoughts Here we will analyze two competition ...
1,464
Given the following text description, write Python code to implement the functionality described below step by step Description: Dane treningowe Ponieważ będziemy potrzebowali na czymś wytrenować naszą sieć neuronową skorzystamy z popularnego zbioru w Machine Learningu czyli MNIST. Zbiór ten zawiera ręcznie pisane cyf...
Python Code: # skorzystamy z gotowej funkcji do pobrania tego zbioru from sklearn.datasets import fetch_mldata mnist = fetch_mldata('MNIST original') Explanation: Dane treningowe Ponieważ będziemy potrzebowali na czymś wytrenować naszą sieć neuronową skorzystamy z popularnego zbioru w Machine Learningu czyli MNIST. Zbi...
1,465
Given the following text description, write Python code to implement the functionality described below step by step Description: Structure Prediction In this notebook, we aim to do a test of the structure substitution algorithm implemented in SMACT Before we can do predictions, we need to create our cation mutator, da...
Python Code: comps=pd.read_csv("Li-Garnet_Comps_sus.csv") comps.head() Explanation: Structure Prediction In this notebook, we aim to do a test of the structure substitution algorithm implemented in SMACT Before we can do predictions, we need to create our cation mutator, database and a table, and a list of hypothetical...
1,466
Given the following text description, write Python code to implement the functionality described below step by step Description: Association Mining The goal in this problem set is to design and code an algorithm for generating association rules based on the apriori algorithm. The dataset that you will use to mine for ...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline with open('itemsets.dat') as f: transactions = [] for row in f: transactions.append(row.strip().split(',')) transactions[0:5] Explanation: Association Mining The goal in this problem set is to design a...
1,467
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Python for Everyone!<br/>Oregon Curriculum Network Descriptors and Properties in Python <img src="https Step2: y's value is an ordinary int, equivalently the value of MyClass.__dict_...
Python Code: class RevealAccess(object): A data descriptor that sets and returns values normally and prints a message logging their access. Descriptor Example: https://docs.python.org/3/howto/descriptor.html def __init__(self, initval=None, name='var'): self.val = initva...
1,468
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Matplotlib Concepts Lecture In this lecture we cover some more advanced topics which you won't usually use as often. You can always reference the documentation for more resources! ...
Python Code: import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.linspace(0, 5, 11) y = x**2 fig, axes = plt.subplots(1, 2, figsize=(10,4)) axes[0].plot(x, x**2, x, np.exp(x)) axes[0].set_title("Normal scale") axes[1].plot(x, x**2, x, np.exp(x)) axes[1].set_yscale("log") axes[1].set_titl...
1,469
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: TF Lattice 사전 제작 모델 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 필수 패키지 가져오기 Step3: UCI Stat...
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...
1,470
Given the following text description, write Python code to implement the functionality described below step by step Description: xlrd demo This notebook demonstrates the xlrd package which is designed to read MS Excel files. This is not a built-in package, but rather 3rd party package that is installed with ArcGIS Des...
Python Code: #Import the os and the xlrd modules import xlrd #Set a variable to the path of the xlsx file xlFilename = './Data/USGSCircular1405-tables1-14.xlsx' Explanation: xlrd demo This notebook demonstrates the xlrd package which is designed to read MS Excel files. This is not a built-in package, but rather 3rd par...
1,471
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 7 Step1: The totient is a multiplicative function, meaning that if $GCD(a,b) = 1$, then $\phi(ab) = \phi(a) \phi(b)$. Therefore, the totient of number can be found quickly from the to...
Python Code: def GCD(a,b): while b: # Recall that != means "not equal to". a, b = b, a % b return abs(a) def totient(m): tot = 0 # The running total. j = 0 while j < m: # We go up to m, because the totient of 1 is 1 by convention. j = j + 1 # Last step of while loop: j = m-1, an...
1,472
Given the following text description, write Python code to implement the functionality described below step by step Description: File IO These notebooks are used to check certain examples in the course notes, hence they are mainly for the benefit of the course developers, rather than a teaching resource. Step1: Pytho...
Python Code: import numpy as np import pandas as pd #Go up one directory as this is where the 'current' directory assumed in the course notes cd .. !head -3 "data/titanic.csv" !tail -3 "data/titanic.csv" Explanation: File IO These notebooks are used to check certain examples in the course notes, hence they are mainly ...
1,473
Given the following text description, write Python code to implement the functionality described below step by step Description: BUILDING A RECOMMENDER SYSTEM ON USER-USER COLLABORATIVE FILTERING (MOVIELENS DATASET) We will load the data sets firsts. Step1: We will use the file u.data first as it contains User ID, Mo...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import math #column headers for the dataset data_cols = ['user id','movie id','rating','timestamp'] item_cols = ['movie id','movie title','release date','video release date','IMDb URL','unknown','Action', 'Adventure','Animation','Childr...
1,474
Given the following text description, write Python code to implement the functionality described below step by step Description: Checking standard usage Step1: NOTE easyplot crashes if nicknames are not given Step2: Loading journal Step3: NOTE should rename index to cell_name instead of filename Step4: Note need t...
Python Code: files = [f1, f2] names = [f1.name, f2.name] ezplt = easyplot.EasyPlot(files, names, figtitle="Test1") ezplt.plot() Explanation: Checking standard usage End of explanation easyplot.EasyPlot( files, names, figtitle="Test2", galvanostatic_normalize_capacity=True, all_in_one=True, dqdv_...
1,475
Given the following text description, write Python code to implement the functionality described below step by step Description: Numerical Modeling Reference Step1: We need to give an initial wave which is a function of $x$ (remember, $u(x,0)=u_0(x)$). We can easily choose a step-function for the velocity Step2: Bre...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt # spatial grid nx = 41 # try changing from 41 to 81 dx = 2./(nx-1) #dx = delta x nt = 20 dt = nt/1000. #dt = delta t c = 1. # wavespeed Explanation: Numerical Modeling Reference: 12 steps to Navier-Stokes. Given the broad topics of "Mode...
1,476
Given the following text description, write Python code to implement the functionality described below step by step Description: Core data model Xarray-Beam tries to make it straightforward to write distributed pipelines with Xarray objects, but unlike libraries like Xarray with Dask or Dask/Spark DataFrames, it doesn...
Python Code: import apache_beam as beam import numpy as np import xarray_beam as xbeam import xarray Explanation: Core data model Xarray-Beam tries to make it straightforward to write distributed pipelines with Xarray objects, but unlike libraries like Xarray with Dask or Dask/Spark DataFrames, it doesn't hide the dist...
1,477
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 7 CHE 116 Step1: 2. Chemical Reaction (6 Points) A set of frist-order chemical reactions can be described by the following system of differential equations Step2: 2.4 Answer That ...
Python Code: import numpy as np from numpy import linalg #note z^2 doesn't affect our answer a_matrix = [[6, 4,-1],\ [1, -1, 0],\ [2, -2, -1]] b_matrix = [0, 6, -4] #convert them to numpy arrays/matrices np_a_matrix = np.array(a_matrix) np_b_matrix = np.array(b_matrix).transpose() #Solve the pro...
1,478
Given the following text description, write Python code to implement the functionality described below step by step Description: 请在环境变量中设置DB_URI指向数据库 Step1: 1. Single Day Analysis Step2: Portfolio Construction using EPS factor as alpha factor; short selling is forbiden; target of volatility for the activate weight i...
Python Code: %matplotlib inline import os import numpy as np import pandas as pd from matplotlib import pyplot as plt from PyFin.api import * from alphamind.api import * from alphamind.strategy.strategy import Strategy, RunningSetting from alphamind.portfolio.meanvariancebuilder import target_vol_builder plt.style.use(...
1,479
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: design a simple deep learning architecture for next word predection
Python Code:: model = Sequential() model.add(Embedding(vocab_size, 10, input_length=1)) model.add(LSTM(1000, return_sequences=True)) model.add(LSTM(1000)) model.add(Dense(1000, activation="relu")) model.add(Dense(vocab_size, activation="softmax"))
1,480
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning to Use XGBoost XGBoost is the leading model for working with standard tabular data (the type of data you store in pandas DataFrames, as opposed to more exotic types of data like ima...
Python Code: import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import Imputer data = pd.read_csv('input/train.csv') data.dropna(axis=0, subset=['SalePrice'], inplace=True) y = data.SalePrice X = data.drop(['SalePrice'], axis=1).select_dtypes(exclude=['object']) train_X,...
1,481
Given the following text description, write Python code to implement the functionality described below step by step Description: Parameter identification example Here is a simple toy model that we use to demonstrate the working of the inference package $\emptyset \xrightarrow[]{k_1(I)} X \; \; \; \; X \xrightarrow[]{d...
Python Code: %matplotlib inline %config InlineBackend.figure_format = "retina" from matplotlib import rcParams rcParams["savefig.dpi"] = 100 rcParams["figure.dpi"] = 100 rcParams["font.size"] = 20 %matplotlib inline import bioscrape as bs from bioscrape.types import Model from bioscrape.simulator import py_simulate_mod...
1,482
Given the following text description, write Python code to implement the functionality described below step by step Description: Overfitting Create a dataset based on a true sinusoidal relationship Let's look at a synthetic dataset consisting of 30 points drawn from the sinusoid $y = \sin(4x)$ Step1: Create random va...
Python Code: import graphlab import math import random import numpy from matplotlib import pyplot as plt %matplotlib inline Explanation: Overfitting Create a dataset based on a true sinusoidal relationship Let's look at a synthetic dataset consisting of 30 points drawn from the sinusoid $y = \sin(4x)$: End of explanati...
1,483
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulating Galaxy Observations Step1: Galaxy Model The model for the spatial intensity of the galaxy we observe (i.e. the distribution of brightness on the sky) has two basic components Ste...
Python Code: # only necessary if you're running Python 2.7 or lower from __future__ import print_function from __builtin__ import range import numpy as np # import plotting utility and define our naming alias from matplotlib import pyplot as plt # plot figures within the notebook rather than externally %matplotlib inli...
1,484
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', 'hammoz-consortium', 'sandbox-3', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: HAMMOZ-CONSORTIUM Source ID: SANDBOX-3 Topic: Ocnbgchem ...
1,485
Given the following text description, write Python code to implement the functionality described below step by step Description: We won't work through this notebook We won't have time. But I thought I'd include it, in case you want to see exactly how I implement my population-level quality metric. Step2: Let's put t...
Python Code: import numpy as np, pandas as pd Explanation: We won't work through this notebook We won't have time. But I thought I'd include it, in case you want to see exactly how I implement my population-level quality metric. End of explanation def measure_prediction_quality(csmf_pred, y_test): Calculate popula...
1,486
Given the following text description, write Python code to implement the functionality described below step by step Description: AdaptiveMD Example 4 - Custom Task objects 0. Imports Step1: Let's open our test project by its name. If you completed the first examples this should all work out of the box. Step2: Open a...
Python Code: from adaptivemd import Project, File#, PythonTask, Task Explanation: AdaptiveMD Example 4 - Custom Task objects 0. Imports End of explanation project = Project('tutorial') Explanation: Let's open our test project by its name. If you completed the first examples this should all work out of the box. End of e...
1,487
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2017 Google LLC. Step1: # 사전 작업
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
1,488
Given the following text description, write Python code to implement the functionality described below step by step Description: Mixtures of Gaussian processes with GPclust This notebook accompanies the paper Nonparameteric Clustering of Structured Time Series James Hensman, Magnus Rattray and Neil D. Lawrence IEEE TP...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'png'#'svg' would be better, but eats memory for these big plots. from matplotlib import pyplot as plt import numpy as np import GPy import sys sys.path.append('/home/james/work/gpclust/') import GPclust Explanation: Mixtures of Gaussian processes wi...
1,489
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a file with arrays or different shapes. I want to zeropad all the array to match the largest shape. The largest shape is (93,13).
Problem: import numpy as np a = np.ones((41, 12)) shape = (93, 13) result = np.pad(a, ((0, shape[0]-a.shape[0]), (0, shape[1]-a.shape[1])), 'constant')
1,490
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Explanation for Classification Models This document describes the usage of a classification model to provide an explanation for a given prediction. Model explanation provides the abili...
Python Code: from sklearn import datasets import pandas as pd %matplotlib inline ds = datasets.load_breast_cancer(); NC = 4 lFeatures = ds.feature_names[0:NC] df_orig = pd.DataFrame(ds.data[:,0:NC] , columns=lFeatures) df_orig['TGT'] = ds.target df_orig.sample(6, random_state=1960) Explanation: Model Explanation for Cl...
1,491
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook illustrates the use of tables in conveying the combination of inferential and computational thinking through studying concepts of probability theory. It the Birthday Surprise ...
Python Code: # HIDDEN from datascience import * %matplotlib inline import matplotlib.pyplot as plots plots.style.use('fivethirtyeight') import numpy as np # datascience version number of last run of this notebook version.__version__ Explanation: This notebook illustrates the use of tables in conveying the combination o...
1,492
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex SDK Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the additional packages, you need to restart the no...
Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG Explanation: Vertex SDK: Custom training image classification model for online prediction with explain...
1,493
Given the following text description, write Python code to implement the functionality described below step by step Description: Centrality This evaluates the Eigenvector Centrality and PageRank implemented in Python against C++-native EVZ and PageRank. The Python implementation uses SciPy (and thus ARPACK) to compute...
Python Code: cd ../../ import networkit G = networkit.graphio.readGraph("input/celegans_metabolic.graph", networkit.Format.METIS) Explanation: Centrality This evaluates the Eigenvector Centrality and PageRank implemented in Python against C++-native EVZ and PageRank. The Python implementation uses SciPy (and thus ARPAC...
1,494
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Exploratory Data Analysis (EDA) for Propensity Modeling This notebook helps to Step1: Notebook custom settings Step2: Configuration Edit config.yaml to update GCP configuration that is ...
Python Code: # Uncomment to install required python modules # !sh ../utils/setup.sh # Add custom utils module to Python environment import os import sys sys.path.append(os.path.abspath(os.pardir)) import pandas as pd from gps_building_blocks.cloud.utils import bigquery as bigquery_utils from utils import eda_ga from ut...
1,495
Given the following text description, write Python code to implement the functionality described below step by step Description: MSM of the alanine dipeptide Here we run through most of the things that can be done with this package using a simple two-state model. There are more sophisticated examples that enable for f...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import math import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set(style="ticks", color_codes=True, font_scale=1.5) sns.set_style({"xtick.direction": "in", "ytick.direction": "in"}) Explanation: MSM of the alanine dipeptide Her...
1,496
Given the following text description, write Python code to implement the functionality described below step by step Description: ODEs We will use this notebook to define the differential equations that will be solved. Each function representing a differential equation or set of differential equations should take a sta...
Python Code: def Exponential(y, t, args=None): dydt=y return(dydt) Explanation: ODEs We will use this notebook to define the differential equations that will be solved. Each function representing a differential equation or set of differential equations should take a state vector and time array as its first two ...
1,497
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Introduction to Regular Expressions Regular Expressions are a powerful feature of the Python programming language. You can access Python's regular expression support t...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
1,498
Given the following text description, write Python code to implement the functionality described below step by step Description: Make figures more publication ready In this example, we show several use cases to take MNE plots and customize them for a more publication-ready look. Step1: Imports We are importing everyt...
Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # Daniel McCloy <dan.mccloy@gmail.com> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # # License: BSD-3-Clause Explanation: Make figures more publication ready In this example, we show several use cases to take MNE plots and customize t...
1,499
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Solution Notebook Problem Step1: Pythonic-Code This question has an artificial constr...
Python Code: from __future__ import division def list_of_chars(chars): if chars is None: return None size = len(chars) for i in range(size//2): chars[i], chars[size-1-i] = \ chars[size-1-i], chars[i] return chars Explanation: <small><i>This notebook was prepared by Donne Mart...