Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
8,700
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 12 Step1: Like last week, we're going to use pyspark, a Python package that wraps Apache Spark and makes its functionality available in Python. We'll also use a few of the standard Pyth...
Python Code: !pip install sseclient Explanation: Lab 12: Spark Streaming Introduction In this lab, we're going to look at data streaming with Apache Spark. At the end of the lab, you should be able to: Create a local StreamingContext object. Use Spark to analyse the recent Wikipedia edits stream. Getting started Let's ...
8,701
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice 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', 'niwa', 'sandbox-2', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NIWA Source ID: SANDBOX-2 Topic: Landice Sub-Topics: Glaciers, Ice. Prop...
8,702
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 4 Imports Step2: Line with Gaussian noise Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 4 Imports End of explanation def random_line(m, b, sigma, size=10): Create a line y = m*x + b + N(0,sigm...
8,703
Given the following text description, write Python code to implement the functionality described below step by step Description: Federated learning algorithms This tutorial introduces algorithms for federated learning in FedJAX. By completing this tutorial, we'll learn how to write clear and efficient algorithms that ...
Python Code: # Uncomment these to install fedjax. # !pip install fedjax # !pip install --upgrade git+https://github.com/google/fedjax.git import jax import jax.numpy as jnp import numpy as np import fedjax # We only use TensorFlow for datasets, so we restrict it to CPU only to avoid # issues with certain ops not being ...
8,704
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating epochs of equal length This tutorial shows how to create equal length epochs and briefly demonstrates an example of their use in connectivity analysis. First, we import necessary mo...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import mne from mne.preprocessing import compute_proj_ecg sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') r...
8,705
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimating Joint Tour Frequency This notebook illustrates how to re-estimate a single model component for ActivitySim. This process includes running ActivitySim in estimation mode to read ...
Python Code: import os import larch # !conda install larch -c conda-forge # for estimation import pandas as pd Explanation: Estimating Joint Tour Frequency This notebook illustrates how to re-estimate a single model component for ActivitySim. This process includes running ActivitySim in estimation mode to read house...
8,706
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a ...
Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist Explanation: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-...
8,707
Given the following text description, write Python code to implement the functionality described below step by step Description: # Table of Contents <div class="toc" style="margin-top Step1: A simple neural network in Numpy So what is a neural network anyway. Let's start by looking at a picture. A neural network cons...
Python Code: # Imports import numpy as np import sys sys.path.append('../') # This is where all the python files are! from importlib import reload import utils; reload(utils) from utils import * import keras_models; reload(keras_models) from keras_models import * from losses import crps_cost_function from scipy.stat...
8,708
Given the following text description, write Python code to implement the functionality described below step by step Description: Tranlation Matrix Tutorial What is it ? Suppose we are given a set of word pairs and their associated vector representaion ${x_{i},z_{i}}{i=1}^{n}$, where $x{i} \in R^{d_{1}}$ is the distibu...
Python Code: import os from gensim import utils from gensim.models import translation_matrix from gensim.models import KeyedVectors Explanation: Tranlation Matrix Tutorial What is it ? Suppose we are given a set of word pairs and their associated vector representaion ${x_{i},z_{i}}{i=1}^{n}$, where $x{i} \in R^{d_{1}}$...
8,709
Given the following text description, write Python code to implement the functionality described below step by step Description: First we import the table of tag-article mappings from our SQL database (but read in as a .csv). Step1: We only care about the content type "Article" Step2: But we need to get the tag name...
Python Code: df = pd.read_csv('atlas-taggings.csv') df[2:5] Explanation: First we import the table of tag-article mappings from our SQL database (but read in as a .csv). End of explanation articles = df[df.tagged_type == 'Article'] Explanation: We only care about the content type "Article" End of explanation articles.t...
8,710
Given the following text description, write Python code to implement the functionality described below step by step Description: Données multidimensionnelles SQL - énoncé Ce notebook propose l'utilisation de SQL avec SQLite pour manipuler les données depuis un notebook (avec le module sqlite3). Step1: Représentation ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('ggplot') import pyensae from pyquickhelper.helpgen import NbImage from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: Données multidimensionnelles SQL - énoncé Ce notebook propose l'utilisation de SQL avec SQLite pou...
8,711
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', 'cas', 'sandbox-2', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: CAS Source ID: SANDBOX-2 Topic: Seaice Sub-Topics: Dynamics, Thermodynamics,...
8,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Functions Functions are blocks of code identified by a name, which can receive ""predetermined"" parameters or not ;). In Python, functions Step3: In the above example, we have caps ...
Python Code: def caps(val): caps returns double the value of the provided value return val*2 a = caps("TEST ") print(a) print(caps.__doc__) Explanation: Functions Functions are blocks of code identified by a name, which can receive ""predetermined"" parameters or not ;). In Python, functions: return o...
8,713
Given the following text description, write Python code to implement the functionality described below step by step Description: Saving and Loading Models In this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in ma...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms import helper import fc_model # Define a transform to normalize the data t...
8,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 2 Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset. The goal of this assignm...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range Explanation: Deep Learning Assignment 2 Previousl...
8,715
Given the following text description, write Python code to implement the functionality described below step by step Description: (&#x1F4D7;) Cookbook Step1: ipcluster setup to run parallel code You can find more details about this in our [ipyparallel tutorial]. Step3: Get default (example) 12 taxon tree The function...
Python Code: ## imports import numpy as np import ipyrad as ip import ipyparallel as ipp from ipyrad.analysis import baba ## print versions print "ipyrad v.{}".format(ip.__version__) print "ipyparallel v.{}".format(ipp.__version__) print "numpy v.{}".format(np.__version__) Explanation: (&#x1F4D7;) Cookbook: ipyrad.anal...
8,716
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 2 Imports Step2: Factorial Write a function that computes the factorial of small numbers using np.arange and np.cumprod. Step4: Write a function that computes the factorial ...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: Numpy Exercise 2 Imports End of explanation def np_fact(n): Compute n! = n*(n-1)*...*1 using Numpy. # YOUR CODE HERE a = np.arange(1, n+1, 1) #Makes array from 1 to n+1 if n==0: ...
8,717
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', 'cmcc', 'cmcc-cm2-hr4', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-CM2-HR4 Topic: Seaice Sub-Topics: Dynamics, Thermod...
8,718
Given the following text description, write Python code to implement the functionality described below step by step Description: Sheet To BigQuery Import data from a sheet and move it to a BigQuery table. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: Sheet To BigQuery Import data from a sheet and move it to a BigQuery table. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License....
8,719
Given the following text description, write Python code to implement the functionality described below step by step Description: TFX Components Walk-through Learning Objectives Develop a high level understanding of TFX pipeline components. Learn how to use a TFX Interactive Context for prototype development of TFX pip...
Python Code: import os import time from pprint import pprint import absl import tensorflow as tf import tensorflow_data_validation as tfdv import tensorflow_model_analysis as tfma import tensorflow_transform as tft import tfx from tensorflow_metadata.proto.v0 import schema_pb2 from tfx.components import ( CsvExampl...
8,720
Given the following text description, write Python code to implement the functionality described below step by step Description: Step by step code for abide_motion_wrapper.py Step1: Read in the phenotypic behavioural data This is the Phenotypic_V1_0b_preprocessed1.csv file. It's saved in the DATA folder. You can fin...
Python Code: import matplotlib.pylab as plt %matplotlib inline from matplotlib import ticker from glob import glob import numpy as np import os import pandas as pd from scipy.stats import linregress, pearsonr, spearmanr import nibabel as nib import urllib import seaborn as sns sns.set_context('notebook', font_scale=2) ...
8,721
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="alert alert-info">**Hint** Step1: You will use this data to train and evaluate your learning algorithm. A "learning algorithm" which finds a polynomial of given degree that mini...
Python Code: data = np.load("data/xy_data.npy") # only show the first ten points, since there are a lot data[:10] Explanation: <div class="alert alert-info">**Hint**: Much of the material covered in this problem is introduced in the Geman et al. (1992) reading. If you are having trouble with the conceptual questions, t...
8,722
Given the following text description, write Python code to implement the functionality described below step by step Description: <table align="left"> <td> <a href="https Step1: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can find the packages. Step...
Python Code: import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG = "--user" if os....
8,723
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Data exploration Exploração dos dados baseado em Step1: Create a function to analysing Step2: Feature Observation We are see the 6 features in dataset Step3: 2. Developing a model In t...
Python Code: from data import get_full_data, get_who_is from matplotlib import pyplot as plt from sklearn import linear_model from predicting_who_is import accuracy_score, performance_metric import pandas as pd import numpy as np from IPython.display import display # Allows the use of display() for DataFrames # Import ...
8,724
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Model Evaluation & Validation Project Step1: Data Exploration In this first section of this project, you will make a cursory investigation about the Bos...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd from sklearn.cross_validation import ShuffleSplit # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the Boston housing dataset data = pd.rea...
8,725
Given the following text description, write Python code to implement the functionality described below step by step Description: PLEASE MAKE A COPY BEFORE CHANGING Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. ...
Python Code: # The Developer Key is used to retrieve a discovery document containing the # non-public Full Circle Query v2 API. This is used to build the service used # in the samples to make API requests. Please see the README for instructions # on how to configure your Google Cloud Project for access to the Full Circ...
8,726
Given the following text description, write Python code to implement the functionality described below step by step Description: Spark RDD basic manipulation RDD creation We create a simple RDD by paralellizing a collection local to the driver (usually they would be created by fetching from external sources or reading...
Python Code: # All numbers from 0 to 1000. Split in 4 partitions numbers = sc.parallelize( range(0,1001), 4 ) print numbers.getNumPartitions() print numbers.count() print numbers.take(10) Explanation: Spark RDD basic manipulation RDD creation We create a simple RDD by paralellizing a collection local to the driver (usu...
8,727
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 9 – Up and running with TensorFlow This notebook contains all the sample code and solutions to the exercices in chapter 9. Setup First, let's make sure this notebook works well in bo...
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 import tensorflow as tf import pandas as pd from sklearn.decomposition import PCA from sklearn.model_selection import train_test_split # to make this noteb...
8,728
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculating Transit Timing Variations (TTV) with REBOUND The following code finds the transit times in a two planet system. The transit times of the inner planet are not exactly periodic, du...
Python Code: import rebound import numpy as np Explanation: Calculating Transit Timing Variations (TTV) with REBOUND The following code finds the transit times in a two planet system. The transit times of the inner planet are not exactly periodic, due to planet-planet interactions. First, let's import the REBOUND and n...
8,729
Given the following text description, write Python code to implement the functionality described below step by step Description: Weights and Biases (wandb) Demo In deep learning, we perform a lot of model training especially for novel neural architectures. The problem is deep learning frameworks like PyTorch do not pr...
Python Code: !pip install wandb Explanation: Weights and Biases (wandb) Demo In deep learning, we perform a lot of model training especially for novel neural architectures. The problem is deep learning frameworks like PyTorch do not provide sufficient tools to visualize input data, track the progress of our experiments...
8,730
Given the following text description, write Python code to implement the functionality described below step by step Description: Aprendizado Supervisionado Testando modelos Step1: Agora vamos analisar os modelos do KNN utilizando K=3 e K=10, mas calculando a acurácia na base de teste. Step2: Apesar de ter dado valor...
Python Code: #Imports necessários from sklearn.datasets import load_iris from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt %matplotlib inline data_iris = load_iris() X = data_iris.data y = data_iris.target ...
8,731
Given the following text description, write Python code to implement the functionality described below step by step Description: Recursion and Dictionaries Dr. Chris Gwilliams gwilliamsc@cardiff.ac.uk Overview Scripts in Python Types Methods and Functions Flow control Lists Iteration for loops while loops Now Dicts Tu...
Python Code: empty_dict = {} contact_dict = { "name": "Homer", "email": "homer@simpsons.com", "phone": 999 } print(contact_dict) Explanation: Recursion and Dictionaries Dr. Chris Gwilliams gwilliamsc@cardiff.ac.uk Overview Scripts in Python Types Methods and Functions Flow control Lists Iteration for loops ...
8,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem 1 Using the following dictionary Step1: Problem 2 Write a function that finds the number of elements in a list (without using the built-in len function). Now, use %%timeit to compar...
Python Code: my_dict = { 'a': 3, 'b': 2, 'c': 10, 'd': 7, 'e': 9, 'f' : 12, 'g' : 13 } # print the keys with even values print('keys with even values:') for key, value in my_dict.items(): # modulo 2 == 0 implies the number is even if value % 2 == 0: print(key) # pri...
8,733
Given the following text description, write Python code to implement the functionality described below step by step Description: Hybrid coding scheme for diagonal Gaussians ``` Copyright 2022 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with...
Python Code: import numpy as np import scipy as sp import scipy.stats import matplotlib.pyplot as plt from tqdm import tqdm %matplotlib inline %config InlineBackend.figure_format = 'retina' Explanation: Hybrid coding scheme for diagonal Gaussians ``` Copyright 2022 Google LLC. Licensed under the Apache License, Version...
8,734
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis of Oscar-nominated Films Step1: Descriptive Analysis To better understand general trends in the data. This is a work in progress. last updated on Step2: This can be more or less c...
Python Code: import re import numpy as np import pandas as pd import scipy.stats as stats pd.set_option('display.float_format', lambda x: '%.3f' % x) %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sb sb.set(color_codes=True) sb.set_palette("muted") np.random.seed(sum(map(o...
8,735
Given the following text description, write Python code to implement the functionality described below step by step Description: Context John Doe remarked in #AP1432 that there may be too much code in our application that isn't used at all. Before migrating the application to the new platform, we have to analyze which...
Python Code: import pandas as pd coverage = pd.read_csv("datasets/jacoco.csv") coverage = coverage[['PACKAGE', 'CLASS', 'LINE_COVERED' ,'LINE_MISSED']] coverage['LINES'] = coverage.LINE_COVERED + coverage.LINE_MISSED coverage.head(1) Explanation: Context John Doe remarked in #AP1432 that there may be too much code in o...
8,736
Given the following text description, write Python code to implement the functionality described below step by step Description: what we will learn ... what is CNN <hr/> Convolution Operation Relu layer <hr/> Pooling? <hr/> Flattening <hr/> Full Connection 1. What is CNN ----------------------------------------------...
Python Code: from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense Explanation: what we will learn ... what is CNN <hr/> Convolution Operation Relu layer <hr/> Pooling? <hr/> Flattening <hr/> Full Connec...
8,737
Given the following text description, write Python code to implement the functionality described below step by step Description: Defining and Run a Custom Analytical Model Here you will be creating trivial analytical model following the API. You can start by importing the necessary module components. Step1: You also ...
Python Code: # Module imports from solarbextrapolation.map3dclasses import Map3D from solarbextrapolation.analyticalmodels import AnalyticalModel from solarbextrapolation.visualisation_functions import visualise Explanation: Defining and Run a Custom Analytical Model Here you will be creating trivial analytical model f...
8,738
Given the following text description, write Python code to implement the functionality described below step by step Description: Partitioner examples This is a jupyter notebook with a few vignettes that present some of the Python partitioner package's functionality. Note Step1: Process the English Wiktionary to gener...
Python Code: from partitioner import partitioner from partitioner.methods import * Explanation: Partitioner examples This is a jupyter notebook with a few vignettes that present some of the Python partitioner package's functionality. Note: Cleaning of text and determination of clauses occurs in the partitionText metho...
8,739
Given the following text description, write Python code to implement the functionality described below step by step Description: TD 7 Step1: La programmation dynamique est une façon de résoudre de manière similaire une classe de problèmes d'optimisation qui vérifie la même propriété. On suppose qu'il est possible de...
Python Code: import pyensae from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: TD 7 : Programmation dynamique et plus court chemin End of explanation import pyensae pyensae.download_data("matrix_distance_7398.zip", website = "xd") Explanation: La programmation dynamique est une façon de résou...
8,740
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Now that I've streamlined the MCMC process, I am going to submit multiple chains simultaneously. This notebook will make multiple, similar config files, for broad comparison. This ma...
Python Code: import yaml import copy from os import path import numpy as np orig_cfg_fname = '/home/users/swmclau2//Git/pearce/bin/mcmc/nh_gg_sham_hsab_mcmc_config.yaml' with open(orig_cfg_fname, 'r') as yamlfile: orig_cfg = yaml.load(yamlfile) orig_cfg #this will enable easier string formatting sbatch_template = #...
8,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Preparing Scraped Data for Prediction This notebook describes the process in which the raw films.csv and nominations.csv files are "wrangled" into a workable format for our classifier(s). At...
Python Code: import re import pandas as pd import numpy as np pd.set_option('display.float_format', lambda x: '%.3f' % x) nominations = pd.read_csv('../data/nominations.csv') # clean out some obvious mistakes... nominations = nominations[~nominations['film'].isin(['2001: A Space Odyssey', 'Oliver!', 'Closely Observed T...
8,742
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have two tensors of dimension like 1000 * 1. I want to check how many of the elements are not equal in the two tensors. I think I should be able to do this in few lines like Numpy...
Problem: import numpy as np import pandas as pd import torch A, B = load_data() cnt_not_equal = int(len(A)) - int((A == B).sum())
8,743
Given the following text description, write Python code to implement the functionality described below step by step Description: deepchem Step1: Let's see what dataset looks like Step2: One of the missions of deepchem is to form a synapse between the chemical and the algorithmic worlds Step3: Now that we're oriente...
Python Code: %load_ext autoreload %autoreload 2 %pdb off # set DISPLAY = True when running tutorial DISPLAY = False # set PARALLELIZE to true if you want to use ipyparallel PARALLELIZE = False import warnings warnings.filterwarnings('ignore') dataset_file= "../datasets/pdbbind_core_df.pkl.gz" from deepchem.utils.save i...
8,744
Given the following text description, write Python code to implement the functionality described below step by step Description: Planning Algorithms Do you remember on lesson 2 and 3 we discussed algorithms that basically solve MDPs? That is, find a policy given a exact representation of the environment. In this secti...
Python Code: import numpy as np import pandas as pd import tempfile import pprint import json import sys import gym from gym import wrappers from subprocess import check_output from IPython.display import HTML Explanation: Planning Algorithms Do you remember on lesson 2 and 3 we discussed algorithms that basically solv...
8,745
Given the following text description, write Python code to implement the functionality described below step by step Description: Naive Bayes Classifiers Naive Bayes classifiers are a family of classifiers that are quite similar to the linear models discussed previously. However, they tend to be even faster in training...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Naive Bayes Classifiers Naive Bayes classifiers are a family of classifiers that are quite similar to the linear models discussed previously. However, they tend to be even faster in training. The price paid for this efficien...
8,746
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Session 3 Step2: Then we're going to try this with the MNIST dataset, which I've included a simple interface for in the libs module. Step3: Let's take a look at what this returns St...
Python Code: # imports %matplotlib inline # %pylab osx import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cm as cmx # Some additional libraries which we'll use just # to produce some visualizations of our training from libs.utils import montag...
8,747
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute source power spectral density (PSD) of VectorView and OPM data Here we compute the resting state from raw for data recorded using a Neuromag VectorView system and a custom OPM system...
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # Luke Bloy <luke.bloy@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import os.path as op from mne.filter import next_fast_len import mne print(__doc__) data_path = mne.datasets.opm.data_path() subject =...
8,748
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: ノートブックで TensorBoard を使用する <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: TensorFlow、dateti...
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...
8,749
Given the following text description, write Python code to implement the functionality described below step by step Description: It appears the two states are equivalent, which means this is a single state. This is the spacetime equivalent of a fair coin, so this is the desired result. Which makes me feel better about...
Python Code: state_overlay_diagram(field, random_states.get_causal_field(), t_max = 50, x_max = 50) for state in random_states.causal_states(): print state.plc_configs() for state in random_states.causal_states(): print state.morph() t_trans = random_states.all_transitions(zipped = False)[1] print np.unique(t_t...
8,750
Given the following text description, write Python code to implement the functionality described below step by step Description: Progress report Neural Networks Sara Jones Abstract This project will take hand written digits 0 to 9 and recognize them through a computer-learning program. The neural network will require ...
Python Code: import numpy as np import math import random import string from scipy import optimize %matplotlib inline import matplotlib.pyplot as plt from IPython.html.widgets import interact from sklearn.datasets import load_digits digits = load_digits() print(digits.data.shape) Explanation: Progress report Neural Net...
8,751
Given the following text description, write Python code to implement the functionality described below step by step Description: Introdução Esse notebook traz as analises pedidas na disciplina Biologia Evolutiva - Bio507 Neste tutorial vamos utilizar a a linguagem Python 2.7 e os pacotes numpy, pandas, dendropy e matp...
Python Code: import numpy as np import pandas as pd import dendropy as dp import matplotlib as mpl Explanation: Introdução Esse notebook traz as analises pedidas na disciplina Biologia Evolutiva - Bio507 Neste tutorial vamos utilizar a a linguagem Python 2.7 e os pacotes numpy, pandas, dendropy e matplotlib Leitura de...
8,752
Given the following text description, write Python code to implement the functionality described below step by step Description: Example code that shows how to plot the function value and a decision boundary for a simple logistic regression model using python Author Step1: Create the domain for the plot Step2: Make ...
Python Code: %matplotlib inline import numpy as np from scipy.special import expit import matplotlib.pyplot as plt # define our hypothesis (vectorized!) def f(x): return expit(np.matrix([0, 1, -.5,.5])*x); Explanation: Example code that shows how to plot the function value and a decision boundary for a simple logist...
8,753
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 4 Imports Step2: Line with Gaussian noise Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 4 Imports End of explanation def random_line(m, b, sigma, size=10): Create a line y = m*x + b + N(0,sigm...
8,754
Given the following text description, write Python code to implement the functionality described below step by step Description: My 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 implementatio...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: My 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...
8,755
Given the following text description, write Python code to implement the functionality described below step by step Description: def sghmc(Y, X, stogradU, M, eps, m, theta, C, V) Step1: Correct coefficients Step2: Our code - SGHMC Step3: Our code - Gradient descent Step5: Cliburn's code
Python Code: # Load data X = np.concatenate((np.ones((pima.shape[0],1)),pima[:,0:8]), axis=1) Y = pima[:,8] Xs = (X - np.mean(X, axis=0))/np.concatenate((np.ones(1),np.std(X[:,1:], axis=0))) n, p = X.shape M = np.identity(p) ### HMC version def logistic(x): return 1/(1+np.exp(-x)) def U(theta, Y, X): return - (...
8,756
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...
8,757
Given the following text description, write Python code to implement the functionality described below step by step Description: If you have not already read it, you may want to start with the first tutorial Step1: Here we will again load some pre-generated data meant to represent well-sampled, precise radial velocit...
Python Code: import astropy.coordinates as coord import astropy.table as at from astropy.time import Time import astropy.units as u import matplotlib.pyplot as plt import numpy as np %matplotlib inline import corner import pymc3 as pm import pymc3_ext as pmx import exoplanet as xo import arviz as az import thejoker as ...
8,758
Given the following text description, write Python code to implement the functionality described below step by step Description: * Visualizing of genetic similarity with Lightning + GraphX * Setup lightning Step1: Load structure similarity data Public data from http Step2: Show the network (unlabeled) Step3: Show t...
Python Code: %libraryDependencies += "org.viz.lightning" %% "lightning-scala" % "0.1.6" %update import org.viz.lightning._ import org.apache.spark.graphx._ val lgn = Lightning(host="https://lightning-spark-summit.herokuapp.com" ) lgn.enableNotebook() Explanation: * Visualizing of genetic similarity with Lightning + Gra...
8,759
Given the following text description, write Python code to implement the functionality described below step by step Description: Wk1.0 Warm-up Step1: 3. Extend your program to n objects. How many different combinations do I have for 5 objects? How about 15? What is the max number of objects I could calculate for if I...
Python Code: count = 1 for elem in range(1, 3 + 1): count *= elem print(count) Explanation: Wk1.0 Warm-up: I got 32767 problems and overflow is one of them. 1. Swap the values of two variables, a and b without using a temporary variable. 2. Suppose I had six different sodas. In how many different combinations ...
8,760
Given the following text description, write Python code to implement the functionality described below step by step Description: <div align="right">Python 3.6</div> Testing The Google Maps Subclass This notebook was created to test objects associated with extracting information into a Dataframe using the Google Maps A...
Python Code: # general libraries import pandas as pd ## required for Google Maps API code import os ## for larger data and/or make many requests in one day - get Google API key and use these lines: # os.environ["GOOGLE_API_KEY"] = "YOUR_GOOGLE_API_Key" ## for better security (PROD environments) - install key to server ...
8,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Deep Learning Project Step1: Step 1 Step2: Include an exploratory visualization of the dataset Visualize the German Traffic Signs Dataset using the pic...
Python Code: # Load pickled data import pickle from keras.datasets import cifar10 from sklearn.model_selection import train_test_split # TODO: Fill this in based on where you saved the training and testing data #training_file = "traffic-signs-data/train.p" #validation_file = "traffic-signs-data/valid.p" #testing_file =...
8,762
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas Examples http Step1: Let's read data from the BRFSS Step2: If we group by sex, we get a DataFrameGroupBy object. Step3: If we select a particular column from the GroupBy, we get a ...
Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import nsfg import first import analytic import thinkstats2 import seaborn Explanation: Pandas Examples http://thinkstats2.com Copyright 2017 Allen B. Downey MIT License: https://opensource.org/licenses/MIT End of explana...
8,763
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: Notation $Y$ generic random variable $U$ latent random variable $V$ residual random variable $X$ predictor Parameters $\eta$ and $\nu$ generic parameters $\mu=E[Y]$ mean parameter $\g...
Python Code: model = data { int<lower=0> N; //nr subjects real<lower=0> k; real<lower=0> t; }generated quantities{ real<lower=0> y; y=gamma_rng(k,1/t); } smGammaGen = pystan.StanModel(model_code=model) model = data { int<lower=0> N; //nr subjects real<lower=0> y[N]; }parameters{ real<l...
8,764
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian interpretation of medical tests This notebooks explores several problems related to interpreting the results of medical tests. Copyright 2016 Allen Downey MIT License Step3: Medica...
Python Code: from __future__ import print_function, division from thinkbayes2 import Pmf, Suite from fractions import Fraction Explanation: Bayesian interpretation of medical tests This notebooks explores several problems related to interpreting the results of medical tests. Copyright 2016 Allen Downey MIT License: htt...
8,765
Given the following text description, write Python code to implement the functionality described below step by step Description: Backpropagation Tutorial (C) 2019 by Damir Cavar Version Step1: For plots of curves and functions we will use pyplot from matplotlib. We will import it here Step2: Non-linearity Function a...
Python Code: import numpy as np Explanation: Backpropagation Tutorial (C) 2019 by Damir Cavar Version: 0.1, November 2019 Download: This and various other Jupyter notebooks are available from my GitHub repo. Introduction For more details on Backpropagation and its use in Neural Networks see Rumelhart, Hinton, and Willi...
8,766
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute LCMV beamformer on evoked data Compute LCMV beamformer solutions on evoked dataset for three different choices of source orientation and stores the solutions in stc files for visuali...
Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import matplotlib.pyplot as plt import numpy as np import mne from mne.datasets import sample from mne.beamformer import lcmv print(__doc__) data_path = sample.data_path() raw_fname = data_path + '/MEG/sample...
8,767
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebook Problem Step1: Unit Test
Python Code: %run ../bst/bst.py %load ../bst/bst.py def in_order_traversal(node, visit_func): # TODO: Implement me pass def pre_order_traversal(node, visit_func): # TODO: Implement me pass def post_order_traversal(node, visit_func): # TODO: Implement me pass Explanation: <small><i>This notebook ...
8,768
Given the following text description, write Python code to implement the functionality described below step by step Description: Running simple example through EC2 start downloading linking_EC2 Tutorial for running liknking_EC2 see Step1: start the actual cluster Step2: login to main node and run Step3: Terimante t...
Python Code: %%bash . ~/.bashrc pip install --upgrade git+https://git@github.com/JonasWallin/linkingEC2 from linkingEC2 import LinkingHandler from ConfigParser import ConfigParser config = ConfigParser() starfigconfig_folder = "/Users/jonaswallin/.starcluster/" config.read(starfigconfig_folder + "config") acess_key_id...
8,769
Given the following text description, write Python code to implement the functionality described below step by step Description: Micromagnetic standard problem 3 Author Step1: Firstly, we import all necessary modules. Step2: The following two functions are used for initialising the system's magnetisation [1]. Step3:...
Python Code: !rm -rf standard_problem3/ # Delete old result files (if any). Explanation: Micromagnetic standard problem 3 Author: Marijan Beg, Ryan Pepper Date: 11 May 2016 Problem specification This problem is to calculate the single domain limit of a cubic magnetic particle. This is the size $L$ of equal energy for ...
8,770
Given the following text description, write Python code to implement the functionality described below step by step Description: If not yet available some libraries and their python bindings have to be installed Step1: Create a meshed screen with a central hole The screen is rectangular (215*150 mm) with a 4mm centr...
Python Code: import numpy as np from scipy import constants import pygmsh from MeshedFields import * Explanation: If not yet available some libraries and their python bindings have to be installed :<br> - gmsh (best installed globally through package management system) - python3 -m pip install pygmsh --user - VTK (best...
8,771
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
8,772
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Binning Following script is used to bin the data and check stats of participants Step1: Reading scan json files and extracting scan parameters Step2: Convention Step3: Group Stats Th...
Python Code: import pandas as pd import numpy as np import json import string df = pd.read_csv('/home1/varunk/data/ABIDE1/RawDataBIDs/composite_phenotypic_file.csv') # , index_col='SUB_ID' df = df.sort_values(['SUB_ID']) df Explanation: Data Binning Following script is used to bin the data and check stats of participan...
8,773
Given the following text description, write Python code to implement the functionality described below step by step Description: Computer Vision to find chess squares in a screenshot Link to Github source code The goal is to build a Reddit bot that listens on /r/chess for posts with an image in it (perhaps checking al...
Python Code: import tensorflow as tf import numpy as np np.set_printoptions(suppress=True) sess = tf.InteractiveSession() Explanation: Computer Vision to find chess squares in a screenshot Link to Github source code The goal is to build a Reddit bot that listens on /r/chess for posts with an image in it (perhaps checki...
8,774
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Autoencoder This scripts contains module for implementing variational autoencoder, the module contains Step2: mnist_loader Step3: Test mnist data Step4: We are generating synt...
Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import time from tensorflow.python.client import timeline %matplotlib inline Explanation: Variational Autoencoder This scri...
8,775
Given the following text description, write Python code to implement the functionality described below step by step Description: ============================================================================ Decoding in time-frequency space data using the Common Spatial Pattern (CSP) ====================================...
Python Code: # Authors: Laura Gwilliams <laura.gwilliams@nyu.edu> # Jean-Remi King <jeanremi.king@gmail.com> # Alex Barachant <alexandre.barachant@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from ...
8,776
Given the following text description, write Python code to implement the functionality described below step by step Description: Question_3-1-3_Multiclass_Ridge Janet Matsen Code notes Step1: Prepare MNIST training data Step2: Dev
Python Code: import numpy as np import matplotlib as mpl %matplotlib inline import pandas as pd import seaborn as sns from mnist import MNIST # public package for making arrays out of MINST data. import sys sys.path.append('../code/') from ridge_regression import RidgeBinary from hyperparameter_explorer import Hyperpa...
8,777
Given the following text description, write Python code to implement the functionality described below step by step Description: What is machine learning? One definition Step1: What are the features? - TV Step2: Linear regression Pros Step3: Splitting X and y into training and testing sets Step4: Linear regression...
Python Code: import pandas as pd # read CSV file directly from a URL and save the results data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0) # display the first 5 rows data.head() data.shape Explanation: What is machine learning? One definition: "Machine learning is the semi-automat...
8,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Using folium.colormap A few examples of how to use folium.colormap in choropleths. Let's load a GeoJSON file, and try to choropleth it. Step2: Self-defined You can build a choropleth in usi...
Python Code: import json import pandas as pd us_states = os.path.join('data', 'us-states.json') US_Unemployment_Oct2012 = os.path.join('data', 'US_Unemployment_Oct2012.csv') geo_json_data = json.load(open(us_states)) unemployment = pd.read_csv(US_Unemployment_Oct2012) unemployment_dict = unemployment.set_index('State')...
8,779
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: 変分推論を使用した一般化線形混合効果モデルの適合 <table class="tfo-notebook-buttons" align="left"> <t...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # 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...
8,780
Given the following text description, write Python code to implement the functionality described below step by step Description: BigQuery command-line tool The BigQuery command-line tool is installed as part of the Cloud SDK and can be used to interact with BigQuery. When you use CLI commands in a notebook, the comman...
Python Code: !bq help Explanation: BigQuery command-line tool The BigQuery command-line tool is installed as part of the Cloud SDK and can be used to interact with BigQuery. When you use CLI commands in a notebook, the command must be prepended with a !. View available commands To view the available commands for the Bi...
8,781
Given the following text description, write Python code to implement the functionality described below step by step Description: Read SST, Mask and Calculate global mean In this notebook, we will carry out the following basic operations * have a quick visualization of spatial data * use mask array to mask out land * c...
Python Code: %matplotlib inline import numpy as np from netCDF4 import Dataset # http://unidata.github.io/netcdf4-python/ import matplotlib.pyplot as plt # to generate plots from matplotlib.pylab import rcParams rcParams['figure.figsize'] = 15, 9 Explanation: Read SST, Mask and Calculate global mean I...
8,782
Given the following text description, write Python code to implement the functionality described below step by step Description: Improving the Text Classifier Goals Try Random Forest on our Sentiment Data Try Support Vector Machines on our Sentiment Data Introduction to Hyperparameters Introduction There are three way...
Python Code: import pandas as pd import numpy as np from sklearn.model_selection import cross_val_score df = pd.read_csv('../scikit/tweets.csv') target = df['is_there_an_emotion_directed_at_a_brand_or_product'] text = df['tweet_text'] # We need to remove the empty rows from the text before we pass into CountVectorizer ...
8,783
Given the following text description, write Python code to implement the functionality described below step by step Description: Measuring a Multiport Device with a 2-Port Network Analyzer Introduction In microwave measurements, one commonly needs to measure a n-port device with a m-port network analyzer ($m<n$ of cou...
Python Code: import skrf as rf from itertools import combinations %matplotlib inline from pylab import * rf.stylely() Explanation: Measuring a Multiport Device with a 2-Port Network Analyzer Introduction In microwave measurements, one commonly needs to measure a n-port device with a m-port network analyzer ($m<n$ of c...
8,784
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 でのプルーニングの例 <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...
8,785
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction You have already seen that when you change the input value to a function, you often get a different output. For instance, consider an add_five() function that just adds five to...
Python Code: print(2 > 3) Explanation: Introduction You have already seen that when you change the input value to a function, you often get a different output. For instance, consider an add_five() function that just adds five to any number and returns the result. Then add_five(7) will return an output of 12 (=7+5), a...
8,786
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 7 Step1: Anytime you see a statement that starts with import, you'll recognize that the programmer is pulling in some sort of external functionality not previously available to Pyth...
Python Code: import random Explanation: Lecture 7: Vectorized Programming CSCI 1360E: Foundations for Informatics and Analytics Overview and Objectives We've covered loops and lists, and how to use them to perform some basic arithmetic calculations. In this lecture, we'll see how we can use an external library to make ...
8,787
Given the following text description, write Python code to implement the functionality described below step by step Description: Single trial linear regression analysis with the LIMO dataset Here we explore the structure of the data contained in the LIMO dataset. This example replicates and extends some of the main an...
Python Code: # Authors: Jose C. Garcia Alanis <alanis.jcg@gmail.com> # # License: BSD-3-Clause import numpy as np import matplotlib.pyplot as plt from mne.datasets.limo import load_data from mne.stats import linear_regression from mne.viz import plot_events, plot_compare_evokeds from mne import combine_evoked print(__d...
8,788
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is part of the clifford documentation Step1: This creates an algebra with the required signature and imports the basis blades into the current workspace. We can check our metr...
Python Code: from clifford.g3c import * blades Explanation: This notebook is part of the clifford documentation: https://clifford.readthedocs.io/. Example 1 Interpolating Conformal Objects In this example we will look at a few of the tools provided by the clifford package for (4,1) conformal geometric algebra (CGA) and...
8,789
Given the following text description, write Python code to implement the functionality described below step by step Description: Hyperparameter Optimization xgboost What the options there're for tuning? * GridSearch * RandomizedSearch All right! Xgboost has about 20 params Step1: Modeling Step2: Tuning hyperparmeter...
Python Code: import pandas as pd import xgboost as xgb import numpy as np import seaborn as sns from hyperopt import hp from hyperopt import hp, fmin, tpe, STATUS_OK, Trials %matplotlib inline train = pd.read_csv('bike.csv') train['datetime'] = pd.to_datetime( train['datetime'] ) train['day'] = train['datetime'].map(la...
8,790
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: can we predict which learner will be best on a dataset from dataset properties? Step2: can we predict the best score achievable on a dataset from dataset properties?
Python Code: # get best classifier for each dataset from tqdm import tqdm best_method = dict() for i,(dataset, group_data) in enumerate(tqdm(data.groupby('dataset'))): best_method[dataset] = group_data['classifier'][np.argmax(group_data['accuracy'])] # print(best_method) # make new dataset combining metafeatures a...
8,791
Given the following text description, write Python code to implement the functionality described below step by step Description: Desription Simulation of data-aided frequency synchronization QPSK symbols are sampled, pulse shaped and transmitted Uniformly distributed frequency distortion is added, before frequency is...
Python Code: # importing import numpy as np import matplotlib.pyplot as plt import matplotlib # showing figures inline %matplotlib inline # plotting options font = {'size' : 20} plt.rc('font', **font) plt.rc('text', usetex=True) matplotlib.rc('figure', figsize=(28, 8) ) Explanation: Desription Simulation of data-aid...
8,792
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples Step1: Try It Yourself Go to the section 4.4. Numeric Types in the Python 3 documentation at https Step2: Variables can be reassigned. Step3: The ability to reassign variable val...
Python Code: # The interpreter can be used as a calculator, and can also echo or concatenate strings. 3 + 3 3 * 3 3 ** 3 3 / 2 # classic division - output is a floating point number # Use quotes around strings 'dogs' # + operator can be used to concatenate strings 'dogs' + "cats" print('Hello World!') Explanation: Exam...
8,793
Given the following text description, write Python code to implement the functionality described below step by step Description: # Defensive programming (2) We have seen the basic idea that we can insert assert statments into code, to check that the results are what we expect, but how can we test software...
Python Code: def test_range_overlap(): assert range_overlap([(-3.0, 5.0), (0.0, 4.5), (-1.5, 2.0)]) == (0.0, 2.0) assert range_overlap([ (2.0, 3.0), (2.0, 4.0) ]) == (2.0, 3.0) assert range_overlap([ (0.0, 1.0), (0.0, 2.0), (-1.0, 1.0) ]) == (0.0, 1.0) Explanation: # Defensive programming (2) We have see...
8,794
Given the following text description, write Python code to implement the functionality described below step by step Description: Planning Chapters 10-11 This notebook serves as supporting material for topics covered in Chapter 10 - Classical Planning and Chapter 11 - Planning and Acting in the Real World from the book...
Python Code: from planning import * from notebook import psource Explanation: Planning Chapters 10-11 This notebook serves as supporting material for topics covered in Chapter 10 - Classical Planning and Chapter 11 - Planning and Acting in the Real World from the book Artificial Intelligence: A Modern Approach. This n...
8,795
Given the following text description, write Python code to implement the functionality described below step by step Description: Matching Market This simple model consists of a buyer, a supplier, and a market. The buyer represents a group of customers whose willingness to pay for a single unit of the good is captured...
Python Code: import random as rnd class Supplier(): def __init__(self): self.wta = [] # the supplier has n quantities that they can sell # they may be willing to sell this quantity anywhere from a lower price of l # to a higher price of u def set_quantity(self,n,l,u): for i in r...
8,796
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Encoder-Decoders Analysis Model Architecture Step1: Perplexity on Each Dataset Step2: Loss vs. Epoch Step3: Perplexity vs. Epoch Step4: Generations Step5: BLEU Analysis Step6:...
Python Code: report_files = ["/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing6_200_512_04drb/encdec_noing6_200_512_04drb.json", "/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing6_bow_200_512_04drb/encdec_noing6_bow_200_512_04drb.json"] log_files = ["/Users/bking/Idea...
8,797
Given the following text description, write Python code to implement the functionality described below step by step Description: 6.2 - Using a pre-trained model with Keras In this tutorial we will load the model we trained in the previous section, along with the training data and mapping dictionaries, and use it to ge...
Python Code: import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import LSTM from keras.callbacks import ModelCheckpoint from keras.utils import np_utils import sys import re import pickle Explanation: 6.2 - Using a pre-trained model w...
8,798
Given the following text description, write Python code to implement the functionality described below step by step Description: 5.2 - Using convnets with small datasets This notebook contains the code sample found in Chapter 5, Section 2 of Deep Learning with Python. Note that the original text features far more cont...
Python Code: import os, shutil # The path to the directory where the original # dataset was uncompressed original_dataset_dir = '/Users/fchollet/Downloads/kaggle_original_data' # The directory where we will # store our smaller dataset base_dir = '/Users/fchollet/Downloads/cats_and_dogs_small' os.mkdir(base_dir) # Direc...
8,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Twitter Step3: So above we use the LIKE statement in conjunction with the % sign. The LIKE operator is going to match a string while the % matches any string of 0 or greater length. ...
Python Code: # BE SURE TO RUN THIS CELL BEFORE ANY OF THE OTHER CELLS import psycopg2 import pandas as pd from skbio.diversity.alpha import shannon # query database statement = SELECT * FROM twitter.job WHERE description LIKE '%New York City%'; try: connect_str = "dbname='twitter' user='dsa_ro_user' host='dbase.d...