Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
15,900
Given the following text description, write Python code to implement the functionality described below step by step Description: Physiology 1) Using the ion concentrations of interstitial and intracellular compartments and the Nernst equation, calculate the equilibrium potentials for Na+, K+, and Cl- Step1: 2) Assumi...
Python Code: from math import log # RT/F = 26.73 at room temperature rt_div_f = 26.73 nernst = lambda xO, xI, z: rt_div_f/z * log(1.0 * xO / xI) Na_Eq = nernst(145, 15, 1) K_Eq = nernst(4.5, 120, 1) Cl_Eq = nernst(116, 20, -1) print "Na+ equilibrium potential is %.2f mV" % (Na_Eq) print "K+ equilibrium potential is %.2...
15,901
Given the following text description, write Python code to implement the functionality described below step by step Description: Decoding (MVPA) Step1: Transformation classes Scaler The Step2: PSDEstimator The Step3: Source power comodulation (SPoC) Source Power Comodulation ( Step4: Decoding over time This stra...
Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression import mne from mne.datasets import sample from mne.decoding import (SlidingEstimator, GeneralizingEstimator, Sc...
15,902
Given the following text description, write Python code to implement the functionality described below step by step Description: Semi-Monocoque Theory Step1: Import Section class, which contains all calculations Step2: Initialization of sympy symbolic tool and pint for dimension analysis (not really implemented rn a...
Python Code: from pint import UnitRegistry import sympy import networkx as nx import numpy as np import matplotlib.pyplot as plt import sys %matplotlib inline from IPython.display import display Explanation: Semi-Monocoque Theory: corrective solutions End of explanation from Section import Section Explanation: Import S...
15,903
Given the following text description, write Python code to implement the functionality described below step by step Description: From FITS to HDF5 Purpose of this notebook is to get the data to suitable data structure for preprocessing. FITS file format https Step1: HDUs A FITS file is comprised of segmets called Hea...
Python Code: %matplotlib inline import os import glob import random import h5py import astropy.io.fits import numpy as np import matplotlib.pyplot as plt # find the normalized spectra in data_path directory # add all filenames to the list fits_paths FITS_DIR = 'data/ondrejov/' fits_paths = glob.glob(FITS_DIR + '*.fits'...
15,904
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook analyzes the predictions of the trading model. <br/>At different thresholds, how effective is the model at predicting<br/> larger-than-average range days? Step1: This file con...
Python Code: %matplotlib inline import numpy as np import pandas as pd pwd cd output ls Explanation: This notebook analyzes the predictions of the trading model. <br/>At different thresholds, how effective is the model at predicting<br/> larger-than-average range days? End of explanation ranking_frame = pd.read_csv('ra...
15,905
Given the following text description, write Python code to implement the functionality described below step by step Description: Section 5.5 superposition in time. Simulating varying head at x=0 using a sequence of sudden changes of head at $x=0$ and $t=0$ IHE, Delft, 20120-01-06 @T.N.Olsthoorn Context The aquifer is ...
Python Code: import numpy as np from scipy.special import erfc from matplotlib import pyplot as plt from matplotlib import animation, rc from matplotlib.animation import FuncAnimation from matplotlib.patches import PathPatch, Path from IPython.display import HTML from scipy.special import erfc import pdb Explanation: S...
15,906
Given the following text description, write Python code to implement the functionality described below step by step Description: Sampling from a Population The law of averages also holds when the random sample is drawn from individuals in a large population. As an example, we will study a population of flight delay ti...
Python Code: united = Table.read_table('http://inferentialthinking.com/notebooks/united_summer2015.csv') united Explanation: Sampling from a Population The law of averages also holds when the random sample is drawn from individuals in a large population. As an example, we will study a population of flight delay times. ...
15,907
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 1 Step1: Useful pandas summary functions In order to make use of the closed form soltion as well as take advantage of graphlab's built in functions we will review some impor...
Python Code: import pandas as pd import numpy as np dtype_dict = {'bathrooms':float, 'waterfront':int, 'sqft_above':int, 'sqft_living15':float, 'grade':int, 'yr_renovated':int, 'price':float, 'bedrooms':float, 'zipcode':str, 'long':float, 'sqft_lot15':float, 'sqft_living':float, 'floors':s...
15,908
Given the following text description, write Python code to implement the functionality described below step by step Description: pyplearnr demo Here I demonstrate pyplearnr, a wrapper for building/training/validating scikit learn pipelines using GridSearchCV or RandomizedSearchCV. Quick keyword arguments give access t...
Python Code: import pandas as pd df = pd.read_pickle('trimmed_titanic_data.pkl') df.info() Explanation: pyplearnr demo Here I demonstrate pyplearnr, a wrapper for building/training/validating scikit learn pipelines using GridSearchCV or RandomizedSearchCV. Quick keyword arguments give access to optional feature selecti...
15,909
Given the following text description, write Python code to implement the functionality described below step by step Description: Regressão Linear Este notebook mostra uma implementação básica de Regressão Linear e o uso da biblioteca MLlib do PySpark para a tarefa de regressão na base de dados Million Song Dataset do ...
Python Code: # carregar base de dados import os.path fileName = os.path.join('Data', 'millionsong.txt') numPartitions = 2 rawData = sc.textFile(fileName, numPartitions) # EXERCICIO numPoints = rawData.count() print (numPoints) samplePoints = rawData.take(5) print (samplePoints) # TEST Load and check the data (1a) asser...
15,910
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Map <script type="text/javascript"> localStorage.setItem('language', 'language-py') </script> <table align="left" style="margin-right Step2: Examples In the following...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License") # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this fi...
15,911
Given the following text description, write Python code to implement the functionality described below step by step Description: Formulas Step1: import convention Step2: OLS regression using formulas Step3: Categorical variables Looking at the summary printed above, notice that patsy determined that elements of Reg...
Python Code: import numpy as np import statsmodels.api as sm Explanation: Formulas: Fitting models using R-style formulas loading modules and fucntions End of explanation from statsmodels.formula.api import ols import statsmodels.formula.api as smf dir(smf) Explanation: import convention End of explanation dta = sm.dat...
15,912
Given the following text description, write Python code to implement the functionality described below step by step Description: Curve fitting in python A.M.C. Dawes - 2015 An introduction to various curve fitting routines useful for physics work. The first cell is used to import additional features so they are availa...
Python Code: import matplotlib.pyplot as plt import numpy as np %matplotlib inline Explanation: Curve fitting in python A.M.C. Dawes - 2015 An introduction to various curve fitting routines useful for physics work. The first cell is used to import additional features so they are available in our notebook. matplotlib pr...
15,913
Given the following text description, write Python code to implement the functionality described below step by step Description: Multithreading, Multiprocessing, and Subprocessing - Chris Sterling This is a primer to help you get started, not an all-encompassing guide I'll be posting this, so no need to frantically wr...
Python Code: def count_down(n): while n > 0: n-=1 COUNT = 500000000 Explanation: Multithreading, Multiprocessing, and Subprocessing - Chris Sterling This is a primer to help you get started, not an all-encompassing guide I'll be posting this, so no need to frantically write code Here and there, I had to do ...
15,914
Given the following text description, write Python code to implement the functionality described below step by step Description: <CENTER> <p><font size="5"> Queuing theory Step1: 2) The discrete valued random variable $X$ follows a Poisson distribution if its probabilities depend on a parameter $\lambda$ and are suc...
Python Code: %matplotlib inline from pylab import * N = 10**5 lambda_ = 2.0 ######################################## # Supply the missing coefficient herein below V1 = -1.0/lambda_ data = V1*log(rand(N)) ######################################## m = mean(data) v = var(data) print("\u0...
15,915
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup $ mkvirtualenv aws_name_similarity $ pip install --upgrade pip $ pip install jellyfish jupyter scipy matplotlib $ jupyter notebook Step1: # Testing it out Step2: With real AWS servic...
Python Code: from itertools import combinations import jellyfish from scipy.cluster import hierarchy import numpy as np import matplotlib.pyplot as plt Explanation: Setup $ mkvirtualenv aws_name_similarity $ pip install --upgrade pip $ pip install jellyfish jupyter scipy matplotlib $ jupyter notebook End of explanation...
15,916
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Deep Learning Project Step1: Step 1 Step2: Include an exploratory visualization of the dataset Visualize the German Traffic Signs Dataset using the pic...
Python Code: # Load pickled data import pickle import cv2 # for grayscale and normalize # TODO: Fill this in based on where you saved the training and testing data training_file ='traffic-signs-data/train.p' validation_file='traffic-signs-data/valid.p' testing_file = 'traffic-signs-data/test.p' with open(training_file,...
15,917
Given the following text description, write Python code to implement the functionality described below step by step Description: Python 浮点数运算 浮点数用来存储计算机中的小数,与现实世界中的十进制小数不同的是,浮点数通过二进制的形式来表示一个小数。在深入了解浮点数的实现之前,先来看几个 Python 浮点数计算有意思的例子: Step1: IEEE 浮点数表示法 这些看起来违反常识的“错误”并非 Python 的错,而是由浮点数的规则所决定的,即使放到其它语言中结果也是这样的。要理解计算机中浮...
Python Code: 0.1 == 0.10000000000000000000001 0.1+0.1+0.1 == 0.3 Explanation: Python 浮点数运算 浮点数用来存储计算机中的小数,与现实世界中的十进制小数不同的是,浮点数通过二进制的形式来表示一个小数。在深入了解浮点数的实现之前,先来看几个 Python 浮点数计算有意思的例子: End of explanation (0.1).as_integer_ratio() Explanation: IEEE 浮点数表示法 这些看起来违反常识的“错误”并非 Python 的错,而是由浮点数的规则所决定的,即使放到其它语言中结果也是这样的。要理解计算机中浮点数的...
15,918
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 3 - Multi Layer Perceptron with MNIST This lab corresponds to Module 3 of the "Deep Learning Explained" course. We assume that you have successfully completed Lab 1 (Downloading the MNI...
Python Code: # Figure 1 Image(url= "http://3.bp.blogspot.com/_UpN7DfJA0j4/TJtUBWPk0SI/AAAAAAAAABY/oWPMtmqJn3k/s1600/mnist_originals.png", width=200, height=200) Explanation: Lab 3 - Multi Layer Perceptron with MNIST This lab corresponds to Module 3 of the "Deep Learning Explained" course. We assume that you have succe...
15,919
Given the following text description, write Python code to implement the functionality described below step by step Description: H2O Tutorial Author Step1: Enable inline plotting in the Jupyter Notebook Step2: Intro to H2O Data Munging Read csv data into H2O. This loads the data into the H2O column compressed, in-me...
Python Code: import pandas as pd import numpy from numpy.random import choice from sklearn.datasets import load_boston import h2o h2o.init() # transfer the boston data from pandas to H2O boston_data = load_boston() X = pd.DataFrame(data=boston_data.data, columns=boston_data.feature_names) X["Median_value"] = boston_dat...
15,920
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I realize my question is fairly similar to Vectorized moving window on 2D array in numpy , but the answers there don't quite satisfy my needs.
Problem: import numpy as np a = np.array([[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]) size = (3, 3) def window(arr, shape=(3, 3)): ans = [] # Find row and column window sizes r_win = np.floor(shape[0] / 2).astype(int) c_win = np.floor(shape[1] / 2).astype(int) x, y = arr.shape ...
15,921
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <img src="http Step1: Hints Step2: Example 2 Considers the following IVP Step3: Example 3 Considers the following IVP Step4: Example 4 See classnotes! Step5: Example 7, for...
Python Code: import numpy as np import scipy.sparse.linalg as sp import sympy as sym from scipy.linalg import toeplitz import ipywidgets as widgets from ipywidgets import IntSlider import matplotlib.pyplot as plt %matplotlib inline from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatte...
15,922
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...
15,923
Given the following text description, write Python code to implement the functionality described below step by step Description: TFX pipeline example - Chicago Taxi tips prediction Overview Tensorflow Extended (TFX) is a Google-production-scale machine learning platform based on TensorFlow. It provides a configuration...
Python Code: !python3 -m pip install pip --upgrade --quiet --user !python3 -m pip install kfp --upgrade --quiet --user pip install tfx==1.4.0 tensorflow==2.5.1 --quiet --user Explanation: TFX pipeline example - Chicago Taxi tips prediction Overview Tensorflow Extended (TFX) is a Google-production-scale machine learning...
15,924
Given the following text description, write Python code to implement the functionality described below step by step Description: <div align="right">Python 3.6 Jupyter Notebook</div> Visual communication Geocoding and markdown examples Your completion of the notebook exercises will be graded based on your ability to do...
Python Code: # Load relevant libraries. import pandas as pd import numpy as np import matplotlib import folium import geocoder from tqdm import tqdm %pylab inline pylab.rcParams['figure.figsize'] = (10, 8) Explanation: <div align="right">Python 3.6 Jupyter Notebook</div> Visual communication Geocoding and markdown exam...
15,925
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare fit of mixture model where the nulldistribution is either with or without prethreshold In this notebook, I did a first effort to see if we can apply the thresholdfree peakdistributio...
Python Code: import matplotlib % matplotlib inline import numpy as np import scipy import scipy.stats as stats import scipy.optimize as optimize import scipy.integrate as integrate from __future__ import print_function, division import os import math from nipy.labs.utils.simul_multisubject_fmri_dataset import surrogate...
15,926
Given the following text description, write Python code to implement the functionality described below step by step Description: Using ChemicalEnvironments Chemical Environments were created as a way to parse SMIRKS strings and make changes in chemical perception space. In this workbook, we will show you have chemica...
Python Code: # import necessary functions from openff.toolkit.typing.chemistry import environment as env from openeye import oechem Explanation: Using ChemicalEnvironments Chemical Environments were created as a way to parse SMIRKS strings and make changes in chemical perception space. In this workbook, we will show y...
15,927
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Linear Regression Step5: Partitioning the data Before we can begin training our model and testing it, it is important to first properly partition the data into three subsets Step9: ...
Python Code: # import libraries import matplotlib import IPython import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl import pylab import seaborn as sns import sklearn as sk %matplotlib inline housing = Read the .csv file containing the housing data Explanation: Linear Regress...
15,928
Given the following text description, write Python code to implement the functionality described below step by step Description: Leakage Coefficient Summary This notebook summarize the leakage coefficient fitted from 4 dsDNA samples. Import software Step1: Data files Step2: Plot style Step3: Average leakage Mean pe...
Python Code: import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from cycler import cycler import seaborn as sns %matplotlib inline %config InlineBackend.figure_format='retina' # for hi-dpi displays figure_size = (5, 4) default_figure = lambda: plt.subplots(figsize...
15,929
Given the following text description, write Python code to implement the functionality described below step by step Description: Thin Plate Splines (TPS) Transforms Step1: Let's create the landmarks used in Principal Warps paper (http Step2: Let's visualize the TPS Step3: This proves that the result is correct Step...
Python Code: import numpy as np from menpo.transform import ThinPlateSplines from menpo.shape import PointCloud Explanation: Thin Plate Splines (TPS) Transforms End of explanation # landmarks used in Principal Warps paper # http://user.engineering.uiowa.edu/~aip/papers/bookstein-89.pdf src_landmarks = np.array([[3.6929...
15,930
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 5 Statistics Describing a Single Set of Data Step4: Central Tendencies Step7: Dispersion Step8: Correlation
Python Code: num_friends = [100,49,41,40,25,21,21,19,19,18,18,16,15,15,15,15,14,14,13,13,13,13,12,12,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4...
15,931
Given the following text description, write Python code to implement the functionality described below step by step Description: Download, Parse and Interrogate Apple Health Export Data The first part of this program is all about getting the Apple Health export and putting it into an analyzable format. At that point ...
Python Code: import xml.etree.ElementTree as et import pandas as pd import numpy as np from datetime import * import matplotlib.pyplot as plt import re import os.path import zipfile import pytz %matplotlib inline plt.rcParams['figure.figsize'] = 16, 8 Explanation: Download, Parse and Interrogate Apple Health Export D...
15,932
Given the following text description, write Python code to implement the functionality described. Description: Count of arrays in which all adjacent elements are such that one of them divide the another Python3 program to count the number of arrays of size n such that every element is in range [ 1 , m ] and adjacent ar...
Python Code: MAX = 1000 def numofArray(n , m ) : dp =[[ 0 for i in range(MAX ) ] for j in range(MAX ) ] di =[[ ] for i in range(MAX ) ] mu =[[ ] for i in range(MAX ) ] for i in range(1 , m + 1 ) : for j in range(2 * i , m + 1 , i ) : di[j ] . append(i ) mu[i ] . append(j )  di[i ] . append(i ) ...
15,933
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparison of the accuracy of a cutting plane active learning procedure using the (i) analytic center; (ii) Chebyshev center; and (iii) random center on the Iris flower data set The set up S...
Python Code: import numpy as np import active import experiment import logistic_regression as logr from sklearn import datasets # The Iris dataset is imported from here. from IPython.display import display import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 1 %aimport active %aimport exp...
15,934
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
15,935
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup Setup that is specific only to Jupyter notebooks Step1: Setup to use Python libraries/modules cf. www.coolprop.org/coolprop/examples.html Step2: Examples from CoolProp's Examples cf....
Python Code: from pathlib import Path import sys notebook_directory_parent = Path.cwd().resolve().parent if str(notebook_directory_parent) not in sys.path: sys.path.append(str(notebook_directory_parent)) Explanation: Setup Setup that is specific only to Jupyter notebooks End of explanation # Import the things you n...
15,936
Given the following text description, write Python code to implement the functionality described below step by step Description: add paths of ac-calibration tools and plotting functions Step1: create PSDMeasurement object - holding the power spectra of one calibration Step2: create PSDfit object and fit the psds
Python Code: import sys sys.path.append('../..') import pyotc Explanation: add paths of ac-calibration tools and plotting functions End of explanation directory = '../exampleData/height_calibration_single_psds/' fname = 'B01_1000.dat' pm = pyotc.PSDMeasurement(warn=False) pm.load(directory, fname) Explanation: create P...
15,937
Given the following text description, write Python code to implement the functionality described below step by step Description: Before we get started, a couple of reminders to keep in mind when using iPython notebooks Step1: Fixing Data Types Step2: Note when running the above cells that we are actively changing th...
Python Code: import unicodecsv ## Longer version of code (replaced with shorter, equivalent version below) # enrollments = [] # f = open('enrollments.csv', 'rb') # reader = unicodecsv.DictReader(f) # for row in reader: # enrollments.append(row) # f.close() with open('enrollments.csv', 'rb') as f: reader = unico...
15,938
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a LAS file from scratch This example shows Step1: Step 1 Create some synthetic data, and make some of the values in the middle null values (numpy.nan specifically). Note that of co...
Python Code: import lasio print(lasio.__version__) import datetime import numpy import os import matplotlib.pyplot as plt %matplotlib inline Explanation: Building a LAS file from scratch This example shows: Creating a pretend/synthetic data curve that we'll call "SYNTH", including some null values Creating an empty LAS...
15,939
Given the following text description, write Python code to implement the functionality described below step by step Description: 국민대, 파이썬, 데이터 W10 NumPy 101 Table of Contents NumPy Basic NumPy Exercises NumPy Example Step1: 1. NumPy Basic 1. Data Container 데이터를 담는 그릇, Data Container라고 합니다. Python 에서는 List/Tuple/Dicti...
Python Code: from IPython.display import Image Explanation: 국민대, 파이썬, 데이터 W10 NumPy 101 Table of Contents NumPy Basic NumPy Exercises NumPy Example: Random Walks Coding Convention import numpy as np End of explanation import numpy as np Explanation: 1. NumPy Basic 1. Data Container 데이터를 담는 그릇, Data Container라고 합니다. Pyt...
15,940
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...
15,941
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' class DLProgress(tqdm): last_block = 0 def h...
15,942
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Adaptive Evolution Strategy (SAES) TODO Step2: (1+1)-$\sigma$-Self-Adaptation-ES Step3: Some explanations about $\sigma$ and $\tau$ Step4: Other inplementations PyAI Import required ...
Python Code: # Init matplotlib %matplotlib inline import matplotlib matplotlib.rcParams['figure.figsize'] = (8, 8) # Setup PyAI import sys sys.path.insert(0, '/Users/jdecock/git/pub/jdhp/pyai') # Set the objective function #from pyai.optimize.functions import sphere as func from pyai.optimize.functions import sphere2d ...
15,943
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro to Cython Why Cython Outline Step1: Now, let's time this Step2: Not too bad, but this can add up. Let's see if Cython can do better Step3: That's a little bit faster, which is nice ...
Python Code: def f(x): y = x**4 - 3*x return y def integrate_f(a, b, n): dx = (b - a) / n dx2 = dx / 2 s = f(a) * dx2 for i in range(1, n): s += f(a + i * dx) * dx s += f(b) * dx2 return s Explanation: Intro to Cython Why Cython Outline: Speed up Python code Interact with Nu...
15,944
Given the following text description, write Python code to implement the functionality described below step by step Description: Trading Framework This framework is developed based on Peter Henry https Step1: Create a new OpenAI Gym environment with the customised Trading environment .initialise_simulator() must be i...
Python Code: csv = "data/EURUSD60.csv" Explanation: Trading Framework This framework is developed based on Peter Henry https://github.com/Henry-bee/gym_trading/ which in turn on developed of Tito Ingargiola's https://github.com/hackthemarket/gym-trading. First, define the address for the CSV data End of explanation en...
15,945
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ...
Python Code: import numpy as np import tensorflow as tf with open('../sentiment_network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment_network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent ...
15,946
Given the following text description, write Python code to implement the functionality described below step by step Description: UTSC Machine Learning WorkShop Cross-validation for feature selection with Linear Regression From the video series Step1: MSE is more popular than MAE because MSE "punishes" larger errors. ...
Python Code: import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from sklearn.feature_selection import SelectKBest, f_regression from sklearn.cross_validation import cross_val_score # read in the advertising dataset data = pd.read_csv('data/Advertising.csv', index_col=0) # create a ...
15,947
Given the following text description, write Python code to implement the functionality described below step by step Description: Now that we understand variables, we can start to develop more complex code structures which can build more interesting functionality into our scripts. Up to this point, our scripts have bee...
Python Code: b = True if b: print 'b is True' Explanation: Now that we understand variables, we can start to develop more complex code structures which can build more interesting functionality into our scripts. Up to this point, our scripts have been pretty basic, and limited to only executing in a top-down order, ...
15,948
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementation of a Devito self adjoint variable density visco- acoustic isotropic modeling operator <br>-- Linearized Ops -- This operator is contributed by Chevron Energy Technology Compan...
Python Code: import numpy as np from examples.seismic import RickerSource, Receiver, TimeAxis from devito import (Grid, Function, TimeFunction, SpaceDimension, Constant, Eq, Operator, solve, configuration, norm) from devito.finite_differences import Derivative from devito.builtins import gaussian_s...
15,949
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: let the function to read the directory recursively into a dataset
Python Code:: import tensorflow as tf from tensorflow.keras.utils import image_dataset_from_directory PATH = ".../Citrus/Leaves" ds = image_dataset_from_directory(PATH, validation_split=0.2, subset="training", image_size=(256,256), interpolation="bilin...
15,950
Given the following text description, write Python code to implement the functionality described below step by step Description: This example assumes the notebook server has been called with ipython notebook --pylab inline and the trunk version of numba at Github. Step1: Numba provides two major decorators Step2: Th...
Python Code: import numpy as np from numba import autojit, jit, double %pylab inline Explanation: This example assumes the notebook server has been called with ipython notebook --pylab inline and the trunk version of numba at Github. End of explanation def sum(arr): M, N = arr.shape sum = 0.0 for i in range...
15,951
Given the following text description, write Python code to implement the functionality described below step by step Description: The issues associated with validation and cross-validation are some of the most important aspects of the practice of machine learning. Selecting the optimal model for your data is vital, a...
Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.svm import SVR from sklearn import cross_validation np.random.seed(0) n_samples = 200 kernels = ['linear', 'poly', 'rbf'] true_fun = lambda X: X ** 3 X = np.sort(5 * (np.random.rand(n_samples) - .5)) y = t...
15,952
Given the following text description, write Python code to implement the functionality described below step by step Description: Segmentation Segmentation is the division of an image into "meaningful" regions. If you've seen The Terminator, you've seen image segmentation Step1: We can try to create a nicer visualizat...
Python Code: import numpy as np from matplotlib import pyplot as plt import skdemo plt.rcParams['image.cmap'] = 'spectral' from skimage import io, segmentation as seg, color url = '../images/spice_1.jpg' image = io.imread(url) labels = seg.slic(image, n_segments=18, compactness=10) skdemo.imshow_all(image, labels.astyp...
15,953
Given the following text description, write Python code to implement the functionality described below step by step Description: SF Purchases Example In this example, interact is used to build a UI for exploring San Francisco department purchases by city agency data. Step1: You can take a quick look at the first 5 ro...
Python Code: # Import Pandas and then load the data. from pandas import read_csv df = read_csv('SFDeptPurchases.csv') Explanation: SF Purchases Example In this example, interact is used to build a UI for exploring San Francisco department purchases by city agency data. End of explanation df[:5] Explanation: You can tak...
15,954
Given the following text description, write Python code to implement the functionality described below step by step Description: Limb Darkening Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to upda...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Limb Darkening Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matplotlib inline impo...
15,955
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 4 Step1: Load in house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2: If we want to do any "feature engi...
Python Code: import graphlab Explanation: Regression Week 4: Ridge Regression (gradient descent) In this notebook, you will implement ridge regression via gradient descent. You will: * Convert an SFrame into a Numpy array * Write a Numpy function to compute the derivative of the regression weights with respect to a sin...
15,956
Given the following text description, write Python code to implement the functionality described below step by step Description: Template for test Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation. Included is N Phosphorylation however no benchmarks are av...
Python Code: from pred import Predictor from pred import sequence_vector from pred import chemical_vector Explanation: Template for test End of explanation par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Train...
15,957
Given the following text description, write Python code to implement the functionality described below step by step Description: Elements and the periodic table This data came from Penn State CS professor Doug Hogan. Thanks to UCF undergraduates Sam Borges, for finding the data set, and Lissa Galguera, for formatting ...
Python Code: # Import modules that contain functions we need import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt Explanation: Elements and the periodic table This data came from Penn State CS professor Doug Hogan. Thanks to UCF undergraduates Sam Borges, for finding the data set, a...
15,958
Given the following text description, write Python code to implement the functionality described below step by step Description: Phone Digits Given a phone number create a list of all the possible words that you can make given a dictionary from numbers to letters. In python there is a itertools.permutations('abc') th...
Python Code: letters_map = {'2':'ABC', '3':'DEF', '4':'GHI', '5':'JKL', '6':'MNO', '7':'PQRS', '8':'TUV', '9':'WXYZ'} def printWords(number, ): #number is phone number def printWordsUtil(numb, curr_digit, output, n): if curr_digit == n: print('%s ' % output) return ...
15,959
Given the following text description, write Python code to implement the functionality described below step by step Description: $$ \def\CC{\bf C} \def\QQ{\bf Q} \def\RR{\bf R} \def\ZZ{\bf Z} \def\NN{\bf N} $$ Fonctions def Step1: Une fonction rassemble un ensemble d'instructions qui permettent d'atteindre un certain...
Python Code: from __future__ import division, print_function # Python 3 Explanation: $$ \def\CC{\bf C} \def\QQ{\bf Q} \def\RR{\bf R} \def\ZZ{\bf Z} \def\NN{\bf N} $$ Fonctions def End of explanation def FONCTION( PARAMETRES ): INSTRUCTIONS Explanation: Une fonction rassemble un ensemble d'instructions qui permett...
15,960
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Filter <script type="text/javascript"> localStorage.setItem('language', 'language-py') </script> <table align="left" style="margin-right Step2: Examples In the follow...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License") # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this fi...
15,961
Given the following text description, write Python code to implement the functionality described below step by step Description: Project 1 Used Vehicle Price Prediction Introduction 1.2 Million listings scraped from TrueCar.com - Price, Mileage, Make, Model dataset from Kaggle Step1: Exercise P1.1 (50%) Develop a mac...
Python Code: %matplotlib inline import pandas as pd data = pd.read_csv('https://github.com/albahnsen/PracticalMachineLearningClass/raw/master/datasets/dataTrain_carListings.zip') data.head() data.shape data.Price.describe() data.plot(kind='scatter', y='Price', x='Year') data.plot(kind='scatter', y='Price', x='Mileage')...
15,962
Given the following text description, write Python code to implement the functionality described below step by step Description: Variance Reduction in Hull-White Monte Carlo Simulation Using Moment Matching Goutham Balaraman In an earlier blog post on how the Hull-White Monte Carlo simulations are notorious for not co...
Python Code: import QuantLib as ql import numpy as np import matplotlib.pyplot as plt %matplotlib inline from scipy.integrate import cumtrapz ql.__version__ Explanation: Variance Reduction in Hull-White Monte Carlo Simulation Using Moment Matching Goutham Balaraman In an earlier blog post on how the Hull-White Monte Ca...
15,963
Given the following text description, write Python code to implement the functionality described below step by step Description: 仿照求$ \sum_{i=1}^mi + \sum_{i=1}^ni + \sum_{i=1}^ki$的完整代码,写程序,可求m!+n!+k! Step1: 写函数可返回1 - 1/3 + 1/5 - 1/7...的前n项的和。在主程序中,分别令n=1000及100000,打印4倍该函数的和。 Step2: 将task3中的练习1及练习4改写为函数,并进行调用。 练习 1...
Python Code: def compute_sum(n): i=0 sum=0 while i<n: i=i+1 sum+=i return sum m=int(input('plz input m: ')) n=int(input('plz input n: ')) k=int(input('plz input k: ')) print(compute_sum(m) + compute_sum(n) + compute_sum(k)) Explanation: 仿照求$ \sum_{i=1}^mi + \sum_{i=1}^ni + \sum_{i=1}^ki...
15,964
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding stories in data with Python and Jupyter notebooks Journocoders London, April 13, 2017 David Blood/@davidcblood/[first] dot [last] at ft.com Introduction The Jupyter notebook provid...
Python Code: import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns from bokeh.plotting import figure, show from bokeh.io import output_notebook %matplotlib inline Explanation: Finding stories in data with Python and Jupyter notebooks Journocoders London, April 13, 2017 David Blo...
15,965
Given the following text description, write Python code to implement the functionality described below step by step Description: 今回のレポートでは、①オートエンコーダの作成、②再帰型ニューラルネットワークの作成を試みた。 ①コブダクラス型生産関数を再現できるオートエンコーダの作成が目標である。 Step1: 定義域は0≤x≤1である。 <P>コブ・ダグラス型生産関数は以下の通りである。</P> <P>z = x_1**0.5*x_2*0.5</P> Step2: NNのクラスはすでにNN.pyからi...
Python Code: %matplotlib inline import numpy as np import pylab as pl import math from sympy import * import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D from NN import NN Explanation: 今回のレポートでは、①オートエンコーダの作成、②再帰型ニューラルネットワークの作成を試みた。 ①コブダクラス型生産関数を再現できるオートエンコーダ...
15,966
Given the following text description, write Python code to implement the functionality described below step by step Description: pandas 패키지의 소개 pandas 패키지 Index를 가진 자료형인 R의 data.frame 자료형을 Python에서 구현 참고 자료 http Step1: Vectorized Operation Step2: 명시적인 Index를 가지는 Series 생성시 index 인수로 Index 지정 Index 원소는 각 데이터에 대한 key ...
Python Code: s = pd.Series([4, 7, -5, 3]) s s.values type(s.values) s.index type(s.index) Explanation: pandas 패키지의 소개 pandas 패키지 Index를 가진 자료형인 R의 data.frame 자료형을 Python에서 구현 참고 자료 http://pandas.pydata.org/ http://pandas.pydata.org/pandas-docs/stable/10min.html http://pandas.pydata.org/pandas-docs/stable/tutorials.html...
15,967
Given the following text description, write Python code to implement the functionality described below step by step Description: This document is intended for intermediate to advanced users. It deals with the internals of the MoveStrategy and MoveScheme objects, as well how to create custom versions of them. For most ...
Python Code: %matplotlib inline import openpathsampling as paths from openpathsampling.visualize import PathTreeBuilder, PathTreeBuilder from IPython.display import SVG, HTML import openpathsampling.high_level.move_strategy as strategies # TODO: handle this better # real fast setup of a small network from openpathsampl...
15,968
Given the following text description, write Python code to implement the functionality described below step by step Description: Before you turn this problem in, make sure everything runs as expected. First, restart the kernel (in the menubar, select Kernel$\rightarrow$Restart) and then run all cells (in the menubar, ...
Python Code: NAME = "" COLLABORATORS = "" Explanation: Before you turn this problem in, make sure everything runs as expected. First, restart the kernel (in the menubar, select Kernel$\rightarrow$Restart) and then run all cells (in the menubar, select Cell$\rightarrow$Run All). Make sure you fill in any place that says...
15,969
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyzer Analyzer is a python program that tries to gauge the evolvability and maintainability of java software. To achieve this, it tries to measure the complexity of the software under eva...
Python Code: # Imports and directives %matplotlib inline import numpy as np from math import log import matplotlib.pyplot as plt from matplotlib.mlab import PCA as mlabPCA import javalang import os, re, requests, zipfile, json, operator from collections import Counter import colorsys import random from StringIO import ...
15,970
Given the following text description, write Python code to implement the functionality described below step by step Description: File (Revision) upload example To run this example, you'll need the Ovation Python API. Install with pip Step1: Connection You use a connection.Session to interact with the Ovaiton REST API...
Python Code: import ovation.core as core from ovation.session import connect from ovation.upload import upload_revision, upload_file, upload_folder from ovation.download import download_revision from pprint import pprint from getpass import getpass from tqdm import tqdm_notebook as tqdm Explanation: File (Revision) upl...
15,971
Given the following text description, write Python code to implement the functionality described below step by step Description: Background Example notebook for the visualiztion of metagenomic data using MinHash signatures calculated with sourmash compute, classified with sourmash gather, and compared with sourmash co...
Python Code: #Import matplotlib %matplotlib inline #Import pandas, seaborn, and ipython display import pandas as pd import seaborn as sns from IPython.display import display, HTML Explanation: Background Example notebook for the visualiztion of metagenomic data using MinHash signatures calculated with sourmash comput...
15,972
Given the following text description, write Python code to implement the functionality described below step by step Description: ML Workbench Sample --- Image Classification <br><br> Introduction of ML Workbench ML Workbench provides an easy command line interface for machine learning life cycle, which involves four s...
Python Code: # ML Workbench magics (%%ml) are under google.datalab.contrib namespace. It is not enabled by default and you need to import it before use. import google.datalab.contrib.mlworkbench.commands Explanation: ML Workbench Sample --- Image Classification <br><br> Introduction of ML Workbench ML Workbench provide...
15,973
Given the following text description, write Python code to implement the functionality described below step by step Description: Tech - calcul matriciel avec numpy numpy est la librairie incontournable pour faire des calculs en Python. Ces fonctionnalités sont disponibles dans tous les langages et utilisent les optimi...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline Explanation: Tech - calcul matriciel avec numpy numpy est la librairie incontournable pour faire des calculs en Python. Ces fonctionnalités sont disponibles dans tous les langages et utilisent les optimisations processeurs. ...
15,974
Given the following text description, write Python code to implement the functionality described below step by step Description: Inspect Graph Edges Your graph edges are represented by a list of tuples of length 3. The first two elements are the node names linked by the edge. The third is the dictionary of edge attrib...
Python Code: # Preview first 5 edges list(g.edges(data=True))[0:5] Explanation: Inspect Graph Edges Your graph edges are represented by a list of tuples of length 3. The first two elements are the node names linked by the edge. The third is the dictionary of edge attributes. End of explanation # Preview first 10 nodes ...
15,975
Given the following text description, write Python code to implement the functionality described below step by step Description: Mediation analysis with duration data This notebook demonstrates mediation analysis when the mediator and outcome are duration variables, modeled using proportional hazards regression. Thes...
Python Code: import pandas as pd import numpy as np import statsmodels.api as sm from statsmodels.stats.mediation import Mediation Explanation: Mediation analysis with duration data This notebook demonstrates mediation analysis when the mediator and outcome are duration variables, modeled using proportional hazards reg...