Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
2,500
Given the following text description, write Python code to implement the functionality described below step by step Description: Normalizing Flows - Introduction (Part 1) This tutorial introduces Pyro's normalizing flow library. It is independent of much of Pyro, but users may want to read about distribution shapes in...
Python Code: import torch import pyro import pyro.distributions as dist import pyro.distributions.transforms as T import matplotlib.pyplot as plt import seaborn as sns import os smoke_test = ('CI' in os.environ) Explanation: Normalizing Flows - Introduction (Part 1) This tutorial introduces Pyro's normalizing flow libr...
2,501
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This work is inspired by this paper from Elie and Celine Bursztein and will try to reproduce their findings applying some different ideas. Step1: Cards data Load the collectib...
Python Code: from hearthpricer import hearthpricer import numpy import os.path import pandas Explanation: Introduction This work is inspired by this paper from Elie and Celine Bursztein and will try to reproduce their findings applying some different ideas. End of explanation all_sets_filename = os.path.join('data', '...
2,502
Given the following text description, write Python code to implement the functionality described below step by step Description: Class Session 17 - Date Hubs and Party Hubs Comparing the histograms of local clustering coefficients of date hubs and party hubs In this class, we will analyze the protein-protein interacti...
Python Code: import igraph import numpy import pandas import matplotlib.pyplot Explanation: Class Session 17 - Date Hubs and Party Hubs Comparing the histograms of local clustering coefficients of date hubs and party hubs In this class, we will analyze the protein-protein interaction network for two classes of yeast pr...
2,503
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', 'sandbox-3', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: MESSY-CONSORTIUM Source ID: SANDBOX-3 Sub-Topics: Radiative...
2,504
Given the following text description, write Python code to implement the functionality described below step by step Description: Building an image classification model using very little data Based on the tutorial by Francois Chollet @fchollet https Step1: Imports Step2: Small Conv Net Model architecture definition S...
Python Code: ##This notebook is built around using tensorflow as the backend for keras #!pip install pillow !KERAS_BACKEND=tensorflow python -c "from keras import backend" import os import numpy as np from keras.models import Sequential from keras.layers import Activation, Dropout, Flatten, Dense from keras.preprocessi...
2,505
Given the following text description, write Python code to implement the functionality described below step by step Description: 阅读笔记 作者:方跃文 Email Step1: Tab 键自动完成 在python shell中,输入表达式时候,只要按下Tab键,当前命名空间中任何已输入的字符串相匹配的变量(对象、函数等)就会被找出来: Step2: 此外,我们还可以在任何对象之后输入一个句点来方便地补全方法和属性的输入: Step3: Tab键自动完成成功不只可以搜索命名空间和自动完成对象或...
Python Code: a = 5 a import numpy as np from numpy.random import randn data = {i: randn() for i in range(7)} print(data) data1 = {j: j**2 for j in range(5)} print(data1) Explanation: 阅读笔记 作者:方跃文 Email: fyuewen@gmail.com 时间:始于2017年9月12日 第三章笔记始于2017年9月28日23:38,结束于 2017年10月17日 第三章 IPtyhon: 一种交互式计算和开发环境 IPython鼓励一种...
2,506
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 5 Step1: A very simple pipeline to show how registers are inferred. Step2: Simulation of the core
Python Code: import pyrtl pyrtl.reset_working_block() class SimplePipeline(object): def __init__(self): self._pipeline_register_map = {} self._current_stage_num = 0 stage_list = [method for method in dir(self) if method.startswith('stage')] for stage in sorted(stage_list): ...
2,507
Given the following text description, write Python code to implement the functionality described below step by step Description: [Your name] Homework 1 The maximum score of this homework is 100+20 points. Grading is listed in this table Step1: 1.2 Replace rare words (10 points) Write a function that takes a text and ...
Python Code: def group_by_retval(sequence, grouper_func): # TODO l = ["ab", 12, "cd", "d", 3] assert(group_by_retval(l, lambda x: isinstance(x, str)) == {True: ["ab", "cd", "d"], False: [12, 3]}) assert(group_by_retval([1, 1, 2, 3, 4], lambda x: x % 3) == {0: [3], 1: [1, 1, 4], 2: [2]}) Explanation: [Your name] Hom...
2,508
Given the following text description, write Python code to implement the functionality described below step by step Description: Statsmodels - glm, mixed models, survival analysis Data scientists normally use R for statistical heavy lifting, with a few exceptions Step1: Above, the Region variable was treated as cathe...
Python Code: import statsmodels.api as sm import statsmodels.formula.api as smf import numpy as np import pandas df = sm.datasets.get_rdataset("Guerry", "HistData").data df = df[['Lottery', 'Literacy', 'Wealth', 'Region']].dropna() df.head() mod = smf.ols(formula='Lottery ~ Literacy + Wealth + Region', data=df) res = m...
2,509
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading and Fomatting the Required Data Step2: Helper Functions For The PreProcessing Taken from the original letter merging python script Step3: Compute the RV Coefficient on the Log Chan...
Python Code: # Load the database of letters and numbers subject_folders_path = os.path.join(os.getcwd(), "DB_wacomPaper_v2") subject_folders = os.listdir(subject_folders_path) letters_db = dict() trajectories = dict() for subject in tqdm(subject_folders): letters_db[subject] = dict() trajectories[subject] = di...
2,510
Given the following text description, write Python code to implement the functionality described below step by step Description: Hey there! Here's more-or-less the steps you'll be taking to reduce our data, and, using those reduced data, extract some flux-calibrated lightcurves of WR 124! First things first, copy this...
Python Code: #Now, let's import some useful libraries import numpy as np from matplotlib import pyplot as plt from adapt import * from phot_tools import * from glob import glob import os from astropy.io import fits from astropy.coordinates import SkyCoord from astropy.table import vstack, Table %matplotlib inline #What...
2,511
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--<img width=700px; src="../img/logoUPSayPlusCDS_990.png"> --> <p style="margin-top Step1: 1. Let's start with a showcase Case 1 Step2: Starting from reading this dataset, to answering q...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt pd.options.display.max_rows = 8 Explanation: <!--<img width=700px; src="../img/logoUPSayPlusCDS_990.png"> --> <p style="margin-top: 3em; margin-bottom: 2em;"><b><big><big><big><big>Introduction to Pandas</big></big></...
2,512
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents Preface Step1: Introductory textbook for Kalman filters and Bayesian filters. The book is written using Jupyter Notebook so you may read the book in your browser and also ...
Python Code: from __future__ import division, print_function %matplotlib inline #format the book import book_format book_format.set_style() Explanation: Table of Contents Preface End of explanation import numpy as np x = np.array([1, 2, 3]) print(type(x)) x Explanation: Introductory textbook for Kalman filters and Baye...
2,513
Given the following text description, write Python code to implement the functionality described below step by step Description: Screenshots and Movies with WebGL One can use the REBOUND WebGL ipython widget to capture screenshots of a simulation. These screenshots can then be easily compiled into a movie. The widget ...
Python Code: import rebound sim = rebound.Simulation() sim.add(m=1) # add a star for i in range(10): sim.add(m=1e-3,a=0.4+0.1*i,inc=0.03*i,omega=5.*i) # Jupiter mass planets on close orbits sim.move_to_com() # Move to the centre of mass frame w = sim.getWidget() w Explanation: Screenshots and Movies with WebGL One ...
2,514
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,515
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting sentiment from product reviews The goal of this first notebook is to explore logistic regression and feature engineering with existing GraphLab functions. In this notebook you wil...
Python Code: from __future__ import division import graphlab import math import string Explanation: Predicting sentiment from product reviews The goal of this first notebook is to explore logistic regression and feature engineering with existing GraphLab functions. In this notebook you will use product review data from...
2,516
Given the following text description, write Python code to implement the functionality described below step by step Description: Convenience This is an example of aneris' convenience module. This module doesn't have anywhere near the error checking of aneris' other features, but it does make it slightly simpler to cal...
Python Code: import matplotlib.pyplot as plt import pandas as pd import aneris.tutorial import aneris.convenience plt.rcParams["figure.figsize"] = (12, 8) Explanation: Convenience This is an example of aneris' convenience module. This module doesn't have anywhere near the error checking of aneris' other features, but i...
2,517
Given the following text description, write Python code to implement the functionality described below step by step Description: Flowers Image Classification with TensorFlow on Cloud ML Engine This notebook demonstrates how to do image classification from scratch on a flowers dataset using the Estimator API. Step1: I...
Python Code: import os PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 MODEL_TYPE = "cnn" # do not change these os.environ["PROJECT"] = PROJECT os.environ["BUCKET"...
2,518
Given the following text description, write Python code to implement the functionality described below step by step Description: Examining racial discrimination in the US job market Background Racial discrimination continues to be pervasive in cultures throughout the world. Researchers examined the level of racial dis...
Python Code: %matplotlib inline from __future__ import division import matplotlib matplotlib.rcParams['figure.figsize'] = (15.0,5.0) import pandas as pd import numpy as np from scipy import stats data = pd.io.stata.read_stata('data/us_job_market_discrimination.dta') print "Total count: ",len(data) print "race == 'b': "...
2,519
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-1', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: TEST-INSTITUTE-1 Source ID: SANDBOX-1 Topic: Atmoschem Su...
2,520
Given the following text description, write Python code to implement the functionality described below step by step Description: Dogs vs Cats https Step1: データ整形 https Step2: 訓練データからランダムに選んだ2000画像をvalidationデータとする Step3: PyTorchで読み込みやすいようにクラスごとにサブディレクトリを作成する Kaggleのテストデータは正解ラベルがついていないため unknown というサブディレクトリにいれる Step4...
Python Code: mkdir %matplotlib inline Explanation: Dogs vs Cats https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition http://aidiary.hatenablog.com/entry/20170108/1483876657 http://aidiary.hatenablog.com/entry/2017060...
2,521
Given the following text description, write Python code to implement the functionality described below step by step Description: Processing Multiple Pandas Series in Parallel Introduction Python's Pandas library for data processing is great for all sorts of data-processing tasks. However, one thing it doesn't support ...
Python Code: from multiprocessing import Pool, cpu_count def process_Pandas_data(func, df, num_processes=None): ''' Apply a function separately to each column in a dataframe, in parallel.''' # If num_processes is not specified, default to minimum(#columns, #machine-cores) if num_processes==None: ...
2,522
Given the following text description, write Python code to implement the functionality described below step by step Description: iPython Cookbook - Monte Carlo III - Principal Components Generating a Monte Carlo vector using eigenvector decomposition Theory Before we go into the implementation, a bit of theory on Mont...
Python Code: import numpy as np d = 3 R = np.random.uniform(-1,1,(d,d))+np.eye(d) C = np.dot(R.T, R) #C = np.array(((5,2,3),(2,5,4),(3,4,5))) C Explanation: iPython Cookbook - Monte Carlo III - Principal Components Generating a Monte Carlo vector using eigenvector decomposition Theory Before we go into the implementati...
2,523
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow IO Authors. Step1: 解码用于医学成像的 DICOM 文件 <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,524
Given the following text description, write Python code to implement the functionality described below step by step Description: CS228 Python Tutorial Adapted from the CS231n Python tutorial by Justin Johnson (http Step1: Python versions There are currently two different supported versions of Python, 2.7 and 3.6. Som...
Python Code: def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[int(len(arr) / 2)] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) print (quicksort([3,6,8,10,1,...
2,525
Given the following text description, write Python code to implement the functionality described below step by step Description: automaton.is_functional Whether the automaton is functional, i.e. each input (string) is transduced to a unique output (string). There may be multiple paths, however, that contain this input...
Python Code: import vcsn Explanation: automaton.is_functional Whether the automaton is functional, i.e. each input (string) is transduced to a unique output (string). There may be multiple paths, however, that contain this input and output string pair. Precondition: - The automaton is transducer Examples End of explana...
2,526
Given the following text description, write Python code to implement the functionality described below step by step Description: 决策树在 sklearn 中的实现简介 0. 预前 本文简单分析 scikit-learn/scikit-learn 中决策树涉及的代码模块关系。 分析的代码版本信息是: ```shell ~/W/s/sklearn ❯❯❯ git log -n 1 ...
Python Code: SVG("./res/uml/Model__tree_0.svg") Explanation: 决策树在 sklearn 中的实现简介 0. 预前 本文简单分析 scikit-learn/scikit-learn 中决策树涉及的代码模块关系。 分析的代码版本信息是: ```shell ~/W/s/sklearn ❯❯❯ git log -n 1 ...
2,527
Given the following text description, write Python code to implement the functionality described below step by step Description: DKRZ data ingest information handling The submission_forms package provides a collection of components to support the management of information related to data ingest related activities (dat...
Python Code: ## the following libraries are needed to interact with ## json based form submissions from dkrz_forms import form_handler, utils, checks,wflow_handler from datetime import datetime ## info_file = "path to json file" info_file = "../Forms/../xxx.json" # load json file and convert to Form object for simple ...
2,528
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.ML101.8 Step1: Hyperparameters, Over-fitting, and Under-fitting The issues associated with validation and cross-validation are some of the most important aspects of the practice of mach...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: 2A.ML101.8: Parameter selection, Validation & Testing The content in this section is adapted from Andrew Ng's excellent Coursera course. Source: Course on machine learning with scikit-learn by Gaël Varoquaux End of explanati...
2,529
Given the following text description, write Python code to implement the functionality described below step by step Description: with open('inputcode.txt',encoding="utf8") as f Step1: def build_dataset(words) Step2: #testing #symbols_in_keys = [ [dictionary[ str(training_data[i])]] for i in range(offset, offset+n_in...
Python Code: training_data = read_data(training_file) print("Loaded training data...") print(training_data) training_data = list(map(int, training_data)) print(training_data) print(training_data[:10]) print(len(training_data)) Explanation: with open('inputcode.txt',encoding="utf8") as f: content = f.read() data...
2,530
Given the following text description, write Python code to implement the functionality described below step by step Description: Mixed Invasion Percolation Until now we have demonstrated percolation that assumed that the important entry pressures are determined by the throat connections, i.e. Bond Percolation. When mo...
Python Code: import warnings import numpy as np import openpnm as op %config InlineBackend.figure_formats = ['svg'] from openpnm.algorithms import MixedInvasionPercolation as mp import matplotlib as mpl import matplotlib.pyplot as plt from ipywidgets import interact, IntSlider %load_ext autoreload %autoreload 2 %matplo...
2,531
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Work through Geometric Factor for Sullivan 1971 How do the results depend on stackup? Both the full formula and a bounded formula How do the results depend on diameter? Both the full ...
Python Code: from pprint import pprint import numpy as np import pymc3 as pm import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set(font_scale=1.5) sns.set_context("notebook", rc={"lines.linewidth": 3}) %matplotlib inline def getBoundedNormal_dist(mean=None, FWHM=None, name=None, lower=0, up...
2,532
Given the following text description, write Python code to implement the functionality described below step by step Description: WMI Win32_Process Class and Create Method for Remote Execution Metadata | Metadata | Value | | Step1: Download & Process Security Dataset Step2: Analytic I Look for wmiprvse.exe...
Python Code: from openhunt.mordorutils import * spark = get_spark() Explanation: WMI Win32_Process Class and Create Method for Remote Execution Metadata | Metadata | Value | |:------------------|:---| | collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] | | creation date | 2019/08/10 | | modification d...
2,533
Given the following text description, write Python code to implement the functionality described. Description: Return median of elements in the list l. This is how the function will work: median([3, 1, 2, 4, 5]) 3 This is how the function will work: median([-10, 4, 6, 1000, 10, 20]) 15.0
Python Code: def median(l: list): l = sorted(l) if len(l) % 2 == 1: return l[len(l) // 2] else: return (l[len(l) // 2 - 1] + l[len(l) // 2]) / 2.0
2,534
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The Cirq Developers Step1: Protocols <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Introduction Cirq's protocols are ver...
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,535
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', 'nasa-giss', 'sandbox-3', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-3 Sub-Topics: Radiative Forcings. Pr...
2,536
Given the following text description, write Python code to implement the functionality described below step by step Description: Know your customer (KYC) - [Lead Scoring] Marketing a new product to customers In this short note we discuss customer targeting through telemarketing phone calls to sell long-term deposits. ...
Python Code: import graphlab as gl import pandas as pd from datetime import datetime from sklearn.cross_validation import StratifiedKFold ## load data set from a locally saved csv file bank_marketing = gl.SFrame.read_csv('./../../../04.UCI.ML.REPO/Bank_Marketing/bank-additional/bank-additional-full.csv', ...
2,537
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup We're going to download the collected works of Nietzsche to use as our data for this class. Step1: Sometimes it's useful to have a zero value in the dataset, e.g. for padding Step2: ...
Python Code: path = get_file('nietzsche.txt', origin="https://s3.amazonaws.com/text-datasets/nietzsche.txt") text = open(path).read() print('corpus length:', len(text)) chars = sorted(list(set(text))) vocab_size = len(chars)+1 print('total chars:', vocab_size) Explanation: Setup We're going to download the collected wo...
2,538
Given the following text description, write Python code to implement the functionality described below step by step Description: Objectives * Learn how to parse html. * Create models that capture different aspects of the problem. * How to learn processes in parallel ? Step1: Text Features based on the boiler plate T...
Python Code: import pandas as pd import numpy as np import os, sys import re, json from urllib.parse import urlparse from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import Imputer, FunctionTransformer from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.preprocessing impo...
2,539
Given the following text description, write Python code to implement the functionality described below step by step Description: StateFarm Distracted Driver Detection Full Dataset Step1: Create Batches Step2: Use Previous Conv sample model on full dataset The previous model used in the sample data should work better...
Python Code: %cd /home/ubuntu/kaggle/state-farm-distracted-driver-detection # Make sure you are in the main directory (state-farm-distracted-driver-detection) %pwd # Create references to key directories import os, sys from glob import glob from matplotlib import pyplot as plt import numpy as np import keras np.set_prin...
2,540
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST数据集介绍 大多数例子使用了手写数字的MNIST数据集。它包含了60000个训练数据和10000个测试数据。这些数字的尺寸已标准化,同时做了居中处理,所以每个数据可以表示成一个值为0到1大小为28 * 28矩阵。 预览 用法 在例子中,我们使用TFinput_data.py脚本来加载数据集。这对管理数据相当好用,具体操作: 数据集下载 加载整个数据集成numpy数组 ...
Python Code: # 导入MNIST from tensorflow.examples.tutorials.mnist import input_data # 加载数据 X_train = mnist.train.images Y_train = mnist.train.labels X_test = mnist.test.images Y_test = mnist.test.labels print(X_train.shape) print(Y_train.shape) print(X_test.shape) print(Y_test.shape) Explanation: MNIST数据集介绍 大多数例子使用了手写数字的...
2,541
Given the following text description, write Python code to implement the functionality described below step by step Description: K-nearest neighbors and scikit-learn Review of the iris dataset Step1: Terminology 150 observations (n=150) Step2: K-nearest neighbors (KNN) classification Pick a value for K. Search for t...
Python Code: %matplotlib inline import pandas as pd url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'] iris = pd.read_csv(url, header=None, names=col_names) iris.head() Explanation: K-nearest neighbors and...
2,542
Given the following text description, write Python code to implement the functionality described below step by step Description: Algo - jeux de dictionnaires, plus grand suffixe commun Les dictionnaires sont très utilisés pour associer des choses entre elles, surtout quand ces choses ne sont pas entières. Le notebook ...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: Algo - jeux de dictionnaires, plus grand suffixe commun Les dictionnaires sont très utilisés pour associer des choses entre elles, surtout quand ces choses ne sont pas entières. Le notebook montre l'intérêt de perdre un peu de tem...
2,543
Given the following text description, write Python code to implement the functionality described below step by step Description: 2D Registration Example Most ndreg functions are convinence wrappers around the SimpleITK registration framework. Functions provided by ndreg should work reasonably well with most types of ...
Python Code: import matplotlib.pyplot as plt from ndreg import * inImg = imgDownload("checkerBig") refImg = imgDownload("checkerSmall") Explanation: 2D Registration Example Most ndreg functions are convinence wrappers around the SimpleITK registration framework. Functions provided by ndreg should work reasonably well ...
2,544
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'thu', 'sandbox-1', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: THU Source ID: SANDBOX-1 Topic: Aerosol Sub-Topics: Transport, Emissions, ...
2,545
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create dataframe Step2: Scatterplot of preTestScore and postTestScore, with the size of each point determined by age Step3: Scatterplot of preTestScore and postTestScore with...
Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np Explanation: Title: Making A Matplotlib Scatterplot From A Pandas Dataframe Slug: matplotlib_scatterplot_from_pandas Summary: Making A Matplotlib Scatterplot From A Pandas Dataframe Date: 2016-05-01 12:00 Category: Py...
2,546
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Import the necessary packages to read in the data, plot, and create a linear regression model Step1: 2. Read in the hanford.csv file Step2: <img src="images/hanford_variables.png"> 3. C...
Python Code: import pandas as pd import statsmodels.formula.api as smf import matplotlib %matplotlib inline import matplotlib.pyplot as plt Explanation: 1. Import the necessary packages to read in the data, plot, and create a linear regression model End of explanation df = pd.read_csv('../data/hanford.csv') df.head() E...
2,547
Given the following text description, write Python code to implement the functionality described below step by step Description: Generalized Linear Models (Formula) This notebook illustrates how you can use R-style formulas to fit Generalized Linear Models. To begin, we load the Star98 dataset and we construct a formu...
Python Code: import statsmodels.api as sm import statsmodels.formula.api as smf star98 = sm.datasets.star98.load_pandas().data formula = "SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT + \ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF" dta = star98[ [ "NABOVE", ...
2,548
Given the following text description, write Python code to implement the functionality described below step by step Description: We will build a logistic regression model to predict whether a student gets admitted into a university. We want to determine each applicant’s chance of admission based on their results on tw...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('ex2data1.txt', header=None) df.columns = ["score1", "score2", "res"] pos = df[(df.res == 1)] neg = df[(df.res == 0)] plt.scatter(pos['score1'], pos['score2'], label='admitted') plt.scatter(neg['score1'], neg['score2']...
2,549
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Dictionaries Unlike some of the other Data Structures we've worked with, most of the really useful methods available to us in Dictionaries have already been explored throughout this...
Python Code: d = {'k1':1,'k2':2} Explanation: Advanced Dictionaries Unlike some of the other Data Structures we've worked with, most of the really useful methods available to us in Dictionaries have already been explored throughout this course. Here we will touch on just a few more for good measure: End of explanation ...
2,550
Given the following text description, write Python code to implement the functionality described below step by step Description: Different ways to load an input graph We recommend using the GML graph format to load a graph. You can also use the DOT format, which requires additional dependencies (either pydot or pygrap...
Python Code: import os, sys import random sys.path.append(os.path.abspath("../../../")) import numpy as np import pandas as pd import dowhy from dowhy import CausalModel from IPython.display import Image, display Explanation: Different ways to load an input graph We recommend using the GML graph format to load a graph....
2,551
Given the following text description, write Python code to implement the functionality described below step by step Description: OM10 Tutorial In this notebook we demonstrate the basic functionality of the om10 package, including how to Step1: Selecting Mock Lens Samples Let's look at what we might expect from DES an...
Python Code: from __future__ import division, print_function import os, numpy as np import matplotlib matplotlib.use('TkAgg') %matplotlib inline import om10 %load_ext autoreload %autoreload 2 Explanation: OM10 Tutorial In this notebook we demonstrate the basic functionality of the om10 package, including how to: Make s...
2,552
Given the following text description, write Python code to implement the functionality described below step by step Description: Part I Step1: We're going to investigate the set of data on the passengers of the Titanic. The datasets I'm providing come from the website http Step2: Note that the above summary gives yo...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize']=(8,5) # optional plt.style.use('bmh') # optional Explanation: Part I End of explanation #change the paths as needed train = pd.read_csv('../data/titanic_train.csv') test = pd.read_csv('...
2,553
Given the following text description, write Python code to implement the functionality described below step by step Description: Below done so far Step1: Create variables for URLs. The base_url is for the search_recipes API call. The metadata_url is for searching for valid search terms. Step2: Extracting data Step3:...
Python Code: # imports import requests import json import pandas as pd import numpy as np # ID and Key app_id = 'e2b9bebc' app_key = '4193215272970d956cfd5384a08580a9' Explanation: Below done so far: - access Yummly API with "Search Recipes API Call" - search for "chicken" recipes - convert JSON into dicts and lists wi...
2,554
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting info on Priming experiment dataset that's needed for modeling Info Step1: Init Step2: Loading OTU table (filter to just bulk samples) Step3: Which gradient(s) to simulate? Step4: ...
Python Code: baseDir = '/home/nick/notebook/SIPSim/dev/priming_exp/' workDir = os.path.join(baseDir, 'exp_info') otuTableFile = '/var/seq_data/priming_exp/data/otu_table.txt' otuTableSumFile = '/var/seq_data/priming_exp/data/otu_table_summary.txt' metaDataFile = '/var/seq_data/priming_exp/data/allsample_metadata_nomock...
2,555
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <p style = "font-size Step2: Preamble Step3: EM and MNIST The $\TeX$ markup used here uses the "align*" environment and thus should not be viewed though nbViewer. Before proceeding,...
Python Code: ## Add JS-based table of contents from IPython.display import HTML as add_TOC add_TOC( u<h1 id="tocheading">Table of Contents</h1></br><div id="toc"></div> <script src="https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js"></script></br></hr></br> ) Explanation: <p style = "font-siz...
2,556
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize Evoked data In this tutorial we focus on the plotting functions of Step1: First we read the evoked object from a file. Check out tut_epoching_and_averaging to get to this stage f...
Python Code: import os.path as op import numpy as np import matplotlib.pyplot as plt import mne # sphinx_gallery_thumbnail_number = 9 Explanation: Visualize Evoked data In this tutorial we focus on the plotting functions of :class:mne.Evoked. End of explanation data_path = mne.datasets.sample.data_path() fname = op.joi...
2,557
Given the following text description, write Python code to implement the functionality described below step by step Description: Bolometric correction grids Bolometric correction is defined as the difference between the apparent bolometric magnitude of a star and its apparent magnitude in a particular bandpass Step1: ...
Python Code: from isochrones.mist.bc import MISTBolometricCorrectionGrid bc_grid = MISTBolometricCorrectionGrid(['J', 'H', 'K', 'G', 'BP', 'RP', 'g', 'r', 'i']) bc_grid.df.head() bc_grid.interp.index_names bc_grid.interp([5770, 4.44, 0.0, 0.], ['G', 'K']) Explanation: Bolometric correction grids Bolometric correction i...
2,558
Given the following text description, write Python code to implement the functionality described below step by step Description: glstring using the get_ functions Each of these functions take a GL String as an argument Step1: get_alleles() & get_loci() Each of these functions returns a set of objects. Step2: get_all...
Python Code: import glstring print(glstring.__file__) from glstring.glstring import * a = "HLA-A*01:01/HLA-A*01:02+HLA-A*24:02|HLA-A*01:03+HLA-A*24:03^HLA-B*44:01+HLA-B*44:02" print(a) Explanation: glstring using the get_ functions Each of these functions take a GL String as an argument End of explanation get_alleles(a...
2,559
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.algo - Optimisation sous contrainte L'optimisation sous contrainte est un problème résolu. Ce notebook utilise une librairie externe et la compare avec l'algorithme Arrow-Hurwicz qu'il fa...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.algo - Optimisation sous contrainte L'optimisation sous contrainte est un problème résolu. Ce notebook utilise une librairie externe et la compare avec l'algorithme Arrow-Hurwicz qu'il faudra implémenter. Plus de précision dans...
2,560
Given the following text description, write Python code to implement the functionality described below step by step Description: probability mass function - maps each value to its probability. Alows you to compare two distributions independently from sample size. probability - frequency expressed as a fraction of the...
Python Code: import thinkstats2 pmf = thinkstats2.Pmf([1,2,2,3,5]) #getting pmf values print pmf.Items() print pmf.Values() print pmf.Prob(2) print pmf[2] #modifying pmf values pmf.Incr(2, 0.2) print pmf.Prob(2) pmf.Mult(2, 0.5) print pmf.Prob(2) #if you modify, probabilities may no longer add up to 1 #to check: print ...
2,561
Given the following text description, write Python code to implement the functionality described below step by step Description: Decoding (MVPA) .. include Step1: Transformation classes Scaler The Step2: PSDEstimator The Step3: Source power comodulation (SPoC) Source Power Comodulation ( Step4: Decoding over tim...
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...
2,562
Given the following text description, write Python code to implement the functionality described below step by step Description: Python API to BeakerX Interactive Plotting You can access Beaker's native interactive plotting library from Python. Plot with simple properties Python plots has syntax very similar to Groovy...
Python Code: from beakerx import * import pandas as pd tableRows = pd.read_csv('../resources/data/interest-rates.csv') Plot(title="Title", xLabel="Horizontal", yLabel="Vertical", initWidth=500, initHeight=200) Explanation: Python API to BeakerX Interactive Plotting You can access Beaker's native int...
2,563
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The Sonnet Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You m...
Python Code: import sys assert sys.version_info >= (3, 6), "Sonnet 2 requires Python >=3.6" !pip install dm-sonnet tqdm import sonnet as snt import tensorflow as tf import tensorflow_datasets as tfds print("TensorFlow version: {}".format(tf.__version__)) print(" Sonnet version: {}".format(snt.__version__)) Explanati...
2,564
Given the following text description, write Python code to implement the functionality described below step by step Description: 5. How to Log and Visualize Simulations Here we explain how to take a log of simulation results and how to visualize it. Step1: 5.1. Logging Simulations with Observers E-Cell4 provides spec...
Python Code: %matplotlib inline import math from ecell4.prelude import * Explanation: 5. How to Log and Visualize Simulations Here we explain how to take a log of simulation results and how to visualize it. End of explanation def create_simulator(f=gillespie.Factory()): m = NetworkModel() A, B, C = Species('A',...
2,565
Given the following text description, write Python code to implement the functionality described below step by step Description: What books topped the Hardcover Fiction NYT best-sellers list on Mother's Day in 2009 and 2010? How about Father's Day? Step1: 2) What are all the different book categories the NYT ranked i...
Python Code: #my IPA key b577eb5b46ad4bec8ee159c89208e220 #base url http://api.nytimes.com/svc/books/{version}/lists import requests response = requests.get("http://api.nytimes.com/svc/books/v2/lists.json?list=hardcover-fiction&published-date=2009-05-10&api-key=b577eb5b46ad4bec8ee159c89208e220") best_seller = response....
2,566
Given the following text description, write Python code to implement the functionality described below step by step Description: Water-filling Visualized This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br> This code illustrates Step1: Specify ...
Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from ipywidgets import interactive import ipywidgets as widgets %matplotlib inline Explanation: Water-filling Visualized This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communic...
2,567
Given the following text description, write Python code to implement the functionality described below step by step Description: A First Look at an X-ray Image Dataset Images are data. They can be 2D, from cameras, or 1D, from spectrographs, or 3D, from IFUs (integral field units). In each case, the data come packaged...
Python Code: from __future__ import print_function import astropy.io.fits as pyfits import numpy as np import os import urllib import astropy.visualization as viz import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 10.0) Explanation: A First Look at an X-ray Image Dataset Images a...
2,568
Given the following text description, write Python code to implement the functionality described below step by step Description: Level 2 Einstieg In diesem Level werden wir lernen, wie die Ausführung von bestimmten Code an Bedingungen knüpfen. Dafür werden wir erst den Typ des boolean und im Anschluss unsere ersten Ko...
Python Code: eingabe = input("Bitte etwas eingeben: ") zahl = int(eingabe) print(zahl) Explanation: Level 2 Einstieg In diesem Level werden wir lernen, wie die Ausführung von bestimmten Code an Bedingungen knüpfen. Dafür werden wir erst den Typ des boolean und im Anschluss unsere ersten Kontrollstrukturen, die if-Bedin...
2,569
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro a Matplotlib Matplotlib = Libreria para graficas cosas matematicas Que es Matplotlib? Matplotlin es un libreria para crear imagenes 2D de manera facil. Checate mas en Step1: Crear gr...
Python Code: import numpy as np # modulo de computo numerico import matplotlib.pyplot as plt # modulo de graficas import pandas as pd # modulo de datos # esta linea hace que las graficas salgan en el notebook %matplotlib inline Explanation: Intro a Matplotlib Matplotlib = Libreria para graficas cosas matematicas Que es...
2,570
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 5 – Support Vector Machines This notebook contains all the sample code and solutions to the exercises in chapter 5. Setup First, let's make sure this notebook works well in both pyth...
Python Code: # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os # to make this notebook's output stable across runs np.random.seed(42) # To plot pretty figures %matplotlib inline import matplotlib import matplotlib.pypl...
2,571
Given the following text description, write Python code to implement the functionality described below step by step Description: Autoregressions This notebook introduces autoregression modeling using the AutoReg model. It also covers aspects of ar_select_order assists in selecting models that minimize an information c...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import pandas_datareader as pdr import seaborn as sns from statsmodels.tsa.ar_model import AutoReg, ar_select_order from statsmodels.tsa.api import acf, pacf, graphics Explanation: Autoregressions This notebook introduces autoregression...
2,572
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Train a DDSP Autoencoder on GPU This notebook demonstrates how to install the DDSP library and train it for synthesis based on your own data using our command-line scr...
Python Code: # Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
2,573
Given the following text description, write Python code to implement the functionality described below step by step Description: SMC2017 Step1: IV.1 Particle Metropolis-Hastings Consider the state-space model $$ \begin{array}{rcll} x_t & = & \cos\left(\theta x_{t - 1}\right) + v_t, &\qquad v_t \sim \mathcal{N}(0, 1)\...
Python Code: import numpy as np from scipy import stats from tqdm import tqdm_notebook %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns sns.set_style() Explanation: SMC2017: Exercise sheet IV Setup End of explanation T = 50 xs_sim = np.zeros((T + 1,)) ys_sim = np.zeros((T,)) # Initial state xs_s...
2,574
Given the following text description, write Python code to implement the functionality described below step by step Description: 用pandas做数据分析 关于数据分析 根据jetbrains公司2018年对python开发人员的调查, 从事数据分析的python使用者超过了 web开发和自动化测试. 在诸多数据科学的框架和库中,numpy pandas是最流行的 而numpy为pandas提供了基础的底层数据结构和处理函数, 用ndarray和ufunc解决了性能问题. ## pandas的核心数据...
Python Code: import pandas as pd x1 = pd.Series([1,2,3,4]) x2 = pd.Series(data=[1,2,3,4], index=['a', 'b', 'c', 'd']) print("x1".center(100,"*")) print(x1) print("x2".center(100,"*")) print(x2) d = {'a':1, 'b':2, 'c':3, 'd':4} x3 = pd.Series(d) print(x3) Explanation: 用pandas做数据分析 关于数据分析 根据jetbrains公司2018年对python开发人员的调查...
2,575
Given the following text description, write Python code to implement the functionality described below step by step Description: Workshop 4 - Performance Metrics In this workshop we study 2 performance metrics(Spread and Inter-Generational Distance) on GA optimizing the POM3 model. Step2: To compute most measures, da...
Python Code: %matplotlib inline # All the imports from __future__ import print_function, division import pom3_ga, sys import pickle # TODO 1: Enter your unity ID here __author__ = "tchhabr" Explanation: Workshop 4 - Performance Metrics In this workshop we study 2 performance metrics(Spread and Inter-Generational Dista...
2,576
Given the following text description, write Python code to implement the functionality described below step by step Description: Weibel instability This notebook shows a demonstration of the Weibel (electromagnetic filamentation) instability in the collision of neutral electron/positron plasma clouds. In this example ...
Python Code: import em2d as zpic eup = zpic.Species( "electrons up", -1.0, ppc = [2,2], ufl = [0.0,0.0,0.6], uth = [0.1,0.1,0.1] ) pup = zpic.Species( "positrons up", +1.0, ppc = [2,2], ufl = [0.0,0.0,0.6], uth = [0.1,0.1,0.1] ) edown = zpic.Species( "electrons down"...
2,577
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimización de funciones escalares diferenciables con Sympy Mediante optimización se obtienen soluciones elegantes tanto en teoría como en ciertas aplicaciones. La teoría de optimización u...
Python Code: # Librería de cálculo simbólico import sympy as sym # Para imprimir en formato TeX from sympy import init_printing; init_printing(use_latex='mathjax') sym.var('x', real = True) f = x**2 f df = sym.diff(f, x) df x_c = sym.solve(df, x) x_c[0] Explanation: Optimización de funciones escalares diferenciables co...
2,578
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Frame the Problem "I think, therefore I am" What type of questions can be answered? Developing a hypothesis drive approach. Making the case. Questions we will answer on alcohol topic acro...
Python Code: # Import the libraries we need, which is Pandas and Numpy import pandas as pd import numpy as np df1 = pd.read_csv('data/drinks2000.csv') df1.head() df1.shape Explanation: 1. Frame the Problem "I think, therefore I am" What type of questions can be answered? Developing a hypothesis drive approach. Making t...
2,579
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Keras를 사용한 반복적 인 신경망 (RNN) <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 내장 RNN 레이어 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,580
Given the following text description, write Python code to implement the functionality described below step by step Description: Average Speed of Answer, Average Handling Time, and After Call Work for Field Support Center <em>Chris Rucker, Associate Data Scientist</em> <em>14 Nov 2016</em> Observation Three discrete q...
Python Code: import pandas as pd import seaborn as sns data = pd.read_csv('C:\Users\crucker\calls.csv') data.head() Explanation: Average Speed of Answer, Average Handling Time, and After Call Work for Field Support Center <em>Chris Rucker, Associate Data Scientist</em> <em>14 Nov 2016</em> Observation Three discrete qu...
2,581
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing Neural Network based Anomaly Detection on actual data This code reads PerfSONAR measured packet loss rates between a specified endpoint and all other endpoints in a selected time ran...
Python Code: %matplotlib inline from elasticsearch import Elasticsearch from elasticsearch.helpers import scan from time import time import numpy as np import pandas as pd import random import matplotlib matplotlib.rc('xtick', labelsize=14) matplotlib.rc('ytick', labelsize=14) import matplotlib.pyplot as plt from sk...
2,582
Given the following text description, write Python code to implement the functionality described below step by step Description: Functions Introduction to Functions This lecture will consist of explaining what a function is in Python and how to create one. Functions will be one of our main building blocks when we cons...
Python Code: def name_of_function(arg1,arg2): ''' This is where the function's Document String (doc-string) goes ''' # Do stuff here #return desired result Explanation: Functions Introduction to Functions This lecture will consist of explaining what a function is in Python and how to create one. Fun...
2,583
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Table of Contents <p><div class="lev1 toc-item"><a href="#Short-study-of-the-Lempel-Ziv-complexity" data-toc-modified-id="Short-study-of-the-Lempel-Ziv-complexity-1"><span class="toc-...
Python Code: def lempel_ziv_complexity(binary_sequence): Lempel-Ziv complexity for a binary sequence, in simple Python code. u, v, w = 0, 1, 1 v_max = 1 length = len(binary_sequence) complexity = 1 while True: if binary_sequence[u + v - 1] == binary_sequence[w + v - 1]: v += ...
2,584
Given the following text description, write Python code to implement the functionality described below step by step Description: Directly compare Monaco to Elekta Linac iCOM This notebook uses the PyMedPhys library to compare the collected iCOM delivery data directly to the recorded plan within Monaco's tel files. Des...
Python Code: import pathlib # for filepath path tooling import lzma # to decompress the iCOM file import numpy as np # for array tooling import matplotlib.pyplot as plt # for plotting Explanation: Directly compare Monaco to Elekta Linac iCOM This notebook uses the PyMedPhys library to compare the collected iCOM del...
2,585
Given the following text description, write Python code to implement the functionality described below step by step Description: DFFs and Registers This example demonstrates the use of d-flip-flops and registers. Step1: DFF To use a DFF we import the mantle circuit DFF. Calling DFF() creates an instance of a DFF. Alt...
Python Code: import magma as m m.set_mantle_target("ice40") Explanation: DFFs and Registers This example demonstrates the use of d-flip-flops and registers. End of explanation from loam.boards.icestick import IceStick from mantle import DFF icestick = IceStick() icestick.Clock.on() # Need to turn on the clock for seque...
2,586
Given the following text description, write Python code to implement the functionality described below step by step Description: On this notebook the best models and input parameters will be searched for. The problem at hand is predicting the price of any stock symbol 14 days ahead, assuming one model for all the symb...
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,587
Given the following text description, write Python code to implement the functionality described below step by step Description: Possible data inputs to DataFrame constructor 2D ndarray A matrix of data, passing optional row and column labels dict of arrays, lists, or tuples Each sequ...
Python Code: state = ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'] year = [2000, 2001, 2002, 2001, 2002] pop = [1.5, 1.7, 3.6, 2.4, 2.9] print(type(state), type(year), type(pop)) # creating dataframe df = pd.DataFrame({'state':state, 'year':year, 'pop':pop}) print(df.info()) print(df) sdata = {'state':state, 'year':year...
2,588
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Text Classification using TensorFlow/Keras on AI Platform </h1> This notebook illustrates Step1: We will look at the titles of articles and figure out whether the article came from the...
Python Code: # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION os.environ['TFVERSION'] = '1.14' if 'COLAB_GPU' in os.environ: # this is ...
2,589
Given the following text description, write Python code to implement the functionality described below step by step Description: Load and preprocess the data. Step1: Create train & test sets. Step2: Define the cost function and how to compute the gradient.<br> Both are needed for the subsequent optimization procedur...
Python Code: data_original = np.loadtxt('stanford_dl_ex/ex1/housing.data') data = np.insert(data_original, 0, 1, axis=1) np.random.shuffle(data) Explanation: Load and preprocess the data. End of explanation train_X = data[:400, :-1] train_y = data[:400, -1] test_X = data[400:, :-1] test_y = data[400:, -1] m, n = train_...
2,590
Given the following text description, write Python code to implement the functionality described below step by step Description: Preliminaries In order to draw the network graphs in these examples (i.e. using r.draw()), you will need graphviz and pygraphviz installed. Please consult the Graphviz documentation for inst...
Python Code: import warnings warnings.filterwarnings("ignore") import tellurium as te te.setDefaultPlottingEngine('matplotlib') %matplotlib inline # model Definition r = te.loada (''' #J1: S1 -> S2; Activator*kcat1*S1/(Km1+S1); J1: S1 -> S2; SE2*kcat1*S1/(Km1+S1); J2: S2 -> S1; Vm2*S2/(Km2+S2); ...
2,591
Given the following text description, write Python code to implement the functionality described below step by step Description: Practical Bin Packing This was motivated by a desire to buy just enough materials to get the job done. In this case the job was a chicken coop I was building. I can buy lumber in standard...
Python Code: import itertools as it import numpy as np import pandas as pd import matplotlib.pyplot as plt stock = np.array([144, 120, 96]) # 12', 10' and 8' lengths rates = np.array([9.17, 8.51, 7.52 ]) # costs for each length (1x4) parts = [84, 72, 54, 36, 30, 30, 24, 24] # list of pieces needed (1x4) minlength ...
2,592
Given the following text description, write Python code to implement the functionality described below step by step Description: Automating Multiple Single-Objective Spatial Optimization Models for Efficiency and Reproducibility James D. Gaboardi &nbsp;&nbsp; | &nbsp;&nbsp; Association of American Geographers 2016 F...
Python Code: import IPython.display as IPd # Local path on user's machine path = '/Users/jgaboardi/AAG_16/Data/' Explanation: Automating Multiple Single-Objective Spatial Optimization Models for Efficiency and Reproducibility James D. Gaboardi &nbsp;&nbsp; | &nbsp;&nbsp; Association of American Geographers 2016 Flori...
2,593
Given the following text description, write Python code to implement the functionality described below step by step Description: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb...
Python Code: import time import numpy as np import tensorflow as tf import utils Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang...
2,594
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: 回帰:燃費を予測する <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: Auto MPG データセット このデータセットはUCI Machine ...
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,595
Given the following text description, write Python code to implement the functionality described below step by step Description: Step4: Copyright 2019 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Step5: Fashion MNIST Classifier Using Keras The code below was presented during the practic...
Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute...
2,596
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 3 Step1: Import libraries Step2: Configure GCP environment settings Update the following variables to reflect the values for your GCP environment Step3: Authenticate your GCP account...
Python Code: !pip install -q -U pip !pip install -q tensorflow==2.2.0 !pip install -q -U google-auth google-api-python-client google-api-core Explanation: Part 3: Create a model to serve the item embedding data This notebook is the third of five notebooks that guide you through running the Real-time Item-to-item Recomm...
2,597
Given the following text description, write Python code to implement the functionality described below step by step Description: 여러개의 Vector를 list로 만들어서 sum 연산을 하는 경우 Step1: Scalar * Vector의 연산 ex) 2 * [1,2,3,4] = [2,4,6,8] Step3: vector 의 평균 구하기 Step5: Vector dot product Step7: 하나의 vector에서 값 element들을 제곱하여 더한 후 ...
Python Code: # Original book version def vector_sum(vectors): return reduce(vector_add, vectors) vectors = [v,w,v,w,v,w] vector_sum(vectors) # Modified version by sc82.choi at Gachon - *은 여러개의 argument를 list로 전환해줌 def vector_sum_modified(vectors): return [sum(value) for value in zip(*vectors)] vectors = [v,w,v...
2,598
Given the following text description, write Python code to implement the functionality described below step by step Description: Session 1 Step1: I'll be using a popular image dataset for faces called the CelebFaces dataset. I've provided some helper functions which you can find on the resources page, which will jus...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') Explanation: Session 1: Introduction to Tensorflow <p class='lead'> Creative Applications of Deep Learning with Tensorflow<br /> Parag K. Mital<br /> Kadenze, Inc.<br /> </p> <a name="learning-goals"></a> Learning...
2,599
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' tar_gz_path = 'cifar-10-python.tar.gz' class DLProgr...