Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
10,200
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Tutorial #16 Reinforcement Learning (Q-Learning) by Magnus Erik Hvass Pedersen / GitHub / Videos on YouTube Introduction This tutorial is about so-called Reinforcement Learning in...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import gym import numpy as np import math # Use TensorFlow v.2 with this old v.1 code. # E.g. placeholder variables and sessions have changed in TF2. import tensorflow.compat.v1 as tf tf.disable_v2_behavior() Explanation: TensorFlow Tutorial #16 Reinforcem...
10,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Character Sequence to Sequence In this notebook, we'll build a model that takes in a sequence of letters, and outputs a sorted version of that sequence. We'll do that using what we've learne...
Python Code: import helper source_path = 'data/letters_source.txt' target_path = 'data/letters_target.txt' source_sentences = helper.load_data(source_path) target_sentences = helper.load_data(target_path) Explanation: Character Sequence to Sequence In this notebook, we'll build a model that takes in a sequence of lette...
10,202
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced model training using hyperopt In the Advanced Model Training tutorial we have already taken a look into hyperparameter optimasation using GridHyperparamOpt in the deepchem pacakge. ...
Python Code: !pip install deepchem !pip install hyperopt Explanation: Advanced model training using hyperopt In the Advanced Model Training tutorial we have already taken a look into hyperparameter optimasation using GridHyperparamOpt in the deepchem pacakge. In this tutorial, we will take a look into another hyperpara...
10,203
Given the following text description, write Python code to implement the functionality described below step by step Description: Econophysics Names of group members // put your names here! Goals of this assignment Witness what we call "emergent behavior"; large patterns manifesting from the simple interactions of tiny...
Python Code: # Use Python to make a filled-in plot # from the data that got reported out Explanation: Econophysics Names of group members // put your names here! Goals of this assignment Witness what we call "emergent behavior"; large patterns manifesting from the simple interactions of tiny agents Develop a graphica...
10,204
Given the following text description, write Python code to implement the functionality described below step by step Description: Instalación Lo primero es instalar Python. Para ello, la mejor forma es bajarse Anaconda, está disponible en Windows, Linux y MacOS. <img src="http Step1: Crear un entorno Anaconda nos per...
Python Code: #from IPython.display import HTML #HTML('''<script> #code_show=true; #function code_toggle() { # if (code_show){ # $('div.input').hide(); # } else { # $('div.input').show(); # }# # code_show = !code_show #} #$( ocument ).ready(code_toggle); #</script> #The raw code for this IPython notebook is by default...
10,205
Given the following text description, write Python code to implement the functionality described below step by step Description: The number of unique values is huge. This makes me think in a direction where we could center basis functions at the centers of discovered clusters. Discover cluster centers via K-Means? Ste...
Python Code: train_X = train.values[:,:-1] train_t = train.values[:,-1] print train_X.shape print train_t.shape train.describe() train.head() train.tail() Explanation: The number of unique values is huge. This makes me think in a direction where we could center basis functions at the centers of discovered clusters. Dis...
10,206
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: 加载和准备数据集 您将使用 MNIST 数据集来训练生成器和判别...
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...
10,207
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex SDK Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the additional packages, you need to restart the no...
Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG Explanation: Vertex SDK: Custom training tabular regression model for batch prediction <table align="l...
10,208
Given the following text description, write Python code to implement the functionality described below step by step Description: Preprocessing For local run, we cannot afford running with full data. We will sample the data randomly (using hash) to about 200~300 instances. It takes about 15 minutes. Step1: Train To ge...
Python Code: import mltoolbox.image.classification as model from google.datalab.ml import * worker_dir = '/content/datalab/tmp/coast' preprocessed_dir = worker_dir + '/coast300' model_dir = worker_dir + '/model300' train_set = BigQueryDataSet('SELECT image_url, label FROM coast.train WHERE rand() < 0.04') model.preproc...
10,209
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Data You'll often want to compare data in your dataset, to see if you can discern trends or relationships. Univariate Data Univariate data is data that consist of only one variable...
Python Code: %matplotlib inline import pandas as pd from matplotlib import pyplot as plt df = pd.DataFrame({'Name': ['Dan', 'Joann', 'Pedro', 'Rosie', 'Ethan', 'Vicky', 'Frederic', 'Jimmie', 'Rhonda', 'Giovanni', 'Francesca', 'Rajab', 'Naiyana', 'Kian', 'Jenny'], 'Grade':[50,50,46,95,50,5,57,42,26,72...
10,210
Given the following text description, write Python code to implement the functionality described below step by step Description: FPE Interface Board Bring-up Procedure Abstract Step1: Test Start Date Step2: Test Conductor Information Please write down your personal information for accountability purposes Step3: Uni...
Python Code: import random test_check = {} Explanation: FPE Interface Board Bring-up Procedure Abstract: This iPython Notebook contains instructions for the FPE Interface Board PCB Bring-up test flow. This procedure can be used for the Interface Boards, versions 6.2 and 7.0. Simliar iPython Notebooks will be created ...
10,211
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Basics with Numpy (optional assignment) Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help fam...
Python Code: ### START CODE HERE ### (≈ 1 line of code) test = 'Hello World' ### END CODE HERE ### print ("test: " + test) Explanation: Python Basics with Numpy (optional assignment) Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will he...
10,212
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: MLE fit for three component binding - simulated data In this notebook we will see how well we can reproduce Kd of a non-fluorescent ligand from simulated experimental data with a maxi...
Python Code: import numpy as np import matplotlib.pyplot as plt from scipy import optimize import seaborn as sns %pylab inline #Competitive binding function #This function and its assumptions are defined in greater detail in this notebook: ## modelling-CompetitiveBinding-ThreeComponentBinding.ipynb def three_component...
10,213
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to Time Series! Forecasting is perhaps the most common application of machine learning in the real world. Businesses forecast product demand, governments forecast economic and popula...
Python Code: #$HIDE_INPUT$ import pandas as pd df = pd.read_csv( "../input/ts-course-data/book_sales.csv", index_col='Date', parse_dates=['Date'], ).drop('Paperback', axis=1) df.head() Explanation: Welcome to Time Series! Forecasting is perhaps the most common application of machine learning in the real wor...
10,214
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: RASP Diabetes Rates Diabetes rates from CHIS surveys for 2015, 2016 and 2017, segmented by race, age, sex and poverty status Step3: Poverty, Age and Race Step4: Compare to CHIS Here...
Python Code: import seaborn as sns import metapack as mp import pandas as pd import numpy as np import matplotlib.pyplot as plt from IPython.display import display from publicdata.chis import * %matplotlib inline sns.set_context('notebook') idx = pd.IndexSlice # Convenience redefinition. #pkg = mp.jupyter.open_packag...
10,215
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Input To do any computation, you need to have data. Getting the data in the framework of a workflow is therefore the first step of every analysis. Nipype provides many different modules...
Python Code: from nipype import DataGrabber, Node # Create DataGrabber node dg = Node(DataGrabber(infields=['subject_id', 'task_id'], outfields=['anat', 'func']), name='datagrabber') # Location of the dataset folder dg.inputs.base_directory = '/data/ds102' # Necessary default parameters ...
10,216
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
10,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Import directives Step1: Ordered dictionaries See https
Python Code: import collections Explanation: Import directives End of explanation d = collections.OrderedDict() d["2"] = 2 d["3"] = 3 d["1"] = 1 print(d) print(type(d.keys())) print(list(d.keys())) print(type(d.values())) print(list(d.values())) for k, v in d.items(): print(k, v) Explanation: Ordered dictionaries S...
10,218
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2> 4ppm </h2> Enough retcor groups, and fewer peak insertion problems than 4.5 or 5ppm. Step1: <h2> Import the dataframe and remove any features that are all zero </h2> Step2: <h2> Get m...
Python Code: import time import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.cross_validation import cross_val_score #fr...
10,219
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Merge overlapping striplogs Imagine we have a Striplog with overlapping Interval. We would like to be able to merge the Intervals in this Striplog, while following some rules about pr...
Python Code: from striplog import Striplog csv = Top,Base,Comp Time,Comp Depth 100,200,2,a 110,120,1,b 150,325,3,c 210,225,1,d 300,400,2,e 350,375,3,f s = Striplog.from_csv(text=csv) Explanation: Merge overlapping striplogs Imagine we have a Striplog with overlapping Interval. We would like to be able to merge the Inte...
10,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Python's super() TODO * https Step1: Sans super() Avant l'existance de la fonction super(), we would have hardwired the call with A.bonjour(self). ... Step2: Le même exemple avec un argume...
Python Code: help(super) Explanation: Python's super() TODO * https://docs.python.org/3/library/functions.html#super * https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ * https://stackoverflow.com/questions/904036/chain-calling-parent-constructors-in-python * https://stackoverflow.com/questions/239930...
10,221
Given the following text description, write Python code to implement the functionality described below step by step Description: GPy GPy is a framework for Gaussian process based applications. It is design for speed and reliability. The main three pillars of its functionality are made of Ease of use Reproduceability ...
Python Code: import GPy, numpy as np from matplotlib import pyplot as plt %matplotlib inline Explanation: GPy GPy is a framework for Gaussian process based applications. It is design for speed and reliability. The main three pillars of its functionality are made of Ease of use Reproduceability Scalability In this tuto...
10,222
Given the following text description, write Python code to implement the functionality described below step by step Description: EventVestor Step1: Let's go over the columns Step2: Now suppose we want a DataFrame of the Blaze Data Object above, want to filter it further down to the announcements only, and we only wa...
Python Code: # import the dataset from quantopian.interactive.data.eventvestor import issue_equity # or if you want to import the free dataset, use: # from quantopian.interactive.data.eventvestor import issue_equity_free # import data operations from odo import odo # import other libraries we will use import pandas as ...
10,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Background on projectors and projections This tutorial provides background information on projectors and Signal Space Projection (SSP), and covers loading and saving projectors, adding and r...
Python Code: import os import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa from scipy.linalg import svd import mne def setup_3d_axes(): ax = plt.axes(projection='3d') ax.view_init(azim=-105, elev=20) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('...
10,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Explicit Solutions This notebook will show how to fit explicit solutions to summary measures. It will first fit the Rescorla-Wagner model to the trial-by-trial response rates. It will then f...
Python Code: # System packages import sys # Storing and manipulating data... import pandas as pd import numpy as np from scipy.optimize import curve_fit, minimize from scipy.stats import norm, pearsonr # Plotting... import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline plt.rc('text', usetex=True) # T...
10,225
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Google LLC. Licensed under the Apache License, Version 2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with ...
Python Code: #@title Run this cell after making your choices. allow_data_collection = True #@param {type: "boolean"} include_in_dataset = True #@param {type: "boolean"} if allow_data_collection: if include_in_dataset: print('Usage data may be collected and released in a public dataset.') else: print('Usag...
10,226
Given the following text description, write Python code to implement the functionality described below step by step Description: Explainable deep-learning -- Visualizing deep neural networks Author Step1: Function to load the model for generating predictions Step2: Function to generate predictions Step3: Function t...
Python Code: import sys import argparse import numpy as np import requests import matplotlib matplotlib.use('Agg') import os import time import json import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import tqdm from io import BytesIO from PIL import Image from keras.preprocessing import image ...
10,227
Given the following text description, write Python code to implement the functionality described below step by step Description: Fine-tuning a Pretrained Network for Style Recognition In this example, we'll explore a common approach that is particularly useful in real-world applications Step1: 1. Setup and dataset do...
Python Code: caffe_root = '../' # this file should be run from {caffe_root}/examples (otherwise change this line) import sys sys.path.insert(0, caffe_root + 'python') import caffe caffe.set_device(0) caffe.set_mode_gpu() import numpy as np from pylab import * %matplotlib inline import tempfile # Helper function for de...
10,228
Given the following text description, write Python code to implement the functionality described below step by step Description: Calling Functions from Functions Step2: Interating over a collection Make the 12 x 12 times table Step3: Iterating over a list of strings Shows how to iterate over strings and that you can...
Python Code: def add_together(one, two): one = one + two return one def mutiply_and_add(one, two): one = add_together(one, two) return one * one temparary_value = mutiply_and_add(2, 3) print(temparary_value) print(mutiply_and_add(2, 3)) Explanation: Calling Functions from Functions End of explanation nu...
10,229
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Quantum Double-slit Experiment Step2: Now define the double_slit function and make it interactive
Python Code: %pylab inline import numpy as np import matplotlib.pyplot as plot from scipy.integrate import trapz,cumtrapz from IPython.html.widgets import interact, interactive def distribute1D(x,prob,N): takes any distribution which is directly proportional to the number of particles, and returns data that is...
10,230
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Cookbook-for-cantera_tools-module" data-toc-modified-id="Cookbook-for-cantera_tools-module-1"><span class="toc-item-num">1&nbsp;&nbs...
Python Code: import cantera_tools as ctt import numpy as np from scipy import integrate import cantera as ct import pandas as pd import matplotlib.pyplot as plt %matplotlib inline Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Cookbook-for-cantera_tools-module" data-toc-modified-id="Cookbook-for...
10,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Image Gradients In this notebook we'll introduce the TinyImageNet dataset and a deep CNN that has been pretrained on this dataset. You will use this pretrained model to compute gradients wit...
Python Code: # As usual, a bit of setup import time, os, json import numpy as np import skimage.io import matplotlib.pyplot as plt from cs231n.classifiers.pretrained_cnn import PretrainedCNN from cs231n.data_utils import load_tiny_imagenet from cs231n.image_utils import blur_image, deprocess_image %matplotlib inline pl...
10,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 3 Step1: Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers...
Python Code: import graphlab Explanation: Regression Week 3: Assessing Fit (polynomial regression) In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will: * Write a function t...
10,233
Given the following text description, write Python code to implement the functionality described below step by step Description: Insights from medical posts In this notebook, I try to find characteristics of medical posts. What is the ratio of post from professionals vs. those from general public? What are the char...
Python Code: # Set up paths/ os import os import sys this_path=os.getcwd() os.chdir("../data") sys.path.insert(0, this_path) # Load datasets import pandas as pd df = pd.read_csv("MedHelp-posts.csv",index_col=0) df.head(2) df_users = pd.read_csv("MedHelp-users.csv",index_col=0) df_users.head(2) # 1 classify users as pr...
10,234
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep LSTM RNNs Step1: Dataset Step2: Check the data real quick Step3: Preparing the data for training Step4: Long short-term memory (LSTM) RNNs An LSTM block has mechanisms to enable "me...
Python Code: from __future__ import print_function import mxnet as mx from mxnet import nd, autograd import numpy as np from collections import defaultdict mx.random.seed(1) # ctx = mx.gpu(0) ctx = mx.cpu(0) %matplotlib inline import matplotlib import matplotlib.pyplot as plt import seaborn as sns import pandas as pd f...
10,235
Given the following text description, write Python code to implement the functionality described below step by step Description: ATM 623 Step1: Contents Emission temperature and lapse rates Solar Radiation Terrestrial Radiation and absorption spectra <a id='section1'></a> 1. Emission temperature and lapse rates Plane...
Python Code: # Ensure compatibility with Python 2 and 3 from __future__ import print_function, division Explanation: ATM 623: Climate Modeling Brian E. J. Rose, University at Albany Lecture 6: A Brief Review of Radiation Warning: content out of date and not maintained You really should be looking at The Climate Labora...
10,236
Given the following text description, write Python code to implement the functionality described below step by step Description: Google Hashcode 2022 Google Hashcode is a team programming competition to solve a complex engineering problem. In this notebook we are showing how Mathematical Optimization methods as Mixed ...
Python Code: import os if not os.path.isdir('input_data'): os.system('git clone https://github.com/ampl/amplpy.git') os.chdir('amplpy/notebooks/hashcode') if not os.path.isdir('ampl_input'): os.mkdir('ampl_input') Explanation: Google Hashcode 2022 Google Hashcode is a team programming competition to solve a c...
10,237
Given the following text description, write Python code to implement the functionality described below step by step Description: 在 python 中,下划线命名规则往往令人相当疑惑:单下划线、双下划线、双下划线还分前后……那它们的作用与使用场景到底有何区别呢? 1、单下划线(_) 通常情况下,单下划线(_)会在以下3种场景中使用: 1.1 在解释器中: 在这种情况下,“_”代表交互式解释器会话中上一条执行的语句的结果。这种用法首先被标准CPython解释器采用,然后其他类型的解释器也先后采用。 Step...
Python Code: 8 * 9 _ + 8 Explanation: 在 python 中,下划线命名规则往往令人相当疑惑:单下划线、双下划线、双下划线还分前后……那它们的作用与使用场景到底有何区别呢? 1、单下划线(_) 通常情况下,单下划线(_)会在以下3种场景中使用: 1.1 在解释器中: 在这种情况下,“_”代表交互式解释器会话中上一条执行的语句的结果。这种用法首先被标准CPython解释器采用,然后其他类型的解释器也先后采用。 End of explanation for _ in range(1, 11): print(_, end='、 ') Explanation: 1.2 作为一个名称: 这与上面一点...
10,238
Given the following text description, write Python code to implement the functionality described below step by step Description: OpenStreetMap的OSM文件对象数据分类捡取器 by openthings@163.com, 2016-03-21. 功能: 输出三个单行存储的json文件,可在Spark中使用,通过spark的sc.read.json()直接读入处理。 本工具将osm文件按照tag快速分类,直接转为node/way/relation三个json文件,并按行存储。 说明: S...
Python Code: import os import time import json from pprint import * import lxml from lxml import etree import xmltodict, sys, gc from pymongo import MongoClient gc.enable() #Enable Garbadge Collection # 将指定tag的对象提取,写入json文件。 def process_element(elem): elem_data = etree.tostring(elem) elem_dict = xmltodict.pars...
10,239
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning Scikit-learn Step1: Import the digits dataset (http Step2: Let's show how the digits look like... Step3: Now, let's define a function that will plot a scatter with the two-dimens...
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...
10,240
Given the following text description, write Python code to implement the functionality described below step by step Description: Redcard Exploratory Data Analysis This dataset is taken from a fantastic paper that looks to see how analytical choices made by different data science teams on the same dataset in an attempt...
Python Code: %matplotlib inline %config InlineBackend.figure_format='retina' from __future__ import absolute_import, division, print_function import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib.pyplot import GridSpec import seaborn as sns import numpy as np import pandas as pd import os, sys f...
10,241
Given the following text description, write Python code to implement the functionality described below step by step Description: N.B., Cannot use 32-bit programmable interrupt timer (PIT) to trigger periodic DMA due to hardware bug. See here. The solution shown below uses the 16-bit programmable delay block (PDB). Dis...
Python Code: import pandas as pd def get_pdb_divide_params(frequency, F_BUS=int(48e6)): mult_factor = np.array([1, 10, 20, 40]) prescaler = np.arange(8) clock_divide = (pd.DataFrame([[i, m, p, m * (1 << p)] for i, m in enumerate(mult_factor) ...
10,242
Given the following text description, write Python code to implement the functionality described below step by step Description: Quick Guide Toytree is a Python tree plotting library designed for use inside jupyter notebooks. In fact, this entire tutorial was created using notebooks, and assumes that you are followin...
Python Code: import toytree # a tree plotting library import toyplot # a general plotting library import numpy as np # numerical library print(toytree.__version__) print(toyplot.__version__) print(np.__version__) Explanation: Quick Guide Toytree is a Python tree plotting library designed for use inside j...
10,243
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color='teal'> Introduction to Neural Networks and Pytorch </font> Notebook version Step1: <font color='teal'> 1. Introduction and purpose of this Notebook </font> <font color='teal'> ...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline size = 18 params = {'legend.fontsize': 'Large', 'axes.labelsize': size, 'axes.titlesize': size, 'xtick.labelsize': size*0.75, 'ytick.labelsize': size*0.75} plt.rcParams.update(params) Explanation: ...
10,244
Given the following text description, write Python code to implement the functionality described below step by step Description: Backpropagation Step1: Variables & Terminology $W_{i}$ - weights of the $i$th layer $B_{i}$ - biases of the $i$th layer $L_{a}^{i}$ - activation (Inner product of weights and inputs of prev...
Python Code: from IPython.display import Image Image("mlp.png", height=200, width=600) Explanation: Backpropagation End of explanation from IPython.display import YouTubeVideo YouTubeVideo("LOc_y67AzCA") import numpy as np from utils import backprop_decision_boundary, backprop_make_classification, backprop_make_moons f...
10,245
Given the following text description, write Python code to implement the functionality described below step by step Description: Target Function Lets create a target 1-D function with multiple local maxima to test and visualize how the BayesianOptimization package works. The target function we will try to maximize is ...
Python Code: def target(x): return np.exp(-(x - 2)**2) + np.exp(-(x - 6)**2/10) + 1/ (x**2 + 1) x = np.linspace(-2, 10, 1000) y = target(x) plt.plot(x, y) Explanation: Target Function Lets create a target 1-D function with multiple local maxima to test and visualize how the BayesianOptimization package works. The t...
10,246
Given the following text description, write Python code to implement the functionality described below step by step Description: verify pyEMU Influence class Step1: instaniate pyemu object and drop prior info. Then reorder the jacobian and save as binary. This is needed because the pest utilities require strict ord...
Python Code: %matplotlib inline import os import shutil import numpy as np import matplotlib.pyplot as plt import pandas as pd import pyemu Explanation: verify pyEMU Influence class End of explanation pst = pyemu.Pst("freyberg.pst") pst.pestpp_options = {} inf = pyemu.Influence(jco="freyberg.jcb",pst=pst,verbose=False)...
10,247
Given the following text description, write Python code to implement the functionality described below step by step Description: Kernel Approximations for Large-Scale Non-Linear Learning Predictions in a kernel-SVM are made using the formular $$ \hat{y} = \alpha_1 y_1 k(\mathbf{x^{(1)}}, \mathbf{x}) + ... + \alpha_n y...
Python Code: from helpers import Timer from sklearn.datasets import load_digits from sklearn.cross_validation import train_test_split digits = load_digits() X, y = digits.data / 16., digits.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) Explanation: Kernel Approximations for Large-Scal...
10,248
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting workbook Plotting workbook to accompany the paper Carbon Capture and Storage Energy Systems vs. Dispatchable Renewables for Climate Mitigation Step1: Eq. 6 Define EROI-CCS function...
Python Code: import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.font_manager as font_manager plt.style.use('seaborn-darkgrid') %matplotlib inline prop = font_manager.FontProperties('Segoe UI') from sympy import * init_printing() Explanation: Plotting workbook Plotting workbook to accompany the ...
10,249
Given the following text description, write Python code to implement the functionality described below step by step Description: Decorators Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more "Pythonic". To properly explain decorat...
Python Code: def func(): return 1 func() Explanation: Decorators Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more "Pythonic". To properly explain decorators we will slowly build up from functions. Make sure to restart the Pyt...
10,250
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Dataset API Learning Objectives 1. Learn how use tf.data to read data from memory 1. Learn how to use tf.data in a training loop 1. Learn how use tf.data to read data from disk 1....
Python Code: # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.0 || pip install tensorflow==2.0 import json import math import os from pprint import pprint import numpy as np import tensorflow as tf print(tf.version.VERSION) Explanation: TensorFlow Dataset API Learning Objectives 1...
10,251
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
10,252
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear models for regression y_pred = x_test[0] * coef_[0] + ... + x_test[n_features-1] * coef_[n_features-1] + intercept_ Step1: Linear Regression Step2: Ridge Regression (L2 penalty) Ste...
Python Code: from sklearn.datasets import make_regression from sklearn.cross_validation import train_test_split X, y, true_coefficient = make_regression(n_samples=80, n_features=30, n_informative=10, noise=100, coef=True, random_state=5) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=5) print(X_...
10,253
Given the following text description, write Python code to implement the functionality described below step by step Description: Radio Frequency Interference mitigation using deep convolutional neural networks This example demonstrates how tf_unet is trained on the 'Bleien Galactic Survey data'. To create the training...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib import numpy as np import glob plt.rcParams['image.cmap'] = 'gist_earth' Explanation: Radio Frequency Interference mitigation using deep convolutional neural networks This example demonstrates how tf_unet is trained on the 'Bleien Galacti...
10,254
Given the following text description, write Python code to implement the functionality described below step by step Description: Le but de cet exemple est de calculer, pour chaque décile de revenu, la part de leur consommation que les ménages accordent à chaque catégorie de bien. Les catégories suivent le niveau le pl...
Python Code: from __future__ import division import pandas import seaborn Explanation: Le but de cet exemple est de calculer, pour chaque décile de revenu, la part de leur consommation que les ménages accordent à chaque catégorie de bien. Les catégories suivent le niveau le plus agrégé de la nomenclature COICOP. Import...
10,255
Given the following text description, write Python code to implement the functionality described below step by step Description: Update TOC trends analysis Tore has previously written code to calculate Mann-Kendall (M-K) trend statistics and Sen's slope estimates for data series in RESA2. According to my notes from a ...
Python Code: # Read data and results from the Excel macro in_xlsx = (r'C:\Data\James_Work\Staff\Heleen_d_W\ICP_Waters\TOC_Trends_Analysis_2015' r'\Data\mk_sen_test_data.xlsx') raw_df = pd.read_excel(in_xlsx, sheetname='input') res_df = pd.read_excel(in_xlsx, sheetname='results') raw_df res_df Explanation: Up...
10,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Gather summary statistics from network outputs This example script displays the use of emu to estimate normal distribution parameters from the output of each convolutional layer in a given p...
Python Code: import sys import os import numpy as np from collections import OrderedDict import matplotlib.pyplot as plt %matplotlib inline Explanation: Gather summary statistics from network outputs This example script displays the use of emu to estimate normal distribution parameters from the output of each convoluti...
10,257
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Text classification with TensorFlow Lite Model Maker <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="http...
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...
10,258
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing logistic regression from scratch The goal of this notebook is to implement your own logistic regression classifier. We will Step1: Load review dataset For this assignment, we w...
Python Code: # Run some setup code for this notebook. import sys import os sys.path.append('..') import graphlab Explanation: Implementing logistic regression from scratch The goal of this notebook is to implement your own logistic regression classifier. We will: Extract features from Amazon product reviews. Convert an...
10,259
Given the following text description, write Python code to implement the functionality described below step by step Description: Brainstorm auditory tutorial dataset Here we compute the evoked from raw for the auditory Brainstorm tutorial dataset. For comparison, see [1]_ and Step1: To reduce memory consumption and r...
Python Code: # Authors: Mainak Jas <mainak.jas@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # Jaakko Leppakangas <jaeilepp@student.jyu.fi> # # License: BSD (3-clause) import os.path as op import pandas as pd import numpy as np import mne from mne import combine_evoked from mne.minimum...
10,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulation of a Noddy history and analysis of its voxel topology Example of how the module can be used to run Noddy simulations and analyse the output. Step1: Compute the model The simplest...
Python Code: from IPython.core.display import HTML css_file = 'pynoddy.css' HTML(open(css_file, "r").read()) # Basic settings import sys, os import subprocess # Now import pynoddy import pynoddy %matplotlib inline # determine path of repository to set paths corretly below repo_path = os.path.realpath('../..') Explanati...
10,261
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Scaling up ML using Cloud ML Engine </h1> In this notebook, we take a previously developed TensorFlow model to predict taxifare rides and package it up so that it can be run in Cloud ML...
Python Code: import os PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID REGION = 'us-central1' # Choose an available region for Cloud MLE from https://cloud.google.com/ml-engine/docs/regions. BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME. Use a regional bucket in the region you selec...
10,262
Given the following text description, write Python code to implement the functionality described below step by step Description: Discrete probability distributions Rigorous definitions of discrete probability laws and discrete random variables are provided in part 00. By reading this part or from your own education, y...
Python Code: N = 6 xk = np.arange(1,N+1) fig, ax = plt.subplots(1, 1) ax.plot(xk, sps.randint.pmf(xk, xk[0], 1+xk[-1]), 'ro', ms=12, mec='r') ax.vlines(xk, 0, sps.randint.pmf(xk, xk[0], 1+xk[-1]), colors='r', lw=4) plt.show() Explanation: Discrete probability distributions Rigorous definitions of discrete probability l...
10,263
Given the following text description, write Python code to implement the functionality described below step by step Description: bqplot This notebook is meant to guide you through the first stages of using the bqplot visualization library. bqplot is a Grammar of Graphics based interactive visualization library for the...
Python Code: # Let's begin by importing some libraries we'll need import numpy as np # And creating some random data size = 100 np.random.seed(0) x_data = np.arange(size) y_data = np.cumsum(np.random.randn(size) * 100.0) Explanation: bqplot This notebook is meant to guide you through the first stages of using the bqplo...
10,264
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaussian Processes in Shogun By Heiko Strathmann - <a href="mailto Step1: Some Formal Background (Skip if you just want code examples) This notebook is about Bayesian regression models with...
Python Code: %matplotlib inline # import all shogun classes from modshogun import * import random import numpy as np import matplotlib.pyplot as plt from math import exp Explanation: Gaussian Processes in Shogun By Heiko Strathmann - <a href="mailto:heiko.strathmann@gmail.com">heiko.strathmann@gmail.com</a> - <a href="...
10,265
Given the following text description, write Python code to implement the functionality described below step by step Description: Mining Ulysses Step1: A better method in Python 3 is - Step2: These are the words that appear more than 200 times and I have excluded the really common words (greater than 944 times)
Python Code: s clean_s = removeDelimiter(s," ",[".",",",";","_","-",":","!","?","\"",")","("]) wordlist = clean_s.split() dictionary = {} for word in wordlist: if word in dictionary: tmp = dictionary[word] dictionary[word]=tmp+1 else: dictionary[word]=1 import operator sorted_dict = sorted(dictionary.items(), k...
10,266
Given the following text description, write Python code to implement the functionality described below step by step Description: Scratch dans un notebook Il existe une version javascript de Scratch Step1: Si le résultat est vide, cela signifie que les fichiers ont déjà été copiés. On veut obtenir ceci Step4: On ex...
Python Code: import code_beatrix.jsscripts.snap %load_ext code_beatrix import os, glob js_path = os.path.dirname(code_beatrix.jsscripts.snap.__file__) files = [ os.path.split(_)[-1] for _ in glob.glob(js_path + "/*.js") ] print(",".join(files)) path = "/static/snap/" js_libs = [path + _ for _ in files ] import notebook...
10,267
Given the following text description, write Python code to implement the functionality described below step by step Description: Time Series Prediction with LSTM Recurrent Neural Networks in Python with Keras 時系列データの予測 Step1: データセットの作成 Step2: 活性化関数にsigmoidやtanhを使うときは入力のスケールに大きな影響をうける 入力は[0, 1]に正規化するとよい scikit-learnの...
Python Code: %matplotlib inline import pandas import matplotlib.pyplot as plt dataset = pandas.read_csv('data/international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=3) plt.plot(dataset) plt.show() dataset Explanation: Time Series Prediction with LSTM Recurrent Neural N...
10,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting Marginal Generating Units in ERCOT Project Goals and Model Choices The goal of this project is to build a model that can predict the type of fossil marginal generating units (MGU)...
Python Code: from IPython.display import SVG SVG('https://www.dropbox.com/s/k8ac0la03hkjo5f/ERCOT%20power%20plants%202007.svg?raw=1') Explanation: Predicting Marginal Generating Units in ERCOT Project Goals and Model Choices The goal of this project is to build a model that can predict the type of fossil marginal gener...
10,269
Given the following text description, write Python code to implement the functionality described below step by step Description: Basics Step1: Let's create a simple regular 10x10 degree grid with grid points at the center of each 10x10 degree cell. First by hand to understand what is going on underneath Step2: These...
Python Code: import pygeogrids.grids as grids import numpy as np Explanation: Basics End of explanation # create the longitudes lons = np.arange(-180 + 5, 180, 10) print(lons) lats = np.arange(90 - 5, -90, -10) print(lats) Explanation: Let's create a simple regular 10x10 degree grid with grid points at the center of ea...
10,270
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare Solutions - Homogenous 3D Brendan Smithyman | November 2015 This notebook shows comparisons between the responses of the different solvers. Step1: Error plots for MiniZephyr vs. the...
Python Code: import sys sys.path.append('../') import numpy as np from zephyr.backend import MiniZephyr25D, SparseKaiserSource, AnalyticalHelmholtz import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('p...
10,271
Given the following text description, write Python code to implement the functionality described below step by step Description: MixUp and Friends Callbacks that can apply the MixUp (and variants) data augmentation to your training Step1: Most Mix variants will perform the data augmentation on the batch, so to implem...
Python Code: from fastai.vision.all import * #|export def reduce_loss( loss:Tensor, reduction:str='mean' # PyTorch loss reduction )->Tensor: "Reduce the loss based on `reduction`" return loss.mean() if reduction == 'mean' else loss.sum() if reduction == 'sum' else loss #|export class MixHandler(Callbac...
10,272
Given the following text description, write Python code to implement the functionality described below step by step Description: Annonce La branche étudiante de l'IEEE propose, ce jeudi 25 février de 13 h 30 à 17 h 30, une formation à Mathematica pour donner les bases de ce logiciel. L'inscription est nécessaire. http...
Python Code: from __future__ import division Explanation: Annonce La branche étudiante de l'IEEE propose, ce jeudi 25 février de 13 h 30 à 17 h 30, une formation à Mathematica pour donner les bases de ce logiciel. L'inscription est nécessaire. http://ieee.aees.be/fr/accueil/25-francais/activites/conferences/151-formati...
10,273
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas Data Munging Step1: ...and you want to filter it on some criteria. Pandas makes that easy with Boolean Indexing Step2: This works great right? Unfortunately not, because once we Ste...
Python Code: import pandas as pd df = pd.DataFrame({'Number' : [100,200,300,400,500], 'Letter' : ['a','b','c', 'd', 'e']}) df Explanation: Pandas Data Munging: Avoiding that 'SettingWithCopyWarning' If you use Python for data analysis, you probably use Pandas for Data Munging. And if you use Pandas, you've probably com...
10,274
Given the following text description, write Python code to implement the functionality described below step by step Description: Demo 1 - Single forward problem [local] Brendan Smithyman | bsmithym@uwo.ca | March, 2015 Import NumPy Step1: Import plotting tools from matplotlib and set format defaults Step2: Base syst...
Python Code: import numpy as np Explanation: Demo 1 - Single forward problem [local] Brendan Smithyman | bsmithym@uwo.ca | March, 2015 Import NumPy End of explanation import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib %matplotlib inline from IPython.display import set_matplotlib_formats set_ma...
10,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Nested Statements and Scope Now that we have gone over on writing our own functions, its important to understand how Python deals with the variable names you assign. When you create a variab...
Python Code: x = 25 def printer(): x = 50 return x print (x) print (printer()) Explanation: Nested Statements and Scope Now that we have gone over on writing our own functions, its important to understand how Python deals with the variable names you assign. When you create a variable name in Python the name is ...
10,276
Given the following text description, write Python code to implement the functionality described below step by step Description: Encoder-Decoder Analysis Model Architecture Step1: Perplexity on Each Dataset Step2: Loss vs. Epoch Step3: Perplexity vs. Epoch Step4: Generations Step5: BLEU Analysis Step6: N-pairs B...
Python Code: report_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drb/encdec_noing10_200_512_04drb.json' log_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_200_512_04drb/encdec_noing10_200_512_04drb_logs.json' import json import matp...
10,277
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Now, you'll use what you learned in the previous tutorial to improve the efficiency of several queries. Before you get started, run the following cell to set everything up. Step...
Python Code: # Set up feedback system from learntools.core import binder binder.bind(globals()) from learntools.sql_advanced.ex4 import * print("Setup Complete") Explanation: Introduction Now, you'll use what you learned in the previous tutorial to improve the efficiency of several queries. Before you get started, run ...
10,278
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Measure-Dynamic-Functional-Connectivity" data-toc-modified-id="Measure-Dynamic-Functional-Connectivity-1"><span class="toc-item-num"...
Python Code: try: %load_ext autoreload %autoreload 2 %reset except: print 'NOT IPYTHON' from __future__ import division import os import sys import glob import numpy as np import pandas as pd import seaborn as sns import scipy.stats as stats import statsmodels.api as sm import scipy.io as io import h5py...
10,279
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: draw a pairplot using python for tips dataset and for column sex in the given dataset
Python Code:: sns.pairplot(tips , hue = ''sex', palette = 'coolwarm')
10,280
Given the following text description, write Python code to implement the functionality described below step by step Description: Benchmarking of various implementations of FADDEEVA's error functions I. Setup Import the multiprecision library mpmath as a reference for accuracy benchmarks Step1: Import the rest of the ...
Python Code: import mpmath Explanation: Benchmarking of various implementations of FADDEEVA's error functions I. Setup Import the multiprecision library mpmath as a reference for accuracy benchmarks: End of explanation import numpy as np import scipy import ctypes import sys Explanation: Import the rest of the usual lo...
10,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Read OpendTect horizons The best way to export horizons from OpendTect is with these options Step1: IL/XL and XY, multi-line header, multiple attributes Load everything (default) X and Y ar...
Python Code: import gio ds = gio.read_odt('../../data/OdT/3d_horizon/Segment_ILXL_Single-line-header.dat') ds ds['twt'].plot() Explanation: Read OpendTect horizons The best way to export horizons from OpendTect is with these options: x/y and inline/crossline with header (single or multi-line, it doesn't matter) choose ...
10,282
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploracion y Visualizacion de Bases de Datos Para el siguiente ejemplo tomaremos como referencia el archivo snie1213.csv que se encuentra en la carpeta data, esta base de datos contiene los...
Python Code: # librerias import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.formula.api as sm import seaborn as sns %matplotlib inline plt.style.use('ggplot') # leer archivo data = pd.read_csv('../data/snie1213.csv', low_memory=False) # verificar su contenido data.head() data.info...
10,283
Given the following text description, write Python code to implement the functionality described below step by step Description: Raspberry Pi Programming GPIO digital output Following example sets PIN18 to High(3.3V). Python's import statement includes external library GPIO.setmode function defines which numbering met...
Python Code: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # use GPIO numbering, see output of gpio command #GPIO.setmode(GPIO.BOARD) # use Physical pin numbering GPIO.setup(18, GPIO.OUT) # PIN18 (Physical:Pin12) : Output GPIO.output(18, GPIO.HIGH) # Ping18 -> High (3.3V) Explanation: Raspberry Pi Programming GPIO di...
10,284
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align = 'center'> Neural Networks Demystified </h1> <h2 align = 'center'> Part 6 Step1: So far we’ve built a neural network in python, computed a cost function to let us know how well o...
Python Code: from IPython.display import YouTubeVideo YouTubeVideo('9KM9Td6RVgQ') Explanation: <h1 align = 'center'> Neural Networks Demystified </h1> <h2 align = 'center'> Part 6: Training </h2> <h4 align = 'center' > @stephencwelch </h4> End of explanation %pylab inline #Import code from previous videos: from partFiv...
10,285
Given the following text description, write Python code to implement the functionality described below step by step Description: Methods for Sampling from the Unit Simplex 1. Uniform Distributions on the Unit Simplex A $\textit{n}$-unit simplex (https Step2: 2. Exponential Distributions on the Unit Simplex The expone...
Python Code: %matplotlib notebook import numpy as np import matplotlib.pyplot as plt import ternary ## generate order statistics from uniform distribution between 0 and 1 U = [[np.random.uniform(), np.random.uniform()] for i in range(50000)] for u in U: u.sort() ## calculate the spacing and plot the sampling result...
10,286
Given the following text description, write Python code to implement the functionality described below step by step Description: This paper presents a novel set of stimuli, which we refer to as "logpolar gratings" or "scaled gratings". These stimuli are sinusoidal gratings whose spatial frequency decreases as the reci...
Python Code: # import necessary packages %matplotlib inline %load_ext autoreload %autoreload 2 import sys sys.path.append('..') import sfp import pandas as pd import torch import numpy as np import matplotlib.pyplot as plt from tqdm.auto import tqdm import seaborn as sns import pyrtools as pt Explanation: This paper p...
10,287
Given the following text description, write Python code to implement the functionality described below step by step Description: SVM classification/SMOTE oversampling for an imbalanced data set Date created Step1: <h3>II. Preprocessing </h3> We process the missing values first, dropping columns which have a large num...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn.preprocessing import Imputer from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split as tts from sklearn.ensemble import RandomForestCl...
10,288
Given the following text description, write Python code to implement the functionality described below step by step Description: LVA Tables (Storage Geometry) We can retrieve the geometry of a given storage. We can also set the geometry of a storage (or set multiple storages to the same geometry) Step1: Specifying fu...
Python Code: lva = v.model.node.storages.lva('IrrigationOnlyStorage') lva scaled_lva = lva * 2 scaled_lva # v.model.node.storages.load_lva(scaled_lva) # Would load the same table into ALL storages # v.model.node.storages.load_lva(scaled_lva,nodes=['StorageOnlyStorage','BothStorage']) # Will load into two storages v...
10,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 5 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: Create new features As in Week 2, ...
Python Code: import sys sys.path.append('C:\Anaconda2\envs\dato-env\Lib\site-packages') import graphlab Explanation: Regression Week 5: Feature Selection and LASSO (Interpretation) In this notebook, you will use LASSO to select features, building on a pre-implemented solver for LASSO (using GraphLab Create, though you ...
10,290
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice 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', 'cams', 'cams-csm1-0', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: CAMS Source ID: CAMS-CSM1-0 Topic: Seaice Sub-Topics: Dynamics, Thermodyn...
10,291
Given the following text description, write Python code to implement the functionality described below step by step Description: CIFAR–10 Codealong Codealong of Radek Osmulski's notebook establishing a CIFAR-10 baseline with the Fastai ImageNet WideResNet22. For a Fastai CV research collaboration. Wayne Nixalo –– 2018...
Python Code: %matplotlib inline %reload_ext autoreload %autoreload 2 from fastai.conv_learner import * # fastai/imagenet-fast/cifar10/models/ repo from imagenet_fast_cifar_models.wideresnet import wrn_22 from torchvision import transforms, datasets # allows you to enable the inbuilt cudnn auto-tuner to find the # best...
10,292
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Shap Summary Plots
Python Code:: import shap shap.initjs() shap_values = shap.TreeExplainer(model).shap_values(X_train) shap.summary_plot(shap_values, X_train, plot_type="bar") shap.summary_plot(shap_values, X_train)
10,293
Given the following text description, write Python code to implement the functionality described below step by step Description: This is duck typing, and it is everywhere although you did not notice it Duck typing Step1: EAFP
Python Code: # Compare def let_duck_swim_and_quack(d): if hasattr(d, "swim") and hasattr(d, "quack"): d.swim() d.quack() else: print "It does not look like a duck" raise AttributeError def let_duck_swim_and_quack(d): try: d.swim() d.quack() except Attribut...
10,294
Given the following text description, write Python code to implement the functionality described below step by step Description: Configure the plotting machinery Step1: Configure the rendering of this notebook with CSS Step2: Response Analysis in the Frequency Domain<br> <small>an Example</small> Samples Step3: We ...
Python Code: %pylab inline %config InlineBackend.figure_format = 'svg' import json s = json.load( open("mplrc.json") ) matplotlib.rcParams.update(s) matplotlib.rcParams['figure.figsize'] = 9,4 black="#404060" # plots containing "real black" elements look artificial Explanation: Configure the plotting machinery End of e...
10,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Математическая статистика Практическое задание 5 В данном задании предлагается провести некоторое исследование модели линейной регрессии и критериев для проверки статистических гипотез, в ча...
Python Code: import numpy as np import scipy.stats as sps import matplotlib.pyplot as plt import pandas as pd %matplotlib inline Explanation: Математическая статистика Практическое задание 5 В данном задании предлагается провести некоторое исследование модели линейной регрессии и критериев для проверки статистических г...
10,296
Given the following text description, write Python code to implement the functionality described below step by step Description: Shots are fired isotropically from a point and hit a position sensitive detector There is no scattering y is fixed to be 1 away Step1: if both are unknown Step2: Now repeat all this updati...
Python Code: # generate some data with pm.Model() as model: x = pm.Cauchy(name='x', alpha=0, beta=1) trace = pm.sample(10000, njobs=4) pm.traceplot(trace) sampledat = trace['x'] trace.varnames, trace['x'] sns.distplot(sampledat, kde=False, norm_hist=True) # plt.hist(sampledat, 200, normed=True); plt.yscale(...
10,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Embedding a Feedforward Cascade in a Recurrent Network Alex Williams 10/24/2015 If you are viewing a static version of this notebook (e.g. on nbviewer), you can launch an interactive session...
Python Code: from __future__ import division from scipy.integrate import odeint,ode from numpy import zeros,ones,eye,tanh,dot,outer,sqrt,linspace,pi,exp,tile,arange,reshape from numpy.random import uniform,normal,choice import pylab as plt import numpy as np %matplotlib inline Explanation: Embedding a Feedforward Casca...
10,298
Given the following text description, write Python code to implement the functionality described below step by step Description: A Neural Network using Numpy on Bike Sharing Time Series dataset In this project, we'll build a neural network and use it to predict daily bike rental ridership. Step1: Load and prepare the...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: A Neural Network using Numpy on Bike Sharing Time Series dataset In this project, we'll build a neural network and use it to predict daily bike rental riders...
10,299
Given the following text description, write Python code to implement the functionality described below step by step Description: 练习 1:写程序,可由键盘读入用户姓名例如Mr. right,让用户输入出生的月份与日期,判断用户星座,假设用户是金牛座,则输出,Mr. right,你是非常有性格的金牛座! Step1: 练习 2:写程序,可由键盘读入两个整数m与n(n不等于0),询问用户意图,如果要求和则计算从m到n的和输出,如果要乘积则计算从m到n的积并输出,如果要求余数则计算m除以n的余数的值并输出,...
Python Code: name = input("请输入您的姓名:") date = float(input("请输入您出生的月份.日期:")) if 3.21 <= date <= 4.19: print(name,",你是非常有性格的白羊座!") elif 4.20 <= date <= 5.20: print(name,",你是非常有性格的金牛座!") elif 5.21 <= date <= 6.21: print(name,",你是非常有性格的双子座!") elif 6.22 <= date <= 7.22: print(name,",你是非常有性格的巨蟹座!") elif 7.23 <...