Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
4,200
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Object reconstruction from a cloud of points in 2D using $\alpha$-shapes and Vietoris-Rips complexes Step4: Now construct $\alpha$-shapes and Vietoris-Rips complex from this cloud of...
Python Code: import dionysus import math from random import random from matplotlib import pyplot def generate_circle(n, radius, max_noise): Generate n points on a sphere with the center in the point (0,0) with the given radius. Noise is added so that the distance from the generated point to ...
4,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Word Embeddings Learning Objectives You will learn Step1: This notebook uses TF2.x. Please check your tensorflow version using the cell below. Step2: Download the IMDb Dataset You will use...
Python Code: # Use the chown command to change the ownership of repository to user. !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst import io import os import re import shutil import string import tensorflow as tf from datetime import datetime from tensorflow.keras import Model, Sequential from tenso...
4,202
Given the following text description, write Python code to implement the functionality described below step by step Description: Key Requirements for the iRF scikit-learn implementation The following is a documentation of the main requirements for the iRF implementation Pseudocode iRF implementation Step 0 Step1: Ste...
Python Code: # Setup %matplotlib inline import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.cross_validation import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix from sklearn.datasets import load_iris from sklearn import...
4,203
Given the following text description, write Python code to implement the functionality described below step by step Description: TFLearn Subject Verb Agreement Error Detection 2 This notebook is based off the original fragment detection notebook, but specific to detection of participle phrase fragments. As our trainin...
Python Code: import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical import spacy import re from textstat.textstat import textstat from pattern.en import lexeme, tenses from pattern.en import pluralize, singularize import sqlite3 import hashlib nlp = spacy.load('en_core_w...
4,204
Given the following text description, write Python code to implement the functionality described below step by step Description: On this notebook the initial steps towards solving the capstone project will be taken. Some data gathering and others... Step1: Getting the data Step2: So, Google has a limit of 15 years o...
Python Code: import yahoo_finance import requests import datetime def print_unix_timestamp_date(timestamp): print( datetime.datetime.fromtimestamp( int(timestamp) ).strftime('%Y-%m-%d %H:%M:%S') ) print_unix_timestamp_date("1420077600") print_unix_timestamp_date("1496113200") EXAMPLE...
4,205
Given the following text description, write Python code to implement the functionality described below step by step Description: Day 1 Step1: Question 1 Find the two entries that sum to 2020 and then multiply those two numbers together. Step2: Question 2 What is the product of the three entries that sum to 2020?
Python Code: input_f = './input.txt' # Read expenses expenses = set() with open(input_f, 'r') as fd: for line in fd: expenses.add(int(line.strip())) Explanation: Day 1 End of explanation # Find 2 expenses that add up to 2020 and get their product stop = 0 for exp1 in expenses: for exp2 in expenses: ...
4,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 1 Step1: Load house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2: Split data into training and testing ...
Python Code: import graphlab Explanation: Regression Week 1: Simple Linear Regression In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will: * Use graphlab SArray and SFrame functions to compute important summary statistics * Write a...
4,207
Given the following text description, write Python code to implement the functionality described below step by step Description: Load in the stopwords file. These are common words which we wish to exclude when performing comparisons (a, an, the, etc). Every word is separated by a new line. Step1: Load in the data fro...
Python Code: stopWordsFile = "en.txt" with open(stopWordsFile) as f: stoplist = [x.strip('\n') for x in f.readlines()] Explanation: Load in the stopwords file. These are common words which we wish to exclude when performing comparisons (a, an, the, etc). Every word is separated by a new line. End of explanation # h...
4,208
Given the following text description, write Python code to implement the functionality described below step by step Description: Taller de Python - Estadística en Física Experimental - 1er día Esta presentación/notebook está disponible Step1: Aquí hemos guardado en un espacio de memoria llamado por nosotros "x" la in...
Python Code: x = 5 y = 'Hola mundo!' z = [1,2,3] Explanation: Taller de Python - Estadística en Física Experimental - 1er día Esta presentación/notebook está disponible: Repositorio Github FIFA BsAs (para descargarlo, usen el botón raw o hagan un fork del repositorio) Página web de talleres FIFA BsAs Programar ¿con qué...
4,209
Given the following text description, write Python code to implement the functionality described below step by step Description: Delay Embedding and the MFPT Here, we give an example script, showing the effect of Delay Embedding on a Brownian motion on the Muller-Brown potential, projeted onto its y-axis. This script...
Python Code: import matplotlib.pyplot as plt import numpy as np import pyedgar from pyedgar.data_manipulation import tlist_to_flat, flat_to_tlist, delay_embed, lift_function %matplotlib inline Explanation: Delay Embedding and the MFPT Here, we give an example script, showing the effect of Delay Embedding on a Brownian ...
4,210
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 4c Step1: Set your bucket Step2: Verify CSV files exist In the seventh lab of this series 1b_prepare_data_babyweight, we sampled from BigQuery our train, eval, and test CSV files. Veri...
Python Code: import datetime import os import shutil import matplotlib.pyplot as plt import numpy as np import tensorflow as tf print(tf.__version__) Explanation: LAB 4c: Create Keras Wide and Deep model. Learning Objectives Set CSV Columns, label column, and column defaults Make dataset of features and label from CSV...
4,211
Given the following text description, write Python code to implement the functionality described below step by step Description: A Detailed RBC Model Example Consider the equilibrium conditions for a basic RBC model without labor Step1: Initializing the model in linearsolve To initialize the model, we need to first s...
Python Code: # Import numpy, pandas, linearsolve, matplotlib.pyplot import numpy as np import pandas as pd import linearsolve as ls import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline Explanation: A Detailed RBC Model Example Consider the equilibrium conditions for a basic RBC model without labo...
4,212
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Introduction and Foundations Project 0 Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the s...
Python Code: import numpy as np import pandas as pd # RMS Titanic data visualization code from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few entries of the RMS Ti...
4,213
Given the following text description, write Python code to implement the functionality described. Description: Program to find the Excenters of a Triangle Python3 program for the above approach ; Function to calculate the distance between a pair of points ; Function to calculate the coordinates of the excenters of a tr...
Python Code: from math import sqrt def distance(m , n , p , q ) : return(sqrt(pow(n - m , 2 ) + pow(q - p , 2 ) * 1.0 ) )  def Excenters(x1 , y1 , x2 , y2 , x3 , y3 ) : a = distance(x2 , x3 , y2 , y3 ) b = distance(x3 , x1 , y3 , y1 ) c = distance(x1 , x2 , y1 , y2 ) excenter =[[ 0 , 0 ] for i in range...
4,214
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis of match thread To run this yourself. Two things have to be done manually Step1: Some parameters These need to be changed every match Step2: More parameters These parame...
Python Code: import praw import datetime import pandas as pd import nltk.sentiment.vader import matplotlib.pyplot as plt # Import all relevant packages from bs4 import BeautifulSoup from selenium import webdriver import numpy as np import os Explanation: Sentiment analysis of match thread To run this yourself. Two thin...
4,215
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras debugging tips Author Step1: Now, rather than using it in a end-to-end model directly, let's try to call the layer on some test data Step2: We get the following Step3: Now our code ...
Python Code: import tensorflow as tf from tensorflow.keras import layers class MyAntirectifier(layers.Layer): def build(self, input_shape): output_dim = input_shape[-1] self.kernel = self.add_weight( shape=(output_dim * 2, output_dim), initializer="he_normal", nam...
4,216
Given the following text description, write Python code to implement the functionality described below step by step Description: PDF is garbage In this example, we are looking for a link to some source code Step1: PDF is garbage, continued If we remove line breaks to fix URLs that have been wrapped, we discover that...
Python Code: urlre = re.compile( '(?P<url>https?://[^\s]+)' ) for page in doc : print urlre.findall( page ) Explanation: PDF is garbage In this example, we are looking for a link to some source code : http://prodege.jgi-psf.org//downloads/src However, in the PDF, the URL is line wrapped, so the src is lost. End of ...
4,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Topic Modeling with MALLET We'd like to test how Taylor Salo integrated MALLET into NeuroSynth, and whether that integration works in a docker container. First, let's import some dependencie...
Python Code: from bs4 import BeautifulSoup import pandas as pd with open('../neurosynth/tests/data/yarkoni_pubmed.xml') as infile: xml_file = infile.read() soup = BeautifulSoup(xml_file, 'lxml') try: assert type(soup) == BeautifulSoup except AssertionError: print('Check file type! Must be HTML or XML.') tit...
4,218
Given the following text description, write Python code to implement the functionality described below step by step Description: CollateX and XML, Part 2 David J. Birnbaum (&#100;&#106;&#98;&#112;&#105;&#116;&#116;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;, http Step1: The WitnessSet class represents al...
Python Code: from collatex import * from lxml import etree import json,re Explanation: CollateX and XML, Part 2 David J. Birnbaum (&#100;&#106;&#98;&#112;&#105;&#116;&#116;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;, http://www.obdurodon.org), 2015-06-29 This example collates a single line of XML from fou...
4,219
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Hub Authors. Step1: <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: You will use the AdamW optimizer from t...
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,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Working With Sessions Import the LArray library Step1: Three Kinds Of Sessions They are three ways to group objects in LArray Step2: CheckedSession The syntax to define a checked-session i...
Python Code: %xmode Minimal from larray import * Explanation: Working With Sessions Import the LArray library: End of explanation # define some scalars, axes and arrays variant = 'baseline' country = Axis('country=Belgium,France,Germany') gender = Axis('gender=Male,Female') time = Axis('time=2013..2017') population = z...
4,221
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is part of the clifford documentation Step1: We'll create copies of the point and line reflected in the circle, using $X = C\hat X\tilde C$, where $\hat X$ is the grade involu...
Python Code: from clifford.g2c import * point = up(2*e1+e2) line = up(3*e1 + 2*e2) ^ up(3*e1 - 2*e2) ^ einf circle = up(e1) ^ up(-e1 + 2*e2) ^ up(-e1 - 2*e2) Explanation: This notebook is part of the clifford documentation: https://clifford.readthedocs.io/. Visualization tools In this example we will look at some exter...
4,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Parsing tsv files and populating the database Step1: Inspecting the first few lines of the file, we get a feel for this data schema. Mongo Considerations Step2: |Number|Name| Name | Positi...
Python Code: osu_roster_filepath = '../data/osu_roster.csv' Explanation: Parsing tsv files and populating the database End of explanation !head {osu_roster_filepath} Explanation: Inspecting the first few lines of the file, we get a feel for this data schema. Mongo Considerations: - can specify categories for validation...
4,223
Given the following text description, write Python code to implement the functionality described below step by step Description: NER using Data Programming Project Mars Target Encyclopedia This notebook does not explain much, however, the exaplanations are found in the original notebook(s) https Step2: Load all data ...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline from snorkel import SnorkelSession import os import numpy as np import re, string import codecs # Open Session session = SnorkelSession() Explanation: NER using Data Programming Project Mars Target Encyclopedia This notebook does not explain much, howev...
4,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Two-Level Step2: We'll just check that the pulse area is what we want. Step3: Solve the Problem Step4: Plot Output Step5: Analysis The $6 \pi$ sech pulse breaks up into three $2 \...
Python Code: import numpy as np SECH_FWHM_CONV = 1./2.6339157938 t_width = 1.0*SECH_FWHM_CONV # [τ] print('t_width', t_width) mb_solve_json = { "atom": { "fields": [ { "coupled_levels": [[0, 1]], "rabi_freq_t_args": { "n_pi": 6.0, "centre": 0.0, "width": %f ...
4,225
Given the following text description, write Python code to implement the functionality described below step by step Description: Spectral Line Data Cubes in Astronomy - Part 1 In this notebook we will introduce spectral line data cubes in astronomy. They are a convenient way to store many spectra at points in the sky....
Python Code: %matplotlib inline import matplotlib.pyplot as plt Explanation: Spectral Line Data Cubes in Astronomy - Part 1 In this notebook we will introduce spectral line data cubes in astronomy. They are a convenient way to store many spectra at points in the sky. Much like having a spectrum at every pixel in a CCD....
4,226
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: テンソルと演算 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: テンソル テンソルは多次元の配列です。NumPy ndarray オブ...
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,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Using deep features to build an image classifier Fire up GraphLab Create Step1: Load a common image analysis dataset We will use a popular benchmark dataset in computer vision called CIFAR-...
Python Code: import graphlab Explanation: Using deep features to build an image classifier Fire up GraphLab Create End of explanation image_train = graphlab.SFrame('image_train_data/') image_test = graphlab.SFrame('image_test_data/') Explanation: Load a common image analysis dataset We will use a popular benchmark data...
4,228
Given the following text description, write Python code to implement the functionality described below step by step Description: Matérn Spectral Mixture (MSM) kernel Gaussian process priors for pitch detection in polyphonic music Learning kernels in frequency domain Written by Pablo A. Alvarado, Centre for Digital Mus...
Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (16, 4) import numpy as np import scipy as sp import scipy.io as sio import scipy.io.wavfile as wav from scipy import signal from scipy.fftpack import fft import gpflow import GPitch sf, y = wav.rea...
4,229
Given the following text description, write Python code to implement the functionality described below step by step Description: 练习 1:仿照求 ∑mi=1i+∑ni=1i+∑ki=1i∑i=1mi+∑i=1ni+∑i=1ki 的完整代码,写程序,可求m!+n!+k! Step1: 练习 2:写函数可返回1-1/3+1/5-1/7...的前n项的和。在主程序中,分别令n=1000及100000,打印4倍该函数的和。 Step2: 练习 3:将task3中的练习1及练习4改写为函数,并进行调用。 St...
Python Code: def product_sum(end): i = 1 total_n = 1 while i < end: i += 1 total_n *= i return total_n m = int(input("请输入第1个整数,以回车结束:")) n = int(input("请输入第2个整数,以回车结束:")) k = int(input("请输入第3个整数,以回车结束:")) print("最终的和是:",product_sum(m)+product_sum(n)+product_sum(k)) Explanation: 练习 1...
4,230
Given the following text description, write Python code to implement the functionality described below step by step Description: The focus of this notebook is refactoring a loop that - gets user input - quits if that input matches some sentinel value - processes the user input The interesting part starts around cell #...
Python Code: from functools import partial def convert(s): converters = (int, float) for converter in converters: try: value = converter(s) except ValueError: pass else: return value return s def process_input(s): value = convert(...
4,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Set up data We're working with the movielens data, which contains one rating per row, like this Step1: Just for display purposes, let's read in the movie names too. Step2: We update the mo...
Python Code: ratings = pd.read_csv(path+'ratings.csv') ratings.head() len(ratings) Explanation: Set up data We're working with the movielens data, which contains one rating per row, like this: End of explanation movie_names = pd.read_csv(path+'movies.csv').set_index('movieId')['title'].to_dict() users = ratings.userId....
4,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with HPE IMC API for Custom Views In this notebook, we will be covering the basics of using the pyhpimc python module to access the RESTFUL interface ( eAPI ) of the HPE IMC Network ...
Python Code: import csv import time from pyhpeimc.auth import * from pyhpeimc.plat.groups import * from pyhpeimc.version import * 2+34 Explanation: Working with HPE IMC API for Custom Views In this notebook, we will be covering the basics of using the pyhpimc python module to access the RESTFUL interface ( eAPI ) of th...
4,233
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's play iPython and BASH a bit count number of paths in $PATH Step1: which is the same as the following command in BASH shell Step2: change the language environment Step3: look for fil...
Python Code: path=!echo $PATH print path path[0].split(":") print len(path[0].split(":")) Explanation: Let's play iPython and BASH a bit count number of paths in $PATH: End of explanation !echo $PATH|tr ":" " "|wc -w Explanation: which is the same as the following command in BASH shell: End of explanation !locale !expo...
4,234
Given the following text description, write Python code to implement the functionality described below step by step Description: graded = 8/10 Homework 6 Step1: Problem set #2 Step2: Problem set #3 Step3: Problem set #4 Step4: Problem set #5 Step5: Specifying a field other than name, area or elevation for the sor...
Python Code: import requests data = requests.get('http://localhost:5000/lakes').json() print(len(data), "lakes") for item in data[:10]: print(item['name'], "- elevation:", item['elevation'], "m / area:", item['area'], "km^2 / type:", item['type']) Explanation: graded = 8/10 Homework 6: Web Applications For this hom...
4,235
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression with Differential Privacy We start by importing the required libraries and modules and collecting the data that we need from the Adult dataset. Step1: Let's also collect...
Python Code: import diffprivlib.models as dp import numpy as np from sklearn.linear_model import LogisticRegression X_train = np.loadtxt("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", usecols=(0, 4, 10, 11, 12), delimiter=", ") y_train = np.loadtxt("https://archive...
4,236
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing the trained weight matrices (not in an ensemble) Step1: Load the weight matrices from the training Step2: Visualize the digit from one hot representation through the activity weigh...
Python Code: import nengo import numpy as np import cPickle import matplotlib.pyplot as plt from matplotlib import pylab import matplotlib.animation as animation from scipy import linalg %matplotlib inline import scipy.ndimage Explanation: Testing the trained weight matrices (not in an ensemble) End of explanation #Wei...
4,237
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka last updated Step1: Using the code above, we created two $3\times20$ datasets - one dataset for each class $\omega_1$ and $\omega_2$ - where each column can be pictured a...
Python Code: import numpy as np np.random.seed(0) mu_vec1 = np.array([0, 0, 0]) cov_mat1 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20).T assert class1_sample.shape == (3, 20), "The matrix has not the dimensions 3x20" mu_vec2 = np.array([1, 1, 1]) cov_...
4,238
Given the following text description, write Python code to implement the functionality described below step by step Description: Using third-party Native Libraries Sometimes, the functionnality you need are onmy available in third-party native libraries. There's still an opportunity to use them from within Pythran, us...
Python Code: import pythran %load_ext pythran.magic %%pythran #pythran export pythran_cbrt(float64(float64), float64) def pythran_cbrt(libm_cbrt, val): return libm_cbrt(val) Explanation: Using third-party Native Libraries Sometimes, the functionnality you need are onmy available in third-party native libraries. Th...
4,239
Given the following text description, write Python code to implement the functionality described below step by step Description: Image Captioning To perform image captioning we are going to apply an approach similar to the work described in references [1],[2], and [3]. The approach applied here uses a recurrent neural...
Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import time import numpy as np import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.framework import dtypes #import reader import collections imp...
4,240
Given the following text description, write Python code to implement the functionality described below step by step Description: REPL Basics <a href="http Step1: Persistent Storage NOTE Step2: Help To get help for the various classes and their respective methods, run Step3: To get help on a specific method in that ...
Python Code: import chip.native import pkgutil module = pkgutil.get_loader('chip.ChipReplStartup') %run {module.path} Explanation: REPL Basics <a href="http://35.236.121.59/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fproject-chip%2Fconnectedhomeip&urlpath=lab%2Ftree%2Fconnectedhomeip%2Fdocs%2Fguides%2Fre...
4,241
Given the following text description, write Python code to implement the functionality described below step by step Description: Q1 Step1: astropy convolution How do you convolve fast? see, e.g., http Step2: Speed of DFT Step3: faster fftw Step4: Q3 Install a module, then keep editing it. python setup.py develop U...
Python Code: x = StringIO.StringIO() arr = np.arange(10) np.savetxt(x,arr, header='test', comments="") x.seek(0) print(x.read()) with open('file.txt','w') as f: f.write(x.getvalue()) %%bash cat file.txt Explanation: Q1: Saving a table to text with a header with no preceding "#" Also, demo StringIO End of explanatio...
4,242
Given the following text description, write Python code to implement the functionality described below step by step Description: 如何爬取Facebook粉絲頁資料 (comments) ? 基本上是透過 Facebook Graph API 去取得粉絲頁的資料,但是使用 Facebook Graph API 還需要取得權限,有兩種方法 Step1: 第一步 - 要先取得應用程式的帳號,密碼 (app_id, app_secret) 第二步 - 輸入要分析的粉絲團的 id [教學]如何申請建立 Fac...
Python Code: # 載入python 套件 import requests import datetime import time import pandas as pd Explanation: 如何爬取Facebook粉絲頁資料 (comments) ? 基本上是透過 Facebook Graph API 去取得粉絲頁的資料,但是使用 Facebook Graph API 還需要取得權限,有兩種方法 : 第一種是取得 Access Token 第二種是建立 Facebook App的應用程式,用該應用程式的帳號,密碼當作權限 兩者的差別在於第一種會有時效限制,必須每隔一段時間去更新Access Token,才能使用 A...
4,243
Given the following text description, write Python code to implement the functionality described. Description: Area of the biggest possible rhombus that can be inscribed in a rectangle Function to find the area of the biggest rhombus ; the length and breadth cannot be negative ; area of the rhombus ; Driver code
Python Code: def rhombusarea(l , b ) : if(l < 0 or b < 0 ) : return - 1  return(l * b ) / 2  if __name__== ' __main __' : l = 16 b = 6 print(rhombusarea(l , b ) ) 
4,244
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercício 01 Step1: Exercício 02 Step2: Exercício 03 Step3: Exercício 04
Python Code: G2 = nx.barabasi_albert_graph(6,3) nx.draw_shell(G2) pos = nx.shell_layout(G2) labels = dict( enumerate(G2.nodes()) ) nx.draw_networkx_labels(G2,pos,labels,font_size=16); print "Dist. media: ", nx.average_shortest_path_length(G2) print "Diametro: ", nx.diameter(G2) print "Coef. Agrupamento médio: ", nx.ave...
4,245
Given the following text description, write Python code to implement the functionality described below step by step Description: Definition(s) The Karatsuba algorithm is a fast multiplication algorithm. It reduces the multiplication of two n-digit numbers to at most ${\displaystyle n^{\log _{2}3}\approx n^{1.585}}$ s...
Python Code: import numpy as np # used for generating random numbers Explanation: Definition(s) The Karatsuba algorithm is a fast multiplication algorithm. It reduces the multiplication of two n-digit numbers to at most ${\displaystyle n^{\log _{2}3}\approx n^{1.585}}$ single-digit multiplications in general. End of ...
4,246
Given the following text description, write Python code to implement the functionality described below step by step Description: Two Topics Coupled example Import Python built-in functions we need to run and plot the game Step1: Set up inline matplotlib Step2: Import Game Modules From a Given Path User have to edit ...
Python Code: import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.image as mpimg from matplotlib import rcParams import seaborn as sb Explanation: Two Topics Coupled example Import Python built-in functions...
4,247
Given the following text description, write Python code to implement the functionality described below step by step Description: 机器学习纳米学位 非监督学习 项目 3 Step1: 分析数据 在这部分,你将开始分析数据,通过可视化和代码来理解每一个特征和其他特征的联系。你会看到关于数据集的统计描述,考虑每一个属性的相关性,然后从数据集中选择若干个样本数据点,你将在整个项目中一直跟踪研究这几个数据点。 运行下面的代码单元给出数据集的一个统计描述。注意这个数据集包含了6个重要的产品类型:'Fresh', ...
Python Code: # 检查你的Python版本 from sys import version_info if version_info.major != 3: raise Exception('请使用Python 3.x 来完成此项目') # 引入这个项目需要的库 import numpy as np import pandas as pd import visuals as vs from IPython.display import display # 使得我们可以对DataFrame使用display()函数 # 设置以内联的形式显示matplotlib绘制的图片(在notebook中显示更美观) %matp...
4,248
Given the following text description, write Python code to implement the functionality described below step by step Description: How to solve H(div) PDEs in practice? This document explores the current, easily accessible, state of the art for solving an $H(\rm div) \times L^2$ formulation of Poisson's problem or equiv...
Python Code: # Import useful libraries from dolfin import * import numpy import pylab # Plot inline in this notebook %matplotlib inline # Set basic optimization parameters for FEniCS parameters["form_compiler"]["representation"] = "uflacs" parameters["form_compiler"]["cpp_optimize"] = True #parameters["plotting_backend...
4,249
Given the following text description, write Python code to implement the functionality described below step by step Description: NoSQL (Neo4j) (sesión 7) Esta hoja muestra cómo acceder a bases de datos Neo4j y también a conectar la salida con Jupyter. Se puede utilizar el propio interfaz de Neo4j también en la direcci...
Python Code: from pprint import pprint as pp import pandas as pd import matplotlib.pyplot as plt import matplotlib %matplotlib inline matplotlib.style.use('ggplot') Explanation: NoSQL (Neo4j) (sesión 7) Esta hoja muestra cómo acceder a bases de datos Neo4j y también a conectar la salida con Jupyter. Se puede utilizar e...
4,250
Given the following text description, write Python code to implement the functionality described below step by step Description: 2 Step1: 4 Step2: 5 Step3: 6
Python Code: f = open("dq_unisex_names.csv", "r") data = f.read() print(data) Explanation: 2: Unisex names 3: Read the file into string Instructions Use the open() function to return a File object with the parameters: r for read mode dq_unisex_names.csv for the file name Then use the read() method of the File object to...
4,251
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--BOOK_INFORMATION--> <img align="left" style="padding-right Step1: As we have seen several times throughout this section, the simplest colorbar can be created with the plt.colorbar funct...
Python Code: import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline import numpy as np Explanation: <!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png"> This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; t...
4,252
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 2 Step1: In this case instead loading a geo_data object directly, we will create one. The main atributes we need to pass are Step2: You can visualize the points in 3D (work in prog...
Python Code: # These two lines are necessary only if gempy is not installed import sys, os sys.path.append("../") # Importing gempy import gempy as gp # Embedding matplotlib figures into the notebooks %matplotlib inline # Aux imports import numpy as np Explanation: Chapter 2: A real example. Importing data and setting ...
4,253
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples and Exercises from Think Stats, 2nd Edition http Step1: Examples One more time, I'll load the data from the NSFG. Step2: And compute the distribution of birth weight for first bab...
Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import nsfg import first import thinkstats2 import thinkplot Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thinkstats2.com Copyright 2016 Allen B. Downey MIT License: https://opensource.org/lice...
4,254
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 8 | Anomaly Detection Step1: Part 1 Step2: Part 2 Step3: Visualize the fit. Step4: Part 3 Step5: Best epsilon and F1 found using cross-validation (F1 should be about 0.899e-5) ...
Python Code: import numpy as np import matplotlib.pyplot as plt import scipy.io from scipy.stats import multivariate_normal %matplotlib inline #%qtconsole Explanation: Exercise 8 | Anomaly Detection End of explanation ex7data1 = scipy.io.loadmat('ex8data1.mat') X = ex7data1['X'] Xval = ex7data1['Xval'] yval = ex7data1[...
4,255
Given the following text description, write Python code to implement the functionality described below step by step Description: Benchmarking Performance and Scaling of Python Clustering Algorithms There are a host of different clustering algorithms and implementations thereof for Python. The performance and scaling c...
Python Code: import hdbscan import debacl import fastcluster import sklearn.cluster import scipy.cluster import sklearn.datasets import numpy as np import pandas as pd import time import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline sns.set_context('poster') sns.set_palette('Paired', 10) sns.set_col...
4,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 7 Step1: Here, range() will return a number of integers, starting from zero, up to (but not including) the number which we pass as an argument to the function. Using range() is of c...
Python Code: for i in range(10): print(i) Explanation: Chapter 7: More on Loops In the previous chapters we have often discussed the powerful concept of looping in Python. Using loops, we can easily repeat certain actions when coding. With for-loops, for instance, it is really easy to visit the items in a list in a...
4,257
Given the following text description, write Python code to implement the functionality described below step by step Description: Efficient Computation of Powers The function power takes two natural numbers $m$ and $n$ and computes $m^n$. Our first implementation is inefficient and takes $n-1$ multiplication to comput...
Python Code: def power(m, n): r = 1 for i in range(n): r *= m return r power(2, 3), power(3, 2) %%time p = power(3, 500000) p Explanation: Efficient Computation of Powers The function power takes two natural numbers $m$ and $n$ and computes $m^n$. Our first implementation is inefficient and takes $...
4,258
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 13 Step1: With NumPy arrays, all the same functionality you know and love from lists is still there. Step2: These operations all work whether you're using Python lists or NumPy arr...
Python Code: li = ["this", "is", "a", "list"] print(li) print(li[1:3]) # Print element 1 (inclusive) to 3 (exclusive) print(li[2:]) # Print element 2 and everything after that print(li[:-1]) # Print everything BEFORE element -1 (the last one) Explanation: Lecture 13: Array Indexing, Slicing, and Broadcasting CSCI 1...
4,259
Given the following text description, write Python code to implement the functionality described below step by step Description: Inspect Raw Netcdf Playing around with efficient ways to merge and view netcdf data from the tower. This ipython notebook depends on the python script of the same name. Step1: Using the xra...
Python Code: usr = 'Julia' FILEDIR = 'C:/Users/%s/Dropbox (PE)/KenyaLab/Data/Tower/TowerData/'%usr NETCDFLOC = FILEDIR + 'raw_netcdf_output/' DATALOC = 'F:/towerdata/' Explanation: Inspect Raw Netcdf Playing around with efficient ways to merge and view netcdf data from the tower. This ipython notebook depends on the py...
4,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Parametric Regression Notebook version Step1: A quick note on the mathematical notation In this notebook we will make extensive use of probability distributions. In general, we wil...
Python Code: # Import some libraries that will be necessary for working with data and displaying plots # To visualize plots in the notebook %matplotlib inline from IPython import display import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy.io # To read matlab files import pylab imp...
4,261
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction To Probabalistic Graph Models Scott Hendrickson 2016-Aug-19 Requirements Step1: Why is this formalism a useful probabalistic problem solving tool? This tool can model a much ge...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import networkx as nx G=nx.DiGraph() G.add_edge('sex','height',weight=0.6) nx.draw_networkx(G, node_color='y',node_size=2000, width=3) plt.axis('off') plt.show() Explanation: Introduction To Probabalistic Graph Models Scott Hendrickson 2016-Aug-19 Requirem...
4,262
Given the following text description, write Python code to implement the functionality described below step by step Description: Ok, we've had a little peek at our dataset, lets prep it for our model. Step1: Prep is done, time for the model. Step2: We've defined the cost and accuracy functions, time to train our mod...
Python Code: randinds = np.random.permutation(len(digits.target)) # shuffle the values from sklearn.utils import shuffle data, targets = shuffle(digits.data, digits.target, random_state=0) # scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler().fit(data) data_scaled = scaler.transfor...
4,263
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute and visualize ERDS maps This example calculates and displays ERDS maps of event-related EEG data. ERDS (sometimes also written as ERD/ERS) is short for event-related desynchronizatio...
Python Code: # Authors: Clemens Brunner <clemens.brunner@gmail.com> # Felix Klotzsche <klotzsche@cbs.mpg.de> # # License: BSD-3-Clause Explanation: Compute and visualize ERDS maps This example calculates and displays ERDS maps of event-related EEG data. ERDS (sometimes also written as ERD/ERS) is short for eve...
4,264
Given the following text description, write Python code to implement the functionality described below step by step Description: https Step1: Request 2 Step2: Request 3 Step3: Request 4 Step4: On a side note
Python Code: fullbase = requests.compat.urljoin(baseurl, endpoint_datatypes) r = requests.get( fullbase, headers=custom_headers, # params={'limit':1000}, params={'limit':1000, 'datasetid':"NORMAL_DLY"}, ) r.headers r.text json.loads(r.text) Explanation: https://www.ncdc.noaa.gov/cdo-web/api/v2/data?data...
4,265
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Network Part2 Step1: Normalization Q1. Apply l2_normalize to x. Step2: Q2. Calculate the mean and variance of x based on the sufficient statistics. Step3: Q3. Calculate the mean an...
Python Code: from __future__ import print_function import numpy as np import tensorflow as tf import matplotlib.pyplot as plt %matplotlib inline from datetime import date date.today() author = "kyubyong. https://github.com/Kyubyong/tensorflow-exercises" tf.__version__ np.__version__ Explanation: Neural Network Part2 En...
4,266
Given the following text description, write Python code to implement the functionality described below step by step Description: Catching errors and unit tests In this tutorial are few examples how catch error and how to perform unit tests in Python. When you code in Python, keep in mind Step1: An example of correct ...
Python Code: def sum_together1(a, b): return a + b Explanation: Catching errors and unit tests In this tutorial are few examples how catch error and how to perform unit tests in Python. When you code in Python, keep in mind: Errors should never pass silently. Unless explicitly silenced. (<a href="https://www.python...
4,267
Given the following text description, write Python code to implement the functionality described. Description: Number of triangles that can be formed with given N points Python3 implementation of the above approach ; This function returns the required number of triangles ; Hash Map to store the frequency of slope corre...
Python Code: from collections import defaultdict from math import gcd def countTriangles(P , N ) : mp = defaultdict(lambda : 0 ) ans = 0 for i in range(0 , N ) : mp . clear() for j in range(i + 1 , N ) : X = P[i ][0 ] - P[j ][0 ] Y = P[i ][1 ] - P[j ][1 ] g = gcd(X , Y ) X //= g Y //= g mp ...
4,268
Given the following text description, write Python code to implement the functionality described below step by step Description: 분류(classification) 성능 평가 분류 문제는 회귀 분석과 달리 모수에 대한 t-검정, 신뢰 구간(confidence interval) 추정 등이 쉽지 않기 때문에 이를 보완하기 위해 다양한 성능 평가 기준이 필요하다. Scikit-Learn 에서 지원하는 분류 성능 평가 명령 sklearn.metrics 서브 패키지 confu...
Python Code: from sklearn.metrics import confusion_matrix y_true = [2, 0, 2, 2, 0, 1] y_pred = [0, 0, 2, 2, 0, 2] confusion_matrix(y_true, y_pred) y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"]) Expl...
4,269
Given the following text description, write Python code to implement the functionality described below step by step Description: Buildings / Addresses I want to understand how buildings and addresses are represented in OSM data. Required reading Step1: Nodes tagged as buildings / with addresses For the Isle of Wight ...
Python Code: import osmdigest.digest as digest Explanation: Buildings / Addresses I want to understand how buildings and addresses are represented in OSM data. Required reading: http://wiki.openstreetmap.org/wiki/Addresses End of explanation import os #filename = os.path.join("//media", "disk", "OSM_Data", "isle-of-wig...
4,270
Given the following text description, write Python code to implement the functionality described. Description: Count of subarrays which forms a permutation from given Array elements Function returns the required count ; Store the indices of the elements present in A [ ] . ; Store the maximum and minimum index of the el...
Python Code: def PermuteTheArray(A , n ) : arr =[0 ] * n for i in range(n ) : arr[A[i ] - 1 ] = i  mini = n maxi = 0 count = 0 for i in range(n ) : mini = min(mini , arr[i ] ) maxi = max(maxi , arr[i ] ) if(maxi - mini == i ) : count += 1   return count  if __name__== "__main __": A...
4,271
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 DeepMind Technologies Limited. Step1: Environments <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step3: Stack Before Writing Th...
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,272
Given the following text description, write Python code to implement the functionality described below step by step Description: Iris Dataset From Wikipedia Step1: read_html Wikipedia has the same dataset as a html table at https Step2: Plotting Let's use pandas to plot the sepal_length vs the petal_length. Step3: ...
Python Code: import pandas as pd url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" df = pd.read_csv(url,names=['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'spe...
4,273
Given the following text description, write Python code to implement the functionality described below step by step Description: 통계적 사고 (2판) 연습문제 (thinkstats2.com, think-stat.xwmooc.org)<br> Allen Downey / 이광춘(xwMOOC) Step1: 연습문제 5.1 BRFSS 데이터셋에서 (5.4절 참조), 신장 분포는 대략 남성에 대해 모수 µ = 178 cm, σ = 7.7cm을 갖는 정규분포이며, 여성에 대해...
Python Code: from __future__ import print_function, division import thinkstats2 import thinkplot %matplotlib inline Explanation: 통계적 사고 (2판) 연습문제 (thinkstats2.com, think-stat.xwmooc.org)<br> Allen Downey / 이광춘(xwMOOC) End of explanation import scipy.stats Explanation: 연습문제 5.1 BRFSS 데이터셋에서 (5.4절 참조), 신장 분포는 대략 남성에 대해 모...
4,274
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Model Evaluation & Validation Project 1 Step1: Data Exploration In this first section of this project, you will make a cursory investigation about the B...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd import visuals as vs # Supplementary code from sklearn.cross_validation import ShuffleSplit # Pretty display for notebooks %matplotlib inline # Load the Boston housing dataset data = pd.read_csv('housing.csv') prices = dat...
4,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: 映画レビューのテキスト分類 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: 感情分析 このノートブックでは、映画レビューのテキストを使...
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,276
Given the following text description, write Python code to implement the functionality described below step by step Description: 3D Shape Classification with Sublevelset Filtrations In this module, we will explore how TDA can be used to classify 3D shapes. We will begine by clustering triangle meshes of humans in dif...
Python Code: import numpy as np %matplotlib notebook import scipy.io as sio from scipy import sparse import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys sys.path.append("pyhks") from HKS import * from GeomUtils import * from ripser import ripser from persim import plot_diagrams, wassers...
4,277
Given the following text description, write Python code to implement the functionality described below step by step Description: Create datasets for the Content-based Filter This notebook builds the data we will use for creating our content based model. We'll collect the data via a collection of SQL queries from the p...
Python Code: import os import tensorflow as tf import numpy as np from google.cloud import bigquery PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # do not chang...
4,278
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro to pychord Create a Chord Step1: Transpose a Chord Step2: Get Component Notes Step3: Find Chords Step4: Chord Progressions Step5: Create a Chord from Note Index in a Scale Step6: ...
Python Code: c = mus.Chord("Am7") print(c.info()) Explanation: Intro to pychord Create a Chord End of explanation c = mus.Chord("C") c.transpose(2) c c = mus.Chord("Dm/G") c.transpose(3) c Explanation: Transpose a Chord End of explanation c = mus.Chord("Dm7") c.components() Explanation: Get Component Notes End of expla...
4,279
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Data Seaborn comes with built-in data sets! Step2: distplot The distplot shows the distribution of a univariate set of observations. Step3: To remove the kde layer an...
Python Code: import seaborn as sns %matplotlib inline Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Distribution Plots Let's discuss some plots that allow us to visualize the distribution of a data set. These plots are: distplot jointplot pairplot rugplot kdeplot Imports ...
4,280
Given the following text description, write Python code to implement the functionality described below step by step Description: Performing Clean-up and Analysis on Native Ad Data Scraped "From Around the Web" Step1: Data Load and Cleaning Step2: As a side note, the headlines from zergnet all have some newlines we n...
Python Code: import pandas as pd from datetime import datetime import dateutil import matplotlib.pyplot as plt from IPython.core.display import display, HTML import re from urllib.parse import urlparse import json Explanation: Performing Clean-up and Analysis on Native Ad Data Scraped "From Around the Web" End of expla...
4,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Introduction and Foundations Project 0 Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the s...
Python Code: import numpy as np import pandas as pd # RMS Titanic data visualization code from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few entries of the RMS Ti...
4,282
Given the following text description, write Python code to implement the functionality described below step by step Description: Using sklearn's Iris Dataset with neon Tony Reina<br> 28 JUNE 2017 Here's an example of how we can load one of the standard sklearn datasets into a neon model. We'll be using the iris datase...
Python Code: from sklearn import datasets iris = datasets.load_iris() X = iris.data Y = iris.target nClasses = len(iris.target_names) # Setosa, Versicolour, and Virginica iris species Explanation: Using sklearn's Iris Dataset with neon Tony Reina<br> 28 JUNE 2017 Here's an example of how we can load one of the stand...
4,283
Given the following text description, write Python code to implement the functionality described below step by step Description: Addition Similarity Step1: Question Step2: Top 10 most similar additions Step3: 10 Least Similar additions Step4: Similarity of a specific combo Step5: But is that good or bad? How does...
Python Code: # Import libraries import numpy as np import pandas as pd # Import the data import WTBLoad wtb = WTBLoad.load() Explanation: Addition Similarity End of explanation import math # Square the difference of each row, and then return the mean of the column. # This is the average difference between the two. # I...
4,284
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 6.2 - Using a pre-trained model with Keras In this section of the lab, we will load the model we trained in the previous section, along with the training data and mapping dictionaries, a...
Python Code: import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import LSTM from keras.callbacks import ModelCheckpoint from keras.utils import np_utils import sys import re import pickle Explanation: Lab 6.2 - Using a pre-trained mod...
4,285
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing argmax in Python Which fruit is the most frequent in this basket? Step1: Returns a tuple, let's get its first element. Step2: Most common element Which item appears most times in...
Python Code: basket = [("apple", 12), ("pear", 3), ("plum", 14)] max(basket, key=lambda pair: pair[1]) Explanation: Computing argmax in Python Which fruit is the most frequent in this basket? End of explanation max(basket, key=lambda pair: pair[1])[0] Explanation: Returns a tuple, let's get its first element. End of ex...
4,286
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Modular neural nets In the previous exercise, we computed the loss and gradient for a two-layer neural network in a single monolithic function. This isn't very difficult for a small t...
Python Code: # As usual, a bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient from cs231n.layers import * %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image....
4,287
Given the following text description, write Python code to implement the functionality described below step by step Description: Dimensionality of the inputs to the filter One of the main strengths of PyMC3 is its dependence on Theano. Theano allows to compute arithmetic operations on arbitrary tensors. This might not...
Python Code: import numpy as np import theano import theano.tensor as tt import kalman import matplotlib.pyplot as plt import seaborn as sns sns.set_style("whitegrid") %matplotlib inline # True values T = 500 # Time steps sigma2_eps0 = 3 # Variance of the observatio...
4,288
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 6 - Data Retrieval Functions Step1: Data Retrieval globus_download If you want to access the raw data underlying entries in MDF, you can use globus_download() and provide the results f...
Python Code: from mdf_forge.forge import Forge mdf = Forge() Explanation: Part 6 - Data Retrieval Functions End of explanation # NBVAL_SKIP # Running this example will save a file in the current directory. res = mdf.search("dft.converged:true AND mdf.resource_type:record", limit=10) mdf.globus_download(res) Explanation...
4,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic damage detection in Wikipedia This notebook demonstrates the basic contruction of a vandalism classification system using the revscoring library that we have developed specifically for...
Python Code: # Magical ipython notebook stuff puts the result of this command into a variable revids_f = !wget http://quarry.wmflabs.org/run/65415/output/0/tsv?download=true -qO- revids = [int(line) for line in revids_f[1:]] len(revids) Explanation: Basic damage detection in Wikipedia This notebook demonstrates the ba...
4,290
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Machine Learning 2nd Edition by Sebastian Raschka, Packt Publishing Ltd. 2017 Code Repository Step1: The use of watermark is optional. You can install this IPython extension via "pip...
Python Code: %load_ext watermark %watermark -a "Sebastian Raschka" -u -d -v -p numpy,pandas,sklearn,nltk Explanation: Python Machine Learning 2nd Edition by Sebastian Raschka, Packt Publishing Ltd. 2017 Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition Code License: MIT License Python M...
4,291
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>GarrissonWow</h1> Script to get world of warcraft data and display it in a website. Step1: inpd character name input ut realm an. Step2: If faction is alliance change CSS to BLUE backg...
Python Code: import battlenet import dominate from dominate.tags import * import json import arrow import requests import datetime from battlenet import Character from battlenet import Realm #Realm.to_json() realm = Realm(battlenet.UNITED_STATES, "jubei'thos") realm print realm.is_online() print realm.to_json() rejs =...
4,292
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy Numpy é um pacote fundamental para programação científica com Python. Ele traz consigo uma variedade de operações matemáticas, principalmente referente à operações algébricas com dados...
Python Code: import numpy as np Explanation: NumPy Numpy é um pacote fundamental para programação científica com Python. Ele traz consigo uma variedade de operações matemáticas, principalmente referente à operações algébricas com dados N-dimensionais! End of explanation a = np.array([1, 2, 3]) print(repr(a), a.shape, e...
4,293
Given the following text description, write Python code to implement the functionality described below step by step Description: Sliders Example This is an example of interactive iPython workbook that uses widgets to meaningfully interact with visualization. Step4: 2D Rank Features
Python Code: # Imports import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from collections import OrderedDict from sklearn.pipeline import Pipeline from sklearn.preprocessing import Imputer from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squ...
4,294
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatiotemporal permutation F-test on full sensor data Tests for differential evoked responses in at least one condition using a permutation clustering test. The FieldTrip neighbor templates ...
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # Alex Rockhill <aprockhill@mailbox.org> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # # License: BSD-3-Clause import numpy as np import matplotlib.pyplot as plt from mpl_to...
4,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Urban Networks II Overview of today's topics Step1: 1. Model a study site First, we will identify a study site, model its street network, and calculate some simple indicators. Step2: 2. Si...
Python Code: import geopandas as gpd import matplotlib.pyplot as plt import networkx as nx import numpy as np import osmnx as ox import pandana import pandas as pd from shapely.geometry import Point # consistent randomization np.random.seed(0) # configure OSMnx cache_folder = '../../data/cache2' ox.config(log_console=T...
4,296
Given the following text description, write Python code to implement the functionality described below step by step Description: Quick start guide Installation Stable Fri can be installed via the Python Package Index (PyPI). If you have pip installed just execute the command pip install fri to get the newest stable ve...
Python Code: import numpy as np # fixed Seed for demonstration STATE = np.random.RandomState(123) from fri import genClassificationData Explanation: Quick start guide Installation Stable Fri can be installed via the Python Package Index (PyPI). If you have pip installed just execute the command pip install fri to get t...
4,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting started with TensorFlow (Eager Mode) Learning Objectives - Understand difference between Tensorflow's two modes Step1: Eager Execution Step2: Adding Two Tensors The value of the ...
Python Code: import tensorflow as tf print(tf.__version__) Explanation: Getting started with TensorFlow (Eager Mode) Learning Objectives - Understand difference between Tensorflow's two modes: Eager Execution and Graph Execution - Practice defining and performing basic operations on constant Tensors - Use Tensorf...
4,298
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright &copy; 2019 The TensorFlow Authors. Step1: TensorFlow Model Analysis An Example of a Key TFX Library This example colab notebook illustrates how TensorFlow Model Analysis (TFMA) c...
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,299
Given the following text description, write Python code to implement the functionality described below step by step Description: Tabular core Basic function to preprocess tabular data before assembling it in a DataLoaders. Initial preprocessing Step1: For example if we have a series of dates we can then generate feat...
Python Code: #|export def make_date(df, date_field): "Make sure `df[date_field]` is of the right date type." field_dtype = df[date_field].dtype if isinstance(field_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype): field_dtype = np.datetime64 if not np.issubdtype(field_dtype, np.datetime64): ...