Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
2,200
Given the following text description, write Python code to implement the functionality described below step by step Description: Supervised Learning Step1: One approach to building a predictive model is to subdivide the variable space into regions, by sequentially subdividing each variable. For example, if we split l...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns sns.set() from sklearn.datasets import load_diabetes # Predictors: "age" "sex" "bmi" "map" "tc" "ldl" "hdl" "tch" "ltg" "glu" diabetes = load_diabetes() y = diabetes['target'] bmi, ltg = diabete...
2,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Bayesian Optimization with GPyOpt Written by Javier Gonzalez, Amazon Research Cambridge Last updated Monday, 22 May 2017. ====================================================...
Python Code: %pylab inline import GPy import GPyOpt from numpy.random import seed import matplotlib Explanation: Introduction to Bayesian Optimization with GPyOpt Written by Javier Gonzalez, Amazon Research Cambridge Last updated Monday, 22 May 2017. ===================================================================...
2,202
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis of Monte Carlo simulations of mutation accumulation in stem cells This Notebook lives at Github. Many adult tissues renew themselves continually via a pool of cells called stem cel...
Python Code: from IPython.display import Image Image(filename="trajectories.png", width=350, height=350) Explanation: Analysis of Monte Carlo simulations of mutation accumulation in stem cells This Notebook lives at Github. Many adult tissues renew themselves continually via a pool of cells called stem cells. Stem cel...
2,203
Given the following text description, write Python code to implement the functionality described. Description: Length of longest common prefix possible by rearranging strings in a given array Python3 program to implement the above approach ; Function to get the length of the longest common prefix by rearranging the str...
Python Code: import sys def longComPre(arr , N ) : freq =[[ 0 for i in range(256 ) ] for i in range(N ) ] for i in range(N ) : M = len(arr[i ] ) for j in range(M ) : freq[i ][ord(arr[i ][j ] ) ] += 1   maxLen = 0 for j in range(256 ) : minRowVal = sys . maxsize for i in range(N ) : minRowVa...
2,204
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 8</font> Download Step1: NumPy Para importar numpy, utilize Step2: Criando Arrays Step3: Funções NumPy Step4: Cria...
Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 8</font> Download: http://github.com/dsacademybr End of explanation # Imp...
2,205
Given the following text description, write Python code to implement the functionality described below step by step Description: Symbol Tutorial Besides the tensor computation interface NDArray, another main object in MXNet is the Symbol provided by mxnet.symbol, or mxnet.sym for short. A symbol represents a multi-out...
Python Code: import mxnet as mx a = mx.sym.Variable('a') b = mx.sym.Variable('b') c = a + b (a, b, c) Explanation: Symbol Tutorial Besides the tensor computation interface NDArray, another main object in MXNet is the Symbol provided by mxnet.symbol, or mxnet.sym for short. A symbol represents a multi-output symbolic ex...
2,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Data Processing Functions Step2: Create Data Pipeline Step3: Send First Two Pieces Of Raw Data Through Pipeline Step4: Send All Raw Data Through Pipeline
Python Code: raw_data = [1,2,3,4,5,6,7,8,9,10] Explanation: Title: Streaming Data Pipeline Slug: streaming_data_pipeline Summary: Streaming Data Pipeline Using Python. Date: 2017-02-02 12:00 Category: Python Tags: Basics Authors: Chris Albon Create Some Raw Data End of explanation # Define a generator that yields inp...
2,207
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 3 Problem 5 Step1: Part 5.a. Here we load the large mandrill image and display it. Step2: Part 5.b. Here we load the small mandrill image and display it. Step3: Now apply the K-M...
Python Code: import numpy as np import matplotlib.pyplot as plt import kmeans KCENTROIDS = 16 MAX_ITERS = 200 EPSILON = 1e-7 Explanation: Homework 3 Problem 5 End of explanation Ilarge = plt.imread('mandrill-large.tiff') Ilarge = np.uint8(np.round(Ilarge)) plt.imshow(Ilarge) plt.show() Explanation: Part 5.a. Here we lo...
2,208
Given the following text description, write Python code to implement the functionality described below step by step Description: Alcune applicazioni delle matrici Subito dopo aver introdotto le matrici e viste le operazioni fondamentali di somma, prodotto e determinante una domanda sorge spontanea. A cosa servono? In ...
Python Code: import sys; sys.path.append('pyggb') %reload_ext geogebra_magic %ggb --width 800 --height 400 --showToolBar 0 --showResetIcon 1 trasformazioni.ggb Explanation: Alcune applicazioni delle matrici Subito dopo aver introdotto le matrici e viste le operazioni fondamentali di somma, prodotto e determinante una d...
2,209
Given the following text description, write Python code to implement the functionality described below step by step Description: Fine-tuning a CNN with MXNet Step1: Dowload pre-trained model from the model zoo (Resnet-152) We then download a pretrained 152-layer ResNet model and load into memory. Note Step3: Fine tu...
Python Code: # Data Iterators for cats vs dogs dataset import mxnet as mx def get_iterators(batch_size, data_shape=(3, 224, 224)): train = mx.io.ImageRecordIter( path_imgrec = './cats_dogs_train.rec', data_name = 'data', label_name = 'softmax_label', batch...
2,210
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-Dimension Visualization Step1: Scatter Matrix The scatter matrix allows users to identify correlations between pairs of dimensions in a matrix form. Step2: Histograms Once you want i...
Python Code: %matplotlib inline import os import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt # Setup context and style sns.set_context('talk') sns.set_style('whitegrid') IRIS = os.path.join("..", "data", "iris.csv") data = pd.read_csv(IRIS) Explanation: Multi-Dimension...
2,211
Given the following text description, write Python code to implement the functionality described below step by step Description: Ausgeführtes Beispiel für den Buchberger-Algorithmus Step1: Zuerst wird ein Polynomring geschaffen. QQ ist $\mathbb Q$. Alternative Termordnungen sind grlex und grevlex. Step2: Es gibt a...
Python Code: from sympy import * init_printing() Explanation: Ausgeführtes Beispiel für den Buchberger-Algorithmus End of explanation P, erzeuger = xring('x,y', QQ, lex) x, y = erzeuger def S_poly(p, q): kgv = p.leading_monom().lcm(q.leading_monom()) t1 = kgv / p.leading_term() * p t2 = kgv / q.leading_term...
2,212
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiments for extracting images of Boyd's Bird Journal into computer readable form (See image below) The journals are PDFs containing a series of scanned images of observations of birds. T...
Python Code: %load_ext watermark %watermark -a 'Raphael LaFrance' -i -u -v -r -g -p numpy,matplotlib,skimage Explanation: Experiments for extracting images of Boyd's Bird Journal into computer readable form (See image below) The journals are PDFs containing a series of scanned images of observations of birds. The obser...
2,213
Given the following text description, write Python code to implement the functionality described below step by step Description: Demo 2 - Remote parallel computation [distributed] Demo for site visit | Brendan Smithyman | April 8, 2015 Choice of IPython / jupyter cluster profile Step1: Importing libraries numpy is th...
Python Code: # profile = 'phobos' # remote workstation # profile = 'pantheon' # remote cluster profile = 'mpi' # local machine Explanation: Demo 2 - Remote parallel computation [distributed] Demo for site visit | Brendan Smithyman | April 8, 2015 Choice of IPython / jupyter cluster profile End of explanation import n...
2,214
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook an estimator for the Volume will be trained. No hyperparameters will be searched for, and the ones from the 'Close' values estimator will be used instead. Step1: Let's gene...
Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error %matplotlib inline %pylab inline pylab.rcParams['figure.figsize'] ...
2,215
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Take a look at a typical review. This one is labeled "negative" Step2: Check for missing values Step3: 35 records show NaN (this stands for "not a number" and is equi...
Python Code: import numpy as np import pandas as pd df = pd.read_csv('../TextFiles/moviereviews.tsv', sep='\t') df.head() len(df) Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Text Classification Project Now we're at the point where we should be able to: * Read in a colle...
2,216
Given the following text description, write Python code to implement the functionality described below step by step Description: 简单线图 先设置ipython notebook 作图环境 Step1: 对于所有Matplotlib图,我们首先创建一个图形和一个轴。以最简单的形式,可以如下创建图形和轴: Step2: 在Matplotlib中,图形(类plt.Figure的一个实例)可以被认为是一个包含所有代表轴,图形,文本和标签的对象的容器。轴(类plt.Axes的实例)就是我们在上面看到的:一个带...
Python Code: %matplotlib inline import matplotlib.pyplot as plt #使用seaborn-whitegrid风格 plt.style.use('seaborn-whitegrid') import numpy as np Explanation: 简单线图 先设置ipython notebook 作图环境 End of explanation fig = plt.figure() ax = plt.axes() Explanation: 对于所有Matplotlib图,我们首先创建一个图形和一个轴。以最简单的形式,可以如下创建图形和轴: End of explanation...
2,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Electric Machinery Fundamentals 5th edition Chapter 2 (Code examples) Example 2-5 Calculate and plot the voltage regulation of a transformer as a function of load for power factors of 0.8 l...
Python Code: %pylab notebook Explanation: Electric Machinery Fundamentals 5th edition Chapter 2 (Code examples) Example 2-5 Calculate and plot the voltage regulation of a transformer as a function of load for power factors of 0.8 lagging, 1.0, and 0.8 leading. Import the PyLab namespace (provides set of useful command...
2,218
Given the following text description, write Python code to implement the functionality described below step by step Description: T-shirt inspiration ❝first solve the problem then write the code❞ Step1: Introduction This Jupyter notebook is a place to keep my thoughts organized on how to best present Fort Lauderdale P...
Python Code: from IPython.display import IFrame IFrame( 'https://www.sunfrog.com/Geek-Tech/First-solve-the-problem-Then-write-the-code.html', width=800, height=350, ) Explanation: T-shirt inspiration ❝first solve the problem then write the code❞ End of explanation from IPython.display import IFrame IFrame...
2,219
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames 001 Step1: We're skipping Table 1 because it is an observing log. Table 2- Members of IC348 Since this table is formatted in the CDS format, it is easiest to take advantage of...
Python Code: %pylab inline import seaborn as sns sns.set_context("notebook", font_scale=1.5) import warnings warnings.filterwarnings("ignore") Explanation: ApJdataFrames 001: Luhman2003 Title: A Census of the Young Cluster IC 348 Authors: Luhman K.L., Stauffer J.R., Muench A.A., Rieke G.H., Lada E.A., Bouvier J., Lada ...
2,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create an example dataframe Step2: List Comprehensions As a loop Step3: As list comprehension
Python Code: # Import modules import pandas as pd # Set ipython's max row display pd.set_option('display.max_row', 1000) # Set iPython's max column width to 50 pd.set_option('display.max_columns', 50) Explanation: Title: Using List Comprehensions With Pandas Slug: pandas_list_comprehension Summary: Using List Comprehen...
2,221
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center"> Introdução ao Processamento de Linguagem Natural (PLN) Usando Python </h1> <h3 align="center"> Professor Fernando Vieira da Silva MSc.</h3> <h2> Técnicas para Pré-Process...
Python Code: import nltk nltk.download("gutenberg") Explanation: <h1 align="center"> Introdução ao Processamento de Linguagem Natural (PLN) Usando Python </h1> <h3 align="center"> Professor Fernando Vieira da Silva MSc.</h3> <h2> Técnicas para Pré-Processamento </h2> <p>Vamos avaliar as técnicas mais comuns para prepar...
2,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Idomatic Pandas Q Step1: Reshaping DataFrame objects In the context of a single DataFrame, we are often interested in re-arranging the layout of our data. This dataset in from Table 6.9 of...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt Explanation: Idomatic Pandas Q: How do I make my pandas code faster with parallelism? A: You don’t need parallelism, you can use Pandas better. -- Matthew Rocklin Now that we have been exposed to the basic functionali...
2,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Models By Saurabh Mahindre - <a href="https Step1: Training and generating weights LeastSquaresRegression has to be initialised with the training features and training labels. On...
Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from cycler import cycler # import all shogun classes from shogun import * slope = 3 X_train = rand(30)*10 y_train = slope*(X_train)+random.randn(30)*2+2 y_true = slope*(X_train)+2 X_test = concatenate(...
2,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: トレーニング後の float16 量子化 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: モデルをトレーニングしてエクスポートする Step3:...
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...
2,225
Given the following text description, write Python code to implement the functionality described below step by step Description: Random Numbers in NumPy Step1: The numpy.random module adds to the standard built-in Python random functions for generating efficiently whole arrays of sample values with many kinds of prob...
Python Code: import numpy as np Explanation: Random Numbers in NumPy End of explanation samples = np.random.normal(size=(4,4)) samples Explanation: The numpy.random module adds to the standard built-in Python random functions for generating efficiently whole arrays of sample values with many kinds of probability distri...
2,226
Given the following text description, write Python code to implement the functionality described below step by step Description: 函数调用的参数规则与解包 Python 的函数在声明参数时大概有下面 4 种形式: 不带默认值的:def func(a) Step1: 另外一条规则是:位置参数优先权: Step2: 最保险的方法就是全部采用关键词参数。 任意参数 任意参数可以接受任意数量的参数,其中*a的形式代表任意数量的位置参数,**d代表任意数量的关键词参数: Step3: 上面的这个def con...
Python Code: def func(a, b = 1): pass func(a = "G", 20) # SyntaxError 语法错误 Explanation: 函数调用的参数规则与解包 Python 的函数在声明参数时大概有下面 4 种形式: 不带默认值的:def func(a): pass 带有默认值的:def func(a, b = 1): pass 任意位置参数:def func(a, b = 1, *c): pass 任意键值参数:def func(a, b = 1, *c, **d): pass 在调用函数时,有两种情况: 没有关键词的参数:func("G", 20) 带有关键词的参数:func(a...
2,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Common Cross Validation Test Code We used the same cross validation test procedure for the three applications described in the paper. This document provides explanations for the code in anal...
Python Code: # The 'combined' list has all the 22 metrics feature_names_combined = ( 'entities', 'agents', 'activities', # PROV types (for nodes) 'nodes', 'edges', 'diameter', 'assortativity', # standard metrics 'acc', 'acc_e', 'acc_a', 'acc_ag', # average clustering coefficients 'mfd_e_e', 'mfd_e_a'...
2,228
Given the following text description, write Python code to implement the functionality described below step by step Description: Twitter Sentiment Analysis Businesses and organizations around the world know that the first requirement for success is a happy customer base. For the purpose of identifying customer sentime...
Python Code: import swat from IPython.display import display swat.options.cas.exception_on_severity = 2 s = swat.CAS('rdcgrd075.unx.sas.com', 3217,authinfo=r'/u/saleem/.authinfo') s.loadactionset('deeplearn') Explanation: Twitter Sentiment Analysis Businesses and organizations around the world know that the first requi...
2,229
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy Basics Numerical Python, or "NumPy" for short, is a foundational package on which many of the most common data science packages are built. Numpy provides us with high performance mult...
Python Code: import numpy as np from __future__ import print_function Explanation: NumPy Basics Numerical Python, or "NumPy" for short, is a foundational package on which many of the most common data science packages are built. Numpy provides us with high performance multi-dimensional arrays which we can use as vector...
2,230
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 style="text-align Step1: Next-word prediction task Part 1 Step2: 1.2.Symbols encoding The LSTM input's can only be numbers. A way to convert words (symbols or any items) to numbers is ...
Python Code: import numpy as np import collections # used to build the dictionary import random import time from time import time import pickle # may be used to save your model import matplotlib.pyplot as plt #Import Tensorflow and rnn import tensorflow as tf from tensorflow.contrib import rnn # Target log path logs...
2,231
Given the following text description, write Python code to implement the functionality described below step by step Description: tidy-harness A tidy pandas.DataFrame with scikit-learn models, interactive bokeh visualizations, and jinja2 templates. Usage Example Step1: More Examples More examples can be found in the t...
Python Code: import harness from harness import Harness from pandas import Categorical from sklearn import datasets, discriminant_analysis iris = datasets.load_iris() # Harness is just a dataframe df = Harness( data=iris['data'], index=Categorical(iris['target']), estimator=discriminant_analysis.LinearDiscrimin...
2,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian interpretation of medical tests This notebooks explores several problems related to interpreting the results of medical tests. Copyright 2016 Allen Downey MIT License Step3: Medica...
Python Code: from __future__ import print_function, division from thinkbayes2 import Pmf, Suite from fractions import Fraction Explanation: Bayesian interpretation of medical tests This notebooks explores several problems related to interpreting the results of medical tests. Copyright 2016 Allen Downey MIT License: htt...
2,233
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
2,234
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementation of ADAM This method computes individual adaptive learning rates for different parameters from estimates of first and second moments of the gradients; the name Adam is derived ...
Python Code: %matplotlib inline import numpy as np import math import matplotlib.pyplot as plt Explanation: Implementation of ADAM This method computes individual adaptive learning rates for different parameters from estimates of first and second moments of the gradients; the name Adam is derived from adaptive moment e...
2,235
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-2', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-2 Topic: Ocean Sub-Topics: Timestepping Fra...
2,236
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 import numpy as np 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 wi...
2,237
Given the following text description, write Python code to implement the functionality described below step by step Description: Postcards of Parliament From A Digital Flâneur Flâneur, noun, A man who saunters around observing society. The flâneur wandered in the shopping arcades, but he did not give in to the temptat...
Python Code: import mnis import datetime # Create a date for the analysis d = datetime.date.today() # Download the full data for MPs serving on the given date as a list mnis.getCommonsMembersOn(d)[0] Explanation: Postcards of Parliament From A Digital Flâneur Flâneur, noun, A man who saunters around observing society. ...
2,238
Given the following text description, write Python code to implement the functionality described below step by step Description: ----- IMPORTANT ------ The code presented here assumes that you're running TensorFlow v1.3.0 or higher, this was not released yet so the easiet way to run this is update your TensorFlow ver...
Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections # tensorflow import tensorflow as tf print('Expected TensorFlow version is v1.3.0 or higher') print('Your TensorFlow version:', tf.__version__) # data manipulation import numpy as...
2,239
Given the following text description, write Python code to implement the functionality described below step by step Description: Baxter kinematics In this notebook, we'll try IKPy on the baxter robot You will get the following chains Step1: ## Robot import and setup Step2: Inverse kinematics
Python Code: # Some necessary imports import numpy as np from ikpy.chain import Chain from ikpy.utils import plot # Optional: support for 3D plotting in the NB %matplotlib widget # turn this off, if you don't need it Explanation: Baxter kinematics In this notebook, we'll try IKPy on the baxter robot You will get the fo...
2,240
Given the following text description, write Python code to implement the functionality described below step by step Description: Time dependent Schrödinger equation We want to describe an electron wavefunction by a wavepacket $\psi (x,y)$ that is a function of position $x$ and time $t$. We assume that the electron is ...
Python Code: %matplotlib inline import numpy as np from matplotlib import pyplot import math import matplotlib.animation as animation from IPython.display import HTML lx=20 dx = 0.04 nx = int(lx/dx) dt = dx**2/20. V0 = 60 alpha = dt/dx**2 fig = pyplot.figure() ax = pyplot.axes(xlim=(0, lx), ylim=(0, 2), xlabel='x', yla...
2,241
Given the following text description, write Python code to implement the functionality described below step by step Description: OpenTire Moment Method Example Draws a constant velocity force-moment diagram of a bicycle using the OpenTire library Import OpenTire and other libraries used in this demonstration Step1: D...
Python Code: from opentire import OpenTire from opentire.Core import TireState import numpy as np import matplotlib.pyplot as plt Explanation: OpenTire Moment Method Example Draws a constant velocity force-moment diagram of a bicycle using the OpenTire library Import OpenTire and other libraries used in this demonstrat...
2,242
Given the following text description, write Python code to implement the functionality described below step by step Description: Parte III Step1: 2. Entrenando un primer modelo (IV) Step2: 2. Entrenando un primer modelo (V) En este primer ejemplo ignoramos muchas cuestiones que se tienen que tomar en cuenta en proye...
Python Code: # configuramos matplotlib para incluir las gráficas en jupyter e importamos pandas %matplotlib inline import pandas as pd # cargamos los datos en un data frame de pandas url = 'http://mlr.cs.umass.edu/ml/machine-learning-databases/iris/iris.data' names = ['sepal_length', 'sepal_width', 'petal_length', 'pet...
2,243
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Calibrated-Recommendations" data-toc-modified-id="Calibrated-Recommendations...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(css_style='custom2.css', plot_style=False) os.chdir(path) # 1. magic for in...
2,244
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction The Lines object provides the following features Step1: Basic Line Chart Step2: We can explore the different attributes by changing each of them for the plot above Step3: In ...
Python Code: import numpy as np from pandas import date_range import bqplot.pyplot as plt from bqplot import * security_1 = np.cumsum(np.random.randn(150)) + 100. security_2 = np.cumsum(np.random.randn(150)) + 100. Explanation: Introduction The Lines object provides the following features: Ability to plot a single set ...
2,245
Given the following text description, write Python code to implement the functionality described below step by step Description: Zipline beginner tutorial Basics Zipline is an open-source algorithmic trading simulator written in Python. The source can be found at Step1: As you can see, we first have to import some fu...
Python Code: # assuming you're running this notebook in zipline/docs/notebooks import os if os.name == 'nt': # windows doesn't have the cat command, but uses 'type' similarly ! type "..\..\zipline\examples\buyapple.py" else: ! cat ../../zipline/examples/buyapple.py Explanation: Zipline beginner tutorial Bas...
2,246
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Tutorial Welcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that w...
Python Code: import math import numpy as np import h5py import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict %matplotlib inline np.random.seed(1) Explanation: TensorFlow Tutorial Welcome to...
2,247
Given the following text description, write Python code to implement the functionality described below step by step Description: Software Engineering for Data Scientists Manipulating Data with Python CSE 583 Today's Objectives 1. Opening & Navigating the Jupyter Notebook 2. Simple Math in the Jupyter Notebook 3. Loadi...
Python Code: !ls Explanation: Software Engineering for Data Scientists Manipulating Data with Python CSE 583 Today's Objectives 1. Opening & Navigating the Jupyter Notebook 2. Simple Math in the Jupyter Notebook 3. Loading data with pandas 4. Cleaning and Manipulating data with pandas 5. Visualizing data with pandas & ...
2,248
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...
2,249
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Data Step2: Exercise 1 Step3: Exercise 2 Step4: Exercise 3 Step5: Exercise 4
Python Code: # Useful Libraries import numpy as np import matplotlib.pyplot as plt from scipy import stats import seaborn as sns # Useful functions def normal_test(X): z, pval = stats.normaltest(X) if pval < 0.05: print 'Values are not normally distributed.' else: print 'Values are normall...
2,250
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Ray for Highly Parallelizable Tasks While Ray can be used for very complex parallelization tasks, often we just want to do something simple in parallel. For example, we may have 100,00...
Python Code: import ray import random import time import math from fractions import Fraction # Let's start Ray ray.init(address='auto') Explanation: Using Ray for Highly Parallelizable Tasks While Ray can be used for very complex parallelization tasks, often we just want to do something simple in parallel. For example,...
2,251
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Transfer Learning Using Pretrained ConvNets <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...
2,252
Given the following text description, write Python code to implement the functionality described below step by step Description: Why Version Control? Here's why. Step1: If that hasn't convinced you, here are some other benefits
Python Code: from IPython.display import Image Image(url='http://www.phdcomics.com/comics/archive/phd101212s.gif') Explanation: Why Version Control? Here's why. End of explanation %%bash git status Explanation: If that hasn't convinced you, here are some other benefits: http://stackoverflow.com/questions/1408450/why-sh...
2,253
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'messy-consortium', 'emac-2-53-vol', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: MESSY-CONSORTIUM Source ID: EMAC-2-53-VOL Sub-Topics: R...
2,254
Given the following text description, write Python code to implement the functionality described below step by step Description: This example builds HMM and MSMs on the alanine_dipeptide dataset using varing lag times and numbers of states, and compares the relaxation timescales Step1: First Step2: Now sequences is ...
Python Code: from __future__ import print_function import os %matplotlib inline from matplotlib.pyplot import * from msmbuilder.featurizer import SuperposeFeaturizer from msmbuilder.example_datasets import AlanineDipeptide from msmbuilder.hmm import GaussianFusionHMM from msmbuilder.cluster import KCenters from msmbuil...
2,255
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to pandas Pandas! They are adorable animals. You might think they are the worst animal ever but that is not true. You might sometimes think pandas is the worst library every,...
Python Code: # import pandas, but call it pd. Why? Because that's What People Do. import pandas as pd #so that you don't have to type pandas later -- most people use pd instead of pands Explanation: An Introduction to pandas Pandas! They are adorable animals. You might think they are the worst animal ever but that is n...
2,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 3 Previously in 2_fullyconnected.ipynb, you trained a logistic regression and a neural network model. The goal of this assignment is to explore regularization techni...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle Explanation: Deep Learning Assignment 3 Previously in 2_fullyconnected.ipynb,...
2,257
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ...
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n...
2,258
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...
2,259
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyzing the NYC Subway Dataset Section 1. Statistical Test 1.1 Which statistical test did you use to analyze the NYC subway data? Did you use a one-tail or a two-tail P value? What is the ...
Python Code: print ggplot(turnstile_weather, aes(x='ENTRIESn_hourly')) +\ geom_histogram(binwidth=1000,position="identity") +\ scale_x_continuous(breaks=range(0, 60001, 10000), labels = range(0, 60001, 10000))+\ facet_grid("rain")+\ ggtitle('Distribution of ENTRIESn_hourly in non-rainy days (0.0) and ra...
2,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Samples and Results Setup Step1: Connection s is a Session object representing a connection to the Ovation API Step2: Organization id required for all calls. Step3: Workflow samples Colle...
Python Code: import uuid from pprint import pprint from datetime import date from ovation.session import connect_lab Explanation: Samples and Results Setup End of explanation s = connect_lab(input("Email: "), api='https://lab-services-staging.ovation.io') Explanation: Connection s is a Session object representing a con...
2,261
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting data from database I set up a Postgres database on Amazon Web Services and used a pandasql engine to write SQL queries directly from Python. sqlalchemy_conn is script containing the ...
Python Code: query = 'SELECT DISTINCT targetname FROM undata WHERE goalid = 1' targets1 = pd.read_sql(query, engine) for target in targets1['targetname']: print target query = 'SELECT DISTINCT targetname FROM undata WHERE goalid = 5' targets5 = pd.read_sql(query, engine) for target in targets5['targetname']: ...
2,262
Given the following text description, write Python code to implement the functionality described below step by step Description: Using custom containers with AI Platform Training Learning Objectives Step1: Configure environment settings Set location paths, connections strings, and other environment settings. Make sur...
Python Code: import json import os import pickle import tempfile import time import uuid from typing import NamedTuple import numpy as np import pandas as pd from google.cloud import bigquery from googleapiclient import discovery, errors from jinja2 import Template from kfp.components import func_to_container_op from s...
2,263
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br> Allen Downey Read the pregnancy file. Step1: Select live births, then make a CDF of <tt>totalwgt_lb</tt>. Step2: Display the CD...
Python Code: %matplotlib inline import nsfg preg = nsfg.ReadFemPreg() import thinkstats2 import thinkplot import numpy as np Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br> Allen Downey Read the pregnancy file. End of explanation live = preg[preg.outcome == 1] print live wgt_cdf = thinkstats2....
2,264
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to the Echo package The "echo" subpackage of murraylab_tools is designed to automate the setup of reactions (mostly TX-TL reactions) with the Echo. The EchoRun class can produce pick...
Python Code: import murraylab_tools.echo as mt_echo import os.path # Relevant input and output files. Check these out for examples of input file format. txtl_inputs = os.path.join("txtl_setup", "inputs") txtl_outputs = os.path.join("txtl_setup", "outputs") stock_file = os.path.join(txtl_inputs, "TX-TL_setup_example_s...
2,265
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.algo - La sous-séquence de plus grande somme Ce problème est connu sur le nom de Maximum subarray problem. Notion abordée Step1: Enoncé On suppose qu'on a une liste $L=( l_1, l_2, ..., ...
Python Code: %matplotlib inline from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.algo - La sous-séquence de plus grande somme Ce problème est connu sur le nom de Maximum subarray problem. Notion abordée : programmation dynamique. End of explanation def somme_partielle(li, i, j): r = 0...
2,266
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Data Step2: Constant baseline As a baseline, we use the empirical mean of y. Step3: Kernel regression Step4: We can visualize the kernel matrix to see which inputs ...
Python Code: import numpy as np import matplotlib.pyplot as plt np.random.seed(seed=1) import math import collections try: import torch except ModuleNotFoundError: %pip install -qq torch import torch from torch import nn from torch.nn import functional as F try: from probml_utils import d2l except Modul...
2,267
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Rock, Paper & Scissors with TensorFlow Hub - TFLite <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https...
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...
2,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Video Segments The following example shows how to read the video segments files Step1: The duration of the segments has to be defined manually. It is 5s for all provided video segment files...
Python Code: import numpy as np import pandas as pd import matplotlib.pylab as plt dfsegs = pd.read_csv("../data/videos/CRZbG73SX3s_segments.csv") Explanation: Video Segments The following example shows how to read the video segments files: End of explanation segment_duration = 5 Explanation: The duration of the segmen...
2,269
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Processing Robotic total station data Upload total station data into sample_data folder Unfortunately, in the space delimited text file, there are spaces in the time ...
Python Code: import re # for regular expressions import numpy as np # for vector/matri operations import matplotlib.pyplot as plt # for charts import pandas as pd # for table like data structures from datetime import datetime, timedelta # for time/date handling Ex...
2,270
Given the following text description, write Python code to implement the functionality described below step by step Description: CAPM - Capital Asset Pricing Model Watch the video for the full overview. Portfolio Returns Step1: Compare Cumulative Return Step2: Get Daily Return Step3: What if our stock was completel...
Python Code: # Model CAPM as a simple linear regression from scipy import stats help(stats.linregress) import pandas as pd import pandas_datareader as web spy_etf = web.DataReader('SPY', 'google') spy_etf.info() spy_etf.head() start = pd.to_datetime('2010-01-04') end = pd.to_datetime('2017-07-18') aapl = web.DataReader...
2,271
Given the following text description, write Python code to implement the functionality described below step by step Description: Measuring a Multiport Device with a 2-Port Network Analyzer Introduction In microwave measurements, one commonly needs to measure a n-port device with a m-port network analyzer ($m<n$ of cou...
Python Code: import skrf as rf from itertools import combinations %matplotlib inline from pylab import * rf.stylely() Explanation: Measuring a Multiport Device with a 2-Port Network Analyzer Introduction In microwave measurements, one commonly needs to measure a n-port device with a m-port network analyzer ($m<n$ of c...
2,272
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Concatenation Concatenation basically glues together DataFrames. Keep in mind that dimensions should match along the axis you are concatenating on. You can use pd.conca...
Python Code: import pandas as pd df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index=[0, 1, 2, 3]) df2 = pd.DataFrame({'A': [...
2,273
Given the following text description, write Python code to implement the functionality described below step by step Description: Plane-DEM intersections First dated version Step1: Test case 1 The first test case is illustrated in the image below. We have a horizontal topographic surface, at a height of 0, with 100 x ...
Python Code: from pygsf.io.gdal.raster import try_read_raster_band Explanation: Plane-DEM intersections First dated version: 2019-06-11 Current version: 2021-04-24 Last run: 2021-04-24 A few simulated topographic surfaces were used to validate the routine for calculating the plane-DEM intersection. Loading the dataset ...
2,274
Given the following text description, write Python code to implement the functionality described below step by step Description: Scores (pyannote.core.scores.Scores) Step1: Scores instances are used to describe classification scores. For instance, one can use a Scores to store the result of speaker identification app...
Python Code: from pyannote.core import Scores Explanation: Scores (pyannote.core.scores.Scores) End of explanation scores = Scores( uri='TheBigBangTheory.Season01.Episode01', modality='speaker' ) Explanation: Scores instances are used to describe classification scores. For instance, one can use a Scores to sto...
2,275
Given the following text description, write Python code to implement the functionality described below step by step Description: analyzing data from multiple files software carpentry Step1: if / else statements syntax similar to that in loops, need Step2: useful tools for strings Step3: regular expressions We have...
Python Code: import glob glob.glob("inflammation-??.csv") filenames = glob.glob('inflammation*.csv') for f in filenames: data = numpy.loadtxt(fname=f, delimiter=',') print("file",f[13:15], ", # rows and columns: ", data.shape, sep="") import numpy import matplotlib.pyplot filenames = sorted(glob.glob(...
2,276
Given the following text description, write Python code to implement the functionality described below step by step Description: Loan Approval Model Created with H2O Automatic Machine Learning This notebook ingests a dataset, and trains many machine learning models intelligently searching the hyper-parameter space for...
Python Code: %%capture import h2o from h2o.automl import H2OAutoML import os import plotly import cufflinks import plotly.plotly as py import plotly.graph_objs as go import plotly.figure_factory as ff plotly.offline.init_notebook_mode(connected=True) myPlotlyKey = os.environ['SECRET_ENV_BRETTS_PLOTLY_KEY'] py.sign_in(u...
2,277
Given the following text description, write Python code to implement the functionality described below step by step Description: 13 Boucles for et while Step1: 13.1 La boucle for Syntaxe Step2: 13.4 Mise à jour d'une variable Step3: 13.5 Quelques exemples Calculer la somme des éléments d'une liste Step4: Écri...
Python Code: from IPython.display import Image Image('../NotesDeCours/images/bart_simpson.jpg') range(100, 109) for i in range(100, 109): print(i, "I will not do this again") for i in range(10): print(i) Explanation: 13 Boucles for et while End of explanation s = 0 Explanation: 13.1 La boucle for Syntaxe : for ...
2,278
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting a linear model fp1 Step1: Linear Function Step2: Fitting the model with polynomial degree of 2 Step3: Trying to fir the model with 53 polynomial Step4: As we can see that betwee...
Python Code: # starting with linear model where degree is 1 # polyfit() - best put that line into the chart so that it results in the smallest # approximation error fp1, residuals, rank, sv, rcond = sp.polyfit(X, y, 1, full=True) fp1 Explanation: Fitting a linear model fp1 End of explanation print(residuals) print(rank...
2,279
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...
2,280
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Better performance with the tf.data API <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Thr...
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...
2,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Cat vs coherent states in a Kerr resonator, and the role of measurement $\newcommand{\ket}[1]{| #1 \rangle}$ $\newcommand{\bra}[1]{\langle #1 |}$ $\newcommand{\braket}[1]{\langle #1 \rangle}...
Python Code: import matplotlib.pyplot as plt import numpy as np from qutip import * from IPython.display import display, Math, Latex Explanation: Cat vs coherent states in a Kerr resonator, and the role of measurement $\newcommand{\ket}[1]{| #1 \rangle}$ $\newcommand{\bra}[1]{\langle #1 |}$ $\newcommand{\braket}[1]{\la...
2,282
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Scale Data Using Standard Scaler in Sklearn
Python Code:: from sklearn.preprocessing import StandardScaler #Initalise standard scaler scaler = StandardScaler() #Fit the scaler using X_train data scaler.fit(X_train) #Transform X_train and X_test using the scaler and convert back to DataFrame X_train = pd.DataFrame(scaler.transform(X_train), columns = X_train.colu...
2,283
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to parameter tuning Hyper-parameters A machine learning model is a mathematical formula with a number of parameters that are learnt from the data. That is the crux of machine le...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use('fivethirtyeight') #Read the data #Read the data df = pd.read_csv("data/historical_loan.csv") # refine the data df.years = df.years.fillna(np.mean(df.years)) # Setup the features and target X = df.iloc[...
2,284
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 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...
2,285
Given the following text description, write Python code to implement the functionality described below step by step Description: Train a Simple TensorFlow Lite for Microcontrollers model This notebook demonstrates the process of training a 2.5 kB model using TensorFlow and converting it for use with TensorFlow Lite fo...
Python Code: # Define paths to model files import os MODELS_DIR = 'models/' if not os.path.exists(MODELS_DIR): os.mkdir(MODELS_DIR) MODEL_TF = MODELS_DIR + 'model' MODEL_NO_QUANT_TFLITE = MODELS_DIR + 'model_no_quant.tflite' MODEL_TFLITE = MODELS_DIR + 'model.tflite' MODEL_TFLITE_MICRO = MODELS_DIR + 'model.cc' Exp...
2,286
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src='http Step1: First algorithm Step2: Note 1 Step3: Representing Cities and Distance Now for the notion of distance. We define total_distance(tour) as the sum of the distances bet...
Python Code: import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cm as cmx import random, operator import time import itertools import numpy import math %matplotlib inline random.seed(time.time()) # planting a random seed Explanation: <img src='http://www.puc-rio.br/sobrepuc/admin/vrd/...
2,287
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize the Architecture of a Neural Network Step1: The function $\texttt{generateNN}(\texttt{Topology})$ takes a network topology Topology as its argument and draws a graph of the resu...
Python Code: import graphviz as gv Explanation: Visualize the Architecture of a Neural Network End of explanation def generateNN(Topology): L = len(Topology) input_layer = ['i' + str(i) for i in range(1, Topology[0]+1)] hidden_layers = [['h' + str(k+1) + ',' + str(i) for i in range(1, s+1)] ...
2,288
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
2,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Pull political boundary data from OpenStreetMap as shapefile This notebook pulls political boundary data from the OpenStreetMap database and creates a shapefile containing the query results....
Python Code: bounding_box_file = "" result_shapefile_filepath = "" p1 = pyproj.Proj("+init=epsg:31254") p2 = pyproj.Proj("+init=epsg:4326") p3 = pyproj.Proj("+init=epsg:3857") p4 = pyproj.Proj("+init=epsg:25832") Explanation: Pull political boundary data from OpenStreetMap as shapefile This notebook pulls political bou...
2,290
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning Scikit-learn Step1: Let's start again with our text-classification problem, but for now we will only use a reduced number of instances. We will work only with 3,000 instances. Step...
Python Code: %pylab inline import IPython import sklearn as sk import numpy as np import matplotlib import matplotlib.pyplot as plt print 'IPython version:', IPython.__version__ print 'numpy version:', np.__version__ print 'scikit-learn version:', sk.__version__ print 'matplotlib version:', matplotlib.__version__ Expla...
2,291
Given the following text description, write Python code to implement the functionality described below step by step Description: Multiple linear regression Step1: Fitting multiple linear regression to the training set Step2: Building the optimal model using Backward elimination Previously to build the multiple regre...
Python Code: # Import the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the datset dataset = pd.read_csv('datasets/50_Startups.csv') dataset.head() X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, 4].values X Y # But there is categorical variable. i.e. independent varaib...
2,292
Given the following text description, write Python code to implement the functionality described below step by step Description: Slice in volumetric data, via Plotly A volume included in a parallelepiped is described by the values of a scalar field, $f(x,y,z)$, with $x\in[a,b]$, $y\in [c,d]$, $z\in[e,f]$. A slice in ...
Python Code: import numpy as np import plotly.graph_objects as go from IPython Explanation: Slice in volumetric data, via Plotly A volume included in a parallelepiped is described by the values of a scalar field, $f(x,y,z)$, with $x\in[a,b]$, $y\in [c,d]$, $z\in[e,f]$. A slice in this volume is visualized by coloring ...
2,293
Given the following text description, write Python code to implement the functionality described below step by step Description: 회귀 분석용 가상 데이터 생성 방법 Scikit-learn 의 datasets 서브 패키지에는 회귀 분석 시험용 가상 데이터를 생성하는 명령어인 make_regression() 이 있다. http Step1: 위 선형 모형은 다음과 같다. $$ y = 100 + 79.1725 x $$ noise 인수를 증가시키면 $\text{Var}...
Python Code: from sklearn.datasets import make_regression X, y, c = make_regression(n_samples=10, n_features=1, bias=0, noise=0, coef=True, random_state=0) print("X\n", X) print("y\n", y) print("c\n", c) plt.scatter(X, y, s=100) plt.show() Explanation: 회귀 분석용 가상 데이터 생성 방법 Scikit-learn 의 datasets 서브 패키지에는 회귀 분석 시험용 가상 데...
2,294
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align='center' style="margin-bottom Step1: Here is a broad outline of technical steps to be done for data collection Sign up for TMDB (themoviedatabase.org), and set up API to scrape mo...
Python Code: import torchvision import urllib2 import requests import json import imdb import time import itertools import wget import os import tmdbsimple as tmdb import numpy as np import random import matplotlib import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns import pickle Explanation: <h1 a...
2,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Updated TOC trends analysis (part 2) This notebook begins to explore trends in the broader water chemistry dataset collated by Heleen, Don and John for the updated TOC analysis. Note that th...
Python Code: # Import custom functions # Connect to db resa2_basic_path = (r'C:\Data\James_Work\Staff\Heleen_d_W\ICP_Waters\Upload_Template' r'\useful_resa2_code.py') resa2_basic = imp.load_source('useful_resa2_code', resa2_basic_path) engine, conn = resa2_basic.connect_to_resa2() # Import code for ...
2,296
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex client library Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the Vertex client library and Google clo...
Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG Explanation: Vertex client library: AutoML text entity extraction model for online prediction <tab...
2,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 25 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: In the previous chapter we modeled a system with constant angular velocity. In this chapter we take t...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
2,298
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="clearfix" style="padding Step1: Advanced usage Step2: Model fitting process N.B. Model-fitting is optional. Fitting the three-state model takes approximately 30 seconds and th...
Python Code: %matplotlib notebook from pyrho import * loadGUI() Explanation: <div class="clearfix" style="padding: 10px; padding-left: 0px"> <a href="https://github.com/ProjectPyRhO/PyRhO", target="_blank"><img src="https://raw.githubusercontent.com/ProjectPyRhO/Prometheus/master/resources/images/PyRhO_logo_H_crop.png"...
2,299
Given the following text description, write Python code to implement the functionality described below step by step Description: COVID-19 Моделирование распространения и анализ Целью данной лабораторной является построение модели заболевания населения COVID-19, обладающей как можно лучшей предсказательной силой. Кажды...
Python Code: # Устанавливаем библиотеки, если это не было сделано ранее. # ! pip3 install seaborn matplotlib numpy pandas # Импорт библиотек import numpy as np import matplotlib.pyplot as plt import urllib.request import pandas as pd import seaborn as sns # Используем настройки seaborn по-умолчанию, устанавливаем тольк...