Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
12,800
Given the following text description, write Python code to implement the functionality described below step by step Description: Anna KaRNNa In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book...
Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf Explanation: Anna KaRNNa In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network...
12,801
Given the following text description, write Python code to implement the functionality described below step by step Description: Dynamical systems A (discrete time) dynamical system describes the evolution of the state of a system and the observations that can be obtained from the state. The general form is \begin{eqn...
Python Code: %matplotlib inline import numpy as np import matplotlib.pylab as plt N = 100 T = 100 a = 0.9 xm = 0.9 sP = np.sqrt(0.001) sR = np.sqrt(0.01) x1 = np.zeros(N) x2 = np.zeros(N) y = np.zeros(N) for i in range(N): if i==0: x1[0] = xm x2[0] = 0 else: x1[i] = xm + a*x1[i-1] + np.r...
12,802
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting Introduction This tutorial describes skrf's plotting features. If you would like to use skrf's matplotlib interface with skrf styling, start with this Step1: Plotting Methods Plot...
Python Code: %matplotlib inline import skrf as rf rf.stylely() Explanation: Plotting Introduction This tutorial describes skrf's plotting features. If you would like to use skrf's matplotlib interface with skrf styling, start with this End of explanation from skrf import Network ring_slot = Network('data/ring slot.s2p...
12,803
Given the following text description, write Python code to implement the functionality described below step by step Description: Time-frequency representations on topographies for MEG sensors Both average power and intertrial coherence are displayed. Step1: Set parameters Step2: Calculate power and intertrial cohere...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne import io from mne.time_frequency import tfr_morlet from mne.datasets import somato...
12,804
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Classification & How To "Frame Problems" for a Neural Network by Andrew Trask Twitter Step1: Note Step2: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one ...
Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].upper(),g.readlines())...
12,805
Given the following text description, write Python code to implement the functionality described below step by step Description: Plot Type Selector Example showing how to construct a dropdown widget that can be used to select a plot type. Here a dictionary must be used for the plot type options. Step1: Load cube. St...
Python Code: import ipywidgets import IPython.display import iris import numpy as np import iris.quickplot as iplt import matplotlib.pyplot as plt Explanation: Plot Type Selector Example showing how to construct a dropdown widget that can be used to select a plot type. Here a dictionary must be used for the plot type ...
12,806
Given the following text description, write Python code to implement the functionality described below step by step Description: Bonus Material Step1: Convert to list of words Step2: Slower version without translate Step3: Using a regular dictionary Step4: Using a default dictionary Step5: Using a Counter Step6: ...
Python Code: text = ''''Twas brillig, and the slithy toves Did gyre and gimble in the wabe; All mimsy were the borogoves, And the mome raths outgrabe. 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnat...
12,807
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Solutions Problem 1 Implement the Min-Max scaling function ($X'=a+{\frac {\left(X-X_{\min }\right)\left(b-a\right)}{X_{\max }-X_{\min }}}$) with the parameters Step2: Problem 2 Use t...
Python Code: # Problem 1 - Implement Min-Max scaling for greyscale image data def normalize_greyscale(image_data): Normalize the image data with Min-Max scaling to a range of [0.1, 0.9] :param image_data: The image data to be normalized :return: Normalized image data a = 0.1 b = 0.9 gr...
12,808
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimization of Degree Distributions on the BEC This code is provided as supplementary material of the lecture Channel Coding 2 - Advanced Methods. This code illustrates * Using linear progr...
Python Code: import cvxpy as cp import numpy as np import matplotlib.pyplot as plot from ipywidgets import interactive import ipywidgets as widgets import math %matplotlib inline Explanation: Optimization of Degree Distributions on the BEC This code is provided as supplementary material of the lecture Channel Coding ...
12,809
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-2', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: NIMS-KMA Source ID: SANDBOX-2 Topic: Aerosol Sub-Topics: Transport, E...
12,810
Given the following text description, write Python code to implement the functionality described below step by step Description: eICU Collaborative Research Database Notebook 3 Step2: 2. Display a list of tables Step4: 3. Selecting a single patient stay 3.1. The patient table The patient table includes general infor...
Python Code: # Import libraries import pandas as pd import matplotlib.pyplot as plt import psycopg2 import os # Plot settings %matplotlib inline plt.style.use('ggplot') fontsize = 20 # size for x and y ticks plt.rcParams['legend.fontsize'] = fontsize plt.rcParams.update({'font.size': fontsize}) # Connect to the databas...
12,811
Given the following text description, write Python code to implement the functionality described below step by step Description: This Notebook illustrates the usage of the OpenMC Python API's generic eigenvalue search capability. In this Notebook, we will do a critical boron concentration search of a typical PWR pin ...
Python Code: # Initialize third-party libraries and the OpenMC Python API import matplotlib.pyplot as plt import numpy as np import openmc import openmc.model %matplotlib inline Explanation: This Notebook illustrates the usage of the OpenMC Python API's generic eigenvalue search capability. In this Notebook, we will d...
12,812
Given the following text description, write Python code to implement the functionality described below step by step Description: Setting the EEG reference This tutorial describes how to set or change the EEG reference in MNE-Python. As usual we'll start by importing the modules we need, loading some example data &lt;s...
Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False) raw.crop(tmax=60).load_data() raw.pi...
12,813
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis of Movie Reviews This tutorial will guide you through the implementation of a recurrent neural network to analyze movie reviews on IMDB and decide if they are positive or ...
Python Code: import pickle as pkl data = pkl.load(open('data/imdb_data.pkl', 'r')) Explanation: Sentiment Analysis of Movie Reviews This tutorial will guide you through the implementation of a recurrent neural network to analyze movie reviews on IMDB and decide if they are positive or negative reviews. The IMDB dataset...
12,814
Given the following text description, write Python code to implement the functionality described below step by step Description: Análisis de los datos obtenidos Uso de ipython para el análsis y muestra de los datos obtenidos durante la producción.Se implementa un regulador experto. Los datos analizados son del día 13 ...
Python Code: #Importamos las librerías utilizadas import numpy as np import pandas as pd import seaborn as sns #Mostramos las versiones usadas de cada librerías print ("Numpy v{}".format(np.__version__)) print ("Pandas v{}".format(pd.__version__)) print ("Seaborn v{}".format(sns.__version__)) #Abrimos el fichero csv co...
12,815
Given the following text description, write Python code to implement the functionality described below step by step Description: Remote Interactive Task Manager LSASS Dump Metadata | | | | Step1: Download & Process Mordor Dataset Step2: Analytic I Look for taskmgr creating files which name conta...
Python Code: from openhunt.mordorutils import * spark = get_spark() Explanation: Remote Interactive Task Manager LSASS Dump Metadata | | | |:------------------|:---| | collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] | | creation date | 2019/10/30 | | modification date | 2020/09/20 | | play...
12,816
Given the following text description, write Python code to implement the functionality described below step by step Description: Importing and Processing CO2 Respiration Data from GC-MS This script will convert output from the GC-MS from multiple sampling timepoints into a table. It can also calculate the mols C based...
Python Code: ## Provide the directory the contains subdirectories with timepoints # example: '/home/roli/PROJECT/ which would contain sub-directories corresponding to timepoints T1, T2, T3 ... that containing the text output from the GC-MS directory = '/home/roli/scripts/gcms/example_data/' ## Name the output for GC-MS...
12,817
Given the following text description, write Python code to implement the functionality described below step by step Description: Emojify! Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier. Have you ever wanted to make your text messages more expressive?...
Python Code: import numpy as np from emo_utils import * import emoji import matplotlib.pyplot as plt %matplotlib inline Explanation: Emojify! Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier. Have you ever wanted to make your text messages more expressi...
12,818
Given the following text description, write Python code to implement the functionality described below step by step Description: Access-lists and firewall rules This category of questions allows you to analyze the behavior of access control lists and firewall rules. It also allows you to comprehensively validate (aka ...
Python Code: bf.set_network('generate_questions') bf.set_snapshot('generate_questions') Explanation: Access-lists and firewall rules This category of questions allows you to analyze the behavior of access control lists and firewall rules. It also allows you to comprehensively validate (aka verification) that some traff...
12,819
Given the following text description, write Python code to implement the functionality described below step by step Description: Publication ready figures with matplotlib and Jupyter notebook A very convenient workflow to analyze data and create figures that can be used in various ways for publication is to use the IP...
Python Code: %matplotlib inline import seaborn as snb import numpy as np import matplotlib.pyplot as plt Explanation: Publication ready figures with matplotlib and Jupyter notebook A very convenient workflow to analyze data and create figures that can be used in various ways for publication is to use the IPython Notebo...
12,820
Given the following text description, write Python code to implement the functionality described below step by step Description: Kalman Filters By Evgenia "Jenny" Nitishinskaya, Dr. Aidan O'Mahony, and Delaney Granizo-Mackenzie. Algorithms by David Edwards. Kalman Filter Beta Estimation Example from Dr. Aidan O'Mahony...
Python Code: %pylab inline # Import a Kalman filter and other useful libraries from pykalman import KalmanFilter import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import poly1d Explanation: Kalman Filters By Evgenia "Jenny" Nitishinskaya, Dr. Aidan O'Mahony, and Delaney Granizo-Mackenzie...
12,821
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Cubic Splines $C^2$-continuous cubic splines through evenly spaced data points can be created by convolving the data points with a $C^2$-continuous piecewise cubic kernel, char...
Python Code: import math #given an array of Y values at consecutive integral x abscissas, #return array of corresponding derivatives to make a natural cubic spline def naturalSpline(ys): vs = [0.0] * len(ys) if (len(ys) < 2): return vs DECAY = math.sqrt(3)-2; endi = len(ys)-1 # make con...
12,822
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Introduction and Foundations Project 0 Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the s...
Python Code: import numpy as np import pandas as pd # RMS Titanic data visualization code from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few entries of the RMS Ti...
12,823
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas Sometimes you want a spreadsheet. Starting point Step1: Write a piece of code that prints the number 5, taken from some_dict. Step2: A pandas dataframe is a dictionary of dictiona...
Python Code: some_dict = {"x":{"a":1,"b":2,"c":3}, "y":{"a":4,"b":5,"c":6}} Explanation: Pandas Sometimes you want a spreadsheet. Starting point End of explanation # Answer some_dict["y"]["b"] Explanation: Write a piece of code that prints the number 5, taken from some_dict. End of explanation import pan...
12,824
Given the following text description, write Python code to implement the functionality described below step by step Description: 20/10 Tipos de datos compuestos. Estructuras de control repetitivas. Índices y slices Diccionarios como acumuladores/contadores Listas Step1: Es fácil saber si un número está en la lista o...
Python Code: lista_de_numeros = [1, 6, 3, 9, 5, 2] print lista_de_numeros print type(lista_de_numeros) Explanation: 20/10 Tipos de datos compuestos. Estructuras de control repetitivas. Índices y slices Diccionarios como acumuladores/contadores Listas End of explanation print 'El %s esta en %s?: %s' % (5, lista_de_nume...
12,825
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing the back normalscore transformation Step1: Getting the data ready for work If the data is in GSLIB format you can use the function gslib.read_gslib_file(filename) to import the data...
Python Code: #general imports import matplotlib.pyplot as plt import pygslib from matplotlib.patches import Ellipse import numpy as np import pandas as pd #make the plots inline %matplotlib inline Explanation: Testing the back normalscore transformation End of explanation #get the data in gslib format into a p...
12,826
Given the following text description, write Python code to implement the functionality described below step by step Description: Cross-validation In the machine learning examples, we have already shown the importance of split training and splitting data. However, a rough trial is not enough. Because if we randomly ass...
Python Code: from sklearn.datasets import load_iris from sklearn.cross_validation import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics # read in the iris data iris = load_iris() # create X (features) and y (response) X = iris.data y = iris.target # use train/test split ...
12,827
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing SDO/AIA Response Functions Step1: Wavelength Response First, load the SSW results into some convenient data structure. Step2: Run the SunPy calculation. Step3: Plot the results ...
Python Code: import numpy as np import matplotlib.pyplot as plt import sunpy.instr.aia %matplotlib inline Explanation: Comparing SDO/AIA Response Functions: SSW and SunPy This notebook runs comparisons between the results of SSW and SunPy in calculating the wavelength and temperature response functions of the AIA instr...
12,828
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started <a name='contents'></a> Contents <a href='#magic'>The <tt>matmodlab</tt> namespace</a> <a href='#model.def'>Defining a Model</a> <a href='#model.def.mat'>Material Model Defin...
Python Code: %pylab inline from matmodlab2 import * Explanation: Getting Started <a name='contents'></a> Contents <a href='#magic'>The <tt>matmodlab</tt> namespace</a> <a href='#model.def'>Defining a Model</a> <a href='#model.def.mat'>Material Model Definition</a> <a href='#model.def.step'>Step Definitions</a> <a href=...
12,829
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Linear SVC Sklearn - Training a Linear SVM Classification Model
Python Code:: from sklearn.svm import SVC from sklearn.metrics import classification_report # create a linear SVC model with balanced class weights model = SVC(C=1, kernel='linear', class_weight='balanced') # fit model model.fit(X_train, y_train) # make predictions on test data y_pred = model.predict(X_test) # create a...
12,830
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Analysis using Pandas Pandas has become the defacto package for data analysis. In this workshop, we are going to use the basics of pandas to analyze the interests of today's group. We a...
Python Code: import meetup.api import pandas as pd from IPython.display import Image, display, HTML from itertools import combinations Explanation: Data Analysis using Pandas Pandas has become the defacto package for data analysis. In this workshop, we are going to use the basics of pandas to analyze the interests of t...
12,831
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="#Lists" data-toc-modified-id="Lists-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Lists</a></div><div class="lev2 toc-item"><a hr...
Python Code: final = "It is with a heavy heart that I take up my pen to write these the last words in which I shall ever record the singular gifts by which my friend Mr. Sherlock Holmes was distinguished." final = final.replace(".", "") final = final.split(" ") final type(final) Explanation: Table of Contents <p><div c...
12,832
Given the following text description, write Python code to implement the functionality described below step by step Description: First, I made a mistake naming the data set! It's 2015 data, not 2014 data. But yes, still use 311-2014.csv. You can rename it. Importing and preparing your data Import your data, but only t...
Python Code: import datetime import datetime as dt dt.datetime.strptime('07/06/2015 10:58:27 AM', '%m/%d/%Y %I:%M:%S %p') #datetime.datetime(2015, 7, 6, 0, 0) parser = lambda date: pd.datetime.strptime(date, '%m/%d/%Y %H:%M:%S') df = pd.read_csv("311-2015.csv", low_memory=False, parse_dates=[1], dtype=str , nrows=20000...
12,833
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Random Forest Contest entry by <a href=\"https Step1: A complete description of the dataset is given in the Original contest notebook by Brendon Hall, Enthought...
Python Code: ###### Importing all used packages %matplotlib inline import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes_locatable import seaborn a...
12,834
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to scikit-learn Classification of Handwritten Digits the task is to predict, given an image, which digit it represents. We are given samples of each of the 10 possible classes (...
Python Code: from sklearn import datasets digits = datasets.load_digits() %pylab inline digits.data digits.data.shape # n_samples, n_features Explanation: Introduction to scikit-learn Classification of Handwritten Digits the task is to predict, given an image, which digit it represents. We are given samples of each of...
12,835
Given the following text description, write Python code to implement the functionality described below step by step Description: Take the set of pings, make sure we have actual clientIds and remove duplicate pings. Step2: We're going to dump each event from the pings. Do a little empty data sanitization so we don't g...
Python Code: def dedupe_pings(rdd): return rdd.filter(lambda p: p["meta/clientId"] is not None)\ .map(lambda p: (p["meta/documentId"], p))\ .reduceByKey(lambda x, y: x)\ .map(lambda x: x[1]) Explanation: Take the set of pings, make sure we have actual clientIds and remove d...
12,836
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Science Demo Step1: And now we create a HiveContext to enable Spark to access data from HIVE Step2: Let's take a look at the dataset - first 5 rows Step3: Exploring the Dataset What ...
Python Code: # Set up Spark Context from pyspark import SparkContext, SparkConf SparkContext.setSystemProperty('spark.executor.memory', '4g') conf = SparkConf() conf.set('spark.sql.autoBroadcastJoinThreshold', 200*1024*1024) # 200MB for map-side joins conf.set('spark.executor.instances', 12) sc = SparkContext('yarn-c...
12,837
Given the following text description, write Python code to implement the functionality described below step by step Description: The dataset The dataset is the mnist digits which is a common toy data set for testing machine learning methods on images. This is a subset of the mnist set which have also been shrunked in ...
Python Code: data = loadmat('small_mnist.mat') # Training data (images, 0-9, even-odd) # Images are stored in a (batch, x, y) array # Labels are integers train_im = data['train_im'] train_y = data['train_y'].ravel() train_eo = data['train_eo'].ravel() # Validation data (images, 0-9, even-odd) # Same format as training ...
12,838
Given the following text description, write Python code to implement the functionality described below step by step Description: Measuring the J/$\psi$ Meson Mass This notebook will walk you through a simplified measurement of the mass of the J/$\psi$ meson. We will use data taken by the CMS experiment hosted on CERN'...
Python Code: # Required imports and setup import os import numpy as np from rootpy.plotting import Hist, Canvas, set_style, get_style from rootpy import asrootpy, log from root_numpy import root2array, fill_hist from ROOT import (RooFit, RooRealVar, RooDataHist, RooArgList, RooVoigtian, RooAddPdf, Roo...
12,839
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 7 Step1: this matrix has $\mathcal{O}(1)$ elements in a row, therefore it is sparse. Finite elements method is also likely to give you a system with a sparse matrix. How to store a ...
Python Code: import matplotlib.pyplot as plt import numpy as np import scipy as sp import matplotlib.cm as cm %matplotlib inline N = 3 B = np.diag(2*np.ones(N)) + np.diag((-1)*np.ones(N-1),k=-1)+ np.diag((-1)*np.ones(N-1),k = 1) Id = np.diag(np.ones(N)); # Assembling a 3D operator: A = np.kron(Id,np.kron(Id,B)) + np.k...
12,840
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting topographic maps of evoked data Load evoked data and plot topomaps for selected time points using multiple additional options. Step1: Basic plot_topomap options We plot evoked topo...
Python Code: # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> # Tal Linzen <linzen@nyu.edu> # Denis A. Engeman <denis.engemann@gmail.com> # Mikołaj Magnuski <mmagnuski@swps.edu.pl> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mne.datasets import...
12,841
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
12,842
Given the following text description, write Python code to implement the functionality described below step by step Description: This is a demo notebook of some of the features of IEtools.py. IEtools includes tools to read FRED economic data https Step1: Read in the files Step2: Here's a plot of nominal GDP Step3: ...
Python Code: import numpy as np import IEtools import pylab as pl %pylab inline Explanation: This is a demo notebook of some of the features of IEtools.py. IEtools includes tools to read FRED economic data https://fred.stlouisfed.org/ in either csv or xls formats. IEtools also includes tools for fitting information equ...
12,843
Given the following text description, write Python code to implement the functionality described below step by step Description: 2.1.1 Huberized Hinge loss Plot on a same plot, with different colors, the misclassification error loss, the (regular) hinge loss, and the huberized hinge loss. Step1: Explain how the hube...
Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.datasets import make_blobs from sklearn.svm import LinearSVC x = np.linspace(-2.0, 2.0, num=100) def huberizedHingeLoss(x, h): if x > 1+h: return 0 elif abs...
12,844
Given the following text description, write Python code to implement the functionality described below step by step Description: Text classification using Neural Networks The goal of this notebook is to learn to use Neural Networks for text classification. In this notebook, we will Step1: Here are all the possible cl...
Python Code: import numpy as np from sklearn.datasets import fetch_20newsgroups newsgroups_train = fetch_20newsgroups(subset='train') newsgroups_test = fetch_20newsgroups(subset='test') sample_idx = 1000 print(newsgroups_train["data"][sample_idx]) target_names = newsgroups_train["target_names"] target_id = newsgroups_t...
12,845
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Model Evaluation & Validation Project 1 Step1: Data Exploration In this first section of this project, you will make a cursory investigation about the B...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd import visuals as vs # Supplementary code from sklearn.cross_validation import ShuffleSplit # Pretty display for notebooks %matplotlib inline # Load the Boston housing dataset data = pd.read_csv('housing.csv') prices = dat...
12,846
Given the following text description, write Python code to implement the functionality described below step by step Description: Trace Analysis Examples Idle States Residency Analysis This notebook shows the features provided by the idle state analysis module. It will be necessary to collect the following events Step1...
Python Code: import logging from conf import LisaLogging LisaLogging.setup() %matplotlib inline import os # Support to access the remote target from env import TestEnv # Support to access cpuidle information from the target from devlib import * # Support to configure and run RTApp based workloads from wlgen import RTA,...
12,847
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Neural Networks Theano Python library that provides efficient (low-level) tools for working with Neural Networks In particular Step1: Inspecting the data Let's load some data Step4: a...
Python Code: from __future__ import absolute_import from __future__ import print_function from ipywidgets import interact, interactive, widgets import numpy as np np.random.seed(1337) # for reproducibility Explanation: Deep Neural Networks Theano Python library that provides efficient (low-level) tools for working wit...
12,848
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Feature Engineering Learning Objectives * Improve the accuracy of a model by using feature engineering * Understand there's two places to do feature engineering in Tensor...
Python Code: import tensorflow as tf import numpy as np import shutil print(tf.__version__) Explanation: Introduction to Feature Engineering Learning Objectives * Improve the accuracy of a model by using feature engineering * Understand there's two places to do feature engineering in Tensorflow 1. Using the tf....
12,849
Given the following text description, write Python code to implement the functionality described below step by step Description: 7 Clustering Goal Step1: Efficiency The algorithm is $O(n^3) = \sum_{i=n}^{2} C_n^2$, since it computes the distances between each pair of clusters in iteration. Optimize Step2: 7.3.2 Init...
Python Code: # Example 7.2 logger.setLevel('WARN') points = np.array([ [4, 10], [7, 10], [4, 8], [6, 8], [3, 4], [10, 5], [12, 6], ...
12,850
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook shows how to use an index file.<br/> This example uses the index file from the Mediterranean Sea region (INSITU_MED_NRT_OBSERVATIONS_013_035) corresponding to the latest data.<...
Python Code: indexfile = "./datafiles/index_latest.txt" Explanation: This notebook shows how to use an index file.<br/> This example uses the index file from the Mediterranean Sea region (INSITU_MED_NRT_OBSERVATIONS_013_035) corresponding to the latest data.<br/> If you download the same file, the results will be sligh...
12,851
Given the following text description, write Python code to implement the functionality described below step by step Description: Product SVD in Python In this NoteBook, the reader will find code to load GeoTiff files, single- or multi-band, from HDFS. It reads the GeoTiffs as a ByteArrays and then stores the GeoTiffs ...
Python Code: #Add all dependencies to PYTHON_PATH import sys sys.path.append("/usr/lib/spark/python") sys.path.append("/usr/lib/spark/python/lib/py4j-0.10.4-src.zip") sys.path.append("/usr/lib/python3/dist-packages") sys.path.append("/data/local/jupyterhub/modules/python") #Define environment variables import os os.env...
12,852
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the trained weights in an ensemble of neurons On the function points branch of nengo On the vision branch of nengo_extras Step1: Load the MNIST database Step2: Each digit is represen...
Python Code: import nengo import numpy as np import cPickle from nengo_extras.data import load_mnist from nengo_extras.vision import Gabor, Mask from matplotlib import pylab import matplotlib.pyplot as plt import matplotlib.animation as animation Explanation: Using the trained weights in an ensemble of neurons On the f...
12,853
Given the following text description, write Python code to implement the functionality described below step by step Description: Author Step1: Simulated FastQ data Installation Step2: Creating the BAM (mapping) and BED files Step3: This uses bwa and samtools behind the scene. Then, we will convert the resulting BAM...
Python Code: !sequana_coverage --download-reference FN433596 Explanation: Author: Thomas Cokelaer Jan 2018 Local time execution: about 10 minutes In this notebook, we will simulate fastq reads and inject CNVs. We will then look at the sensitivity (proportion of true positive by the sum of positives) of sequana_coverag...
12,854
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Advanced Step3: Let's also combine our plotting code into a cohesive function Step4: Now we can tie our plot function, plot_planck, to the interact function from ipywidgets
Python Code: # Import numpy and alias to "np" import numpy as np # Import and alias to "plt" import matplotlib.pyplot as plt def planck(wavelength, temp): Return the emitted radiation from a blackbody of a given temp and wavelength Args: wavelength (float): wavelength (m) temp (float): tem...
12,855
Given the following text description, write Python code to implement the functionality described below step by step Description: TOC Thematic Report - February 2019 (Part 1 Step2: 1.2. Finland Jussi has supplied an entirely new dataset for all Finnish stations covering the period from 1990 to 2017. This supersedes th...
Python Code: ## Switch TOC/DOC pre-March 1995 to method with correction factor of 1.28 #with eng.begin() as conn: # sql = ("UPDATE resa2.water_chemistry_values2 " # "SET method_id = 10823 " # "WHERE sample_id IN ( " # " SELECT water_sample_id " # " FROM resa2.water_samples ...
12,856
Given the following text description, write Python code to implement the functionality described below step by step Description: Get information for all stations in list and write out to JSON file Step1: Optional
Python Code: OUTFN = "AK_NCDC_FirstOrderStations.json" SAVEDATA = False stationdata = [] for station in all_stations: path = os.path.join(endpoint_stations, "GHCND:{}".format(station)) fullbase = requests.compat.urljoin(baseurl, path) r = requests.get( fullbase, headers=custom_headers, ...
12,857
Given the following text description, write Python code to implement the functionality described below step by step Description: $$\begin{align}\Omega &= [0, 1]^2\ \Gamma_D &= \partial\Omega\end{align}$$ Step1: $$\begin{align}\kappa(x; \mu) &
Python Code: g = grid.make_cube_grid__2d_simplex_aluconform(lower_left=[0, 0], upper_right=[1, 1], num_elements=[4, 4], num_refinements=2, overlap_size=[0, 0]) #g.visualize('grid') Explanation: $$\begin{align}\Omega &= [0, 1]^2\ \Gamma_D &= \partial\Omega\end{align}$$ End of explanation #bump = functions.make_expressio...
12,858
Given the following text description, write Python code to implement the functionality described below step by step Description: Contextual Bandits with TF-agents Learning Objectives Learn to load a dataset in BigQuery and connect to it using TensorFlow IO Learn how to transform a classification dataset into a context...
Python Code: pip freeze | grep tf_agents || pip install -q tf_agents==0.11.0 Explanation: Contextual Bandits with TF-agents Learning Objectives Learn to load a dataset in BigQuery and connect to it using TensorFlow IO Learn how to transform a classification dataset into a contextual bandit problem Learn how to stream a...
12,859
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Sklearn Gradient Boosting Regressor - Training a Regression Model
Python Code:: from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, mean_absolute_error, max_error, explained_variance_score, mean_absolute_percentage_error # initialise & fit Gradient Boosting Regressor model = GradientBoostingRegressor(loss='squared_error', ...
12,860
Given the following text description, write Python code to implement the functionality described below step by step Description: d3viz Step1: Like Theano’s printing module, d3viz requires graphviz binary to be available. Overview d3viz extends Theano’s printing module to interactively visualize compute graphs. Instea...
Python Code: !pip install pydot-ng Explanation: d3viz: Interactive visualization of Theano compute graphs Requirements d3viz requires the pydot package. pydot-ng fork is better maintained, and it works both in Python 2.x and 3.x. Install it with pip:: End of explanation import theano as th import theano.tensor as T imp...
12,861
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <h1> ILI285 - Computación Científica I / INF285 - Computación Científica </h1> <h2> Linear Systems of Equations </h2> <h2> <a href="#acknowledgements"> [S]cientific [C]...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: <center> <h1> ILI285 - Computación Científica I / INF285 - Computación Científica </h1> <h2> Linear Systems of Equations </h2> <h2> <a href="#acknowledgements"> [S]cientific [C]omputing [T]eam </a> </h2> <h2...
12,862
Given the following text description, write Python code to implement the functionality described below step by step Description: Python API to EasyForm Step1: You can access the values from the form by treating it as an array indexed on the field names Step2: The array works both ways, so you set default values on t...
Python Code: from beakerx import * f = EasyForm("Form and Run") f.addTextField("first") f['first'] = "First" f.addTextField("last") f['last'] = "Last" f.addButton("Go!", tag="run") f Explanation: Python API to EasyForm End of explanation "Good morning " + f["first"] + " " + f["last"] f['last'][::-1] + '...' + f['first'...
12,863
Given the following text description, write Python code to implement the functionality described below step by step Description: Ordinary Differential Equations Exercise 3 Imports Step1: Damped, driven nonlinear pendulum The equations of motion for a simple pendulum of mass $m$, length $l$ are Step4: Write a functio...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.integrate import odeint from IPython.html.widgets import interact, fixed Explanation: Ordinary Differential Equations Exercise 3 Imports End of explanation g = 9.81 # m/s^2 l = 0.5 # length of pendul...
12,864
Given the following text description, write Python code to implement the functionality described below step by step Description: SAP Credv2 The following subsections show a representation of the file format portions and how to generate them. First we need to perform some setup to import the packet classes Step1: Cred...
Python Code: from pysap.SAPCredv2 import * from IPython.display import display Explanation: SAP Credv2 The following subsections show a representation of the file format portions and how to generate them. First we need to perform some setup to import the packet classes: End of explanation with open("../../tests/data/cr...
12,865
Given the following text description, write Python code to implement the functionality described below step by step Description: Recommendation Methods Step1: Recommendation Comparison A more general framework for comparing different recommendation techniques Evaluation DataSet See notes in the creating_dataset_for_e...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') %matplotlib inline import sys import os sys.path.append('../') os.getcwd() import src import src.recommendation reload(src.recommendation) from src.recommendation import * Explanation: Recomm...
12,866
Given the following text description, write Python code to implement the functionality described below step by step Description: Implicit Georeferencing This workbook sets explicit georeferences from implicit georeferencing through names of extents given in dataset titles or keywords. A file sources.py needs to contai...
Python Code: import ckanapi from harvest_helpers import * from secret import CKAN ckan = ckanapi.RemoteCKAN(CKAN["dpaw-internal"]["url"], apikey=CKAN["dpaw-internal"]["key"]) print("Using CKAN {0}".format(ckan.address)) Explanation: Implicit Georeferencing This workbook sets explicit georeferences from implicit georefe...
12,867
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction To OANDA-System Environment Step1: Data Containers Tick Bar Event Objects market event bar event signal event order event fill event Event Queue Object Should be structured in ...
Python Code: from api import* myConfig = Config() myConfig.view() Explanation: Introduction To OANDA-System Environment: Python-Anaconda 2.7 pandas, json, requests Config Class Contains infomations that we need to connect to OANDA server and make requests. End of explanation q1 = EventQueue() q2 = EventQueue() q = {'mk...
12,868
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial de especificação de histograma, caso discreto exato O problema consiste em mapear os pixels de uma imagem dada para que o histograma da imagem transformada seja um histograma especi...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import sys,os ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia hout = np.concatenate((np.arange(128),np.aran...
12,869
Given the following text description, write Python code to implement the functionality described below step by step Description: First, load up the data First you're going to want to create a data frame from the dailybots.csv file which can be found in the data directory. You should be able to do this with the pd.rea...
Python Code: data = pd.read_csv( '../../data/dailybots.csv' ) #Look at a summary of the data data.describe() data['botfam'].value_counts() Explanation: First, load up the data First you're going to want to create a data frame from the dailybots.csv file which can be found in the data directory. You should be able to d...
12,870
Given the following text description, write Python code to implement the functionality described below step by step Description: Bolidozor FITS files time restorer For use of this notebook you must have mounted space.astro.cz storage server to local filesystem. It is possible to do with sshfs bash sshfs &lt;user&gt;...
Python Code: import os import datetime import numpy import scipy.signal from astropy.io import fits import matplotlib.pyplot as plt import matplotlib.dates as md %matplotlib inline paths = ['/home/roman/mnt/server-space/storage/bolidozor/ZVPP/ZVPP-R6/snapshots/2017/09/'] times = numpy.ndarray((0,2)) start_time = date...
12,871
Given the following text description, write Python code to implement the functionality described below step by step Description: Object Detection API Demo <table align="left"><td> <a target="_blank" href="https Step1: Make sure you have pycocotools installed Step2: Get tensorflow/models or cd to parent directory ...
Python Code: !pip install -U --pre tensorflow=="2.*" !pip install tf_slim Explanation: Object Detection API Demo <table align="left"><td> <a target="_blank" href="https://colab.sandbox.google.com/github/tensorflow/models/blob/master/research/object_detection/colab_tutorials/colab_tutorials/object_detection_tutorial....
12,872
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Python This tutorial was originally drawn from Scipy Lecture Notes by this list of contributors. I've continued to modify it as I use it. This work is CC-BY. Author Step1: A...
Python Code: # open the source CSV file csv = open("cars.csv") # create a list with the column names. we assume the first row contiains them. # we strip the carriage return (if there is one) from the line, then split values on the commas. # Note: this uses a nifty python feature called 'list comprehension' to do it in ...
12,873
Given the following text description, write Python code to implement the functionality described below step by step Description: Scraping Reviews This notebook shows how to use the scrape reviews from Indeed and Glassdoor. To visualize the ratings go to the Ratings notebook and to do topic modeling go to the Topic Mod...
Python Code: # Search settings KEYWORD_FILTER = "Data Scientist" LOCATION_FILTER = "New York City, NY" # Other settings MAX_PAGES_COMPANIES = 500 MAX_PAGES_REVIEWS = 500 import os import re from datetime import datetime from pymongo import MongoClient import indeed import glassdoor import utils # DB settings client = M...
12,874
Given the following text description, write Python code to implement the functionality described below step by step Description: INF-495, v0.01, Claudio Torres, ctorres@inf.utfsm.cl. DI-UTFSM Textbook Step1: First algorithm Step2: Second algorithm Step3: Third algorithm Step4: 8.2 Stochastic predator-prey model
Python Code: import numpy as np import scipy.sparse.linalg as sp import sympy as sym from scipy.linalg import toeplitz import ipywidgets as widgets from ipywidgets import IntSlider import matplotlib.pyplot as plt %matplotlib inline from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatte...
12,875
Given the following text description, write Python code to implement the functionality described below step by step Description: Workshop 4 - Performance Metrics In this workshop we study 2 performance metrics(Spread and Inter-Generational Distance) on GA optimizing the POM3 model. Step2: To compute most measures, da...
Python Code: %matplotlib inline # All the imports from __future__ import print_function, division import pom3_ga, sys import pickle # TODO 1: Enter your unity ID here __author__ = "dndesai" Explanation: Workshop 4 - Performance Metrics In this workshop we study 2 performance metrics(Spread and Inter-Generational Dista...
12,876
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Module 1 Step2: Given the dataset, let's test our dataset by seeing some of the images and their corresponding labels. PyTorch provides us with a neat little function called make_gri...
Python Code: import sys, os import pickle import torch import torch.utils.data as data import glob from PIL import Image import numpy as np def unpickle(fname): with open(fname, 'rb') as f: Dict = pickle.load(f, encoding='bytes') return Dict def load_data(batch): print ("Loading batch:{}".format...
12,877
Given the following text description, write Python code to implement the functionality described below step by step Description: Kalman Filter and your Matrix Class Once you have a working matrix class, you can use the class to run a Kalman filter! You will need to put your matrix class into the workspace Step1: Vis...
Python Code: %matplotlib inline import pandas as pd import math import matplotlib.pyplot as plt import matplotlib import datagenerator import matrix as m matplotlib.rcParams.update({'font.size': 16}) # data_groundtruth() has the following inputs: # Generates Data # Input variables are: # initial position meters # initi...
12,878
Given the following text description, write Python code to implement the functionality described below step by step Description: VirtualEATING Andrew Lane, University of California, Berkeley Overview CRISPR-EATING is a molecular biology protocol to generate libraries of CRISPR guide RNAs. The use of this this approach...
Python Code: import Bio from Bio.Blast.Applications import NcbiblastnCommandline from Bio import SeqIO from Bio.Blast import NCBIXML from Bio import Restriction from Bio.Restriction import * from Bio.Alphabet.IUPAC import IUPACAmbiguousDNA from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord import cPickle as ...
12,879
Given the following text description, write Python code to implement the functionality described below step by step Description: Example Q3 Step1: Creating the Default Filter Pipeline Step2: The PipelineManager is analogous to the ChannelLibrary insomuchas it provides the user with an interface to programmatically m...
Python Code: from QGL import * cl = ChannelLibrary(":memory:") # Create five qubits and supporting hardware for i in range(5): q1 = cl.new_qubit(f"q{i}") cl.new_APS2(f"BBNAPS2-{2*i+1}", address=f"192.168.5.{101+2*i}") cl.new_APS2(f"BBNAPS2-{2*i+2}", address=f"192.168.5.{102+2*i}") cl.new_X6(f"X6_{i}", ...
12,880
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: colvolve given image uisng python or scipy
Python Code:: from scipy.signal import convolve2d import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt gray = np.mean(image, axis =2) x = np.linspace(-6, 6 , 40) fx = norm.pdf(x, loc= 0, scale =1) filt = np.outer(fx, fx) output = convolve2d(gray, filt) plt.imshow(output)
12,881
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 ...
12,882
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 1. Write a function that returns the Pythagorean triplet (a, b, c) given any two of the arguments a, b or c. For example, triplet(a=3, c=5) will return (3, 4, 5). Step3: 2. The $n^\t...
Python Code: import numpy as np def triplet(a=None, b=None, c=None): Returns the Pythagoraen tripler (a, b, c) given any two arguments. Assumes but does not check that two named argumets are called. Retruns None if no triplet possible with given arguments. if a is None: q, r = div...
12,883
Given the following text description, write Python code to implement the functionality described below step by step Description: Outline Glossary Positional Astronomy Next Step1: Import section specific modules
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS Explanation: Outline Glossary Positional Astronomy Next: Equatorial Coordinates Import standard modules: End of explanation from IPython.display import HTML...
12,884
Given the following text description, write Python code to implement the functionality described below step by step Description: Memory-efficient embeddings for recommendation systems Author Step1: Prepare the data Download and process data Step2: Create train and eval data splits Step3: Define dataset metadata and...
Python Code: import os import math from zipfile import ZipFile from urllib.request import urlretrieve import numpy as np import pandas as pd import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers import StringLookup import matplotlib.pyplot as plt Explanati...
12,885
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-nu...
Python Code: debug_flag = False Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Introduction</a></span></li><li><span><a href="#Setup" data-to...
12,886
Given the following text description, write Python code to implement the functionality described below step by step Description: What is Serial Dependence? In earlier lessons, we investigated properties of time series that were most easily modeled as time dependent properties, that is, with features we could derive di...
Python Code: #$HIDE_INPUT$ import pandas as pd # Federal Reserve dataset: https://www.kaggle.com/federalreserve/interest-rates reserve = pd.read_csv( "../input/ts-course-data/reserve.csv", parse_dates={'Date': ['Year', 'Month', 'Day']}, index_col='Date', ) y = reserve.loc[:, 'Unemployment Rate'].dropna().to...
12,887
Given the following text description, write Python code to implement the functionality described below step by step Description: http Step1: Complex 1-n correspondance Step2: https
Python Code: keyEN = ['red', 'yellow', 'green', 'blue', 'black'] keyFR1 = ['rouge', 'jaune', 'vert', 'bleu', 'noir'] keyFR2 = ['jaune', 'vert', 'bleu', 'noir', 'rouge'] keyDE = ['gelb', 'gruen', 'blau', 'schwartz', 'rot'] dataENFR = pd.DataFrame({'keyEN' : keyEN, 'keyFR' : keyFR1}) dataENFR dataFRDE = pd.DataFrame({'ke...
12,888
Given the following text description, write Python code to implement the functionality described below step by step Description: The input data Here we use the (not publically available) data for Chicago, which has we believe accurate geocoding. Step1: Just the south side Step2: Covariance For KDE applications, it i...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib import descartes import os import numpy as np import descartes import open_cp.sources.chicago as chicago import open_cp.naive import open_cp.geometry import open_cp.plot datadir = os.path.join("//media", "disk", "Data") #datadir = os.path...
12,889
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In this blog post, I want to show you a graph-based way to split up a class into several independent ones. We take a small example class from Michael Feathers' book "Working eff...
Python Code: %load_ext cypher Explanation: Introduction In this blog post, I want to show you a graph-based way to split up a class into several independent ones. We take a small example class from Michael Feathers' book "Working effectively with legacy code" and use Neo4j's Awesome Procedures On Cypher (APOC). Hint: T...
12,890
Given the following text description, write Python code to implement the functionality described below step by step Description: Async optimization Loop Tim Head, February 2017. Step1: Bayesian optimization is used to tune parameters for walking robots or other experiments that are not a simple (expensive) function c...
Python Code: import numpy as np np.random.seed(1234) %matplotlib inline import matplotlib.pyplot as plt plt.set_cmap("viridis") Explanation: Async optimization Loop Tim Head, February 2017. End of explanation from skopt.learning import ExtraTreesRegressor from skopt import Optimizer noise_level = 0.1 # Our 1D toy probl...
12,891
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Auto Encoders Reference Step1: Fashion MNIST Step2: Standard full-connected VAE model Let's define a VAE model with fully connected MLPs for the encoder and decoder networks. ...
Python Code: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from tensorflow.keras.layers import Input, Dense, Lambda, Flatten, Reshape, Conv2D, Conv2DTranspose from tensorflow.keras.models import Model from tensorflow.keras import metrics from tensorflow.keras.da...
12,892
Given the following text description, write Python code to implement the functionality described below step by step Description: Build simple models to predict pulsar candidates In this notebook we will look at building machine learning models to predict Pulsar Candidate. The data comes from Rob Lyon at Manchester. Th...
Python Code: # For numerical stuff import pandas as pd # Plotting import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline plt.rcParams['figure.figsize'] = (7.0, 7.0) # Some preprocessing utilities from sklearn.cross_validation import train_test_split # Data splitting from sklearn.util...
12,893
Given the following text description, write Python code to implement the functionality described below step by step Description: 201 - Engineering Text Features Using mmlspark Modules and Spark SQL Again, try to predict Amazon book ratings greater than 3 out of 5, this time using the TextFeaturizer module which is a c...
Python Code: import pandas as pd import mmlspark from pyspark.sql.types import IntegerType, StringType, StructType, StructField dataFile = "BookReviewsFromAmazon10K.tsv" textSchema = StructType([StructField("rating", IntegerType(), False), StructField("text", StringType(), False)]) import os, u...
12,894
Given the following text description, write Python code to implement the functionality described below step by step Description: version 1.0.2 + Introduction to Machine Learning with Apache Spark Predicting Movie Ratings One of the most common uses of big data is to predict what users want. This allows Google to sh...
Python Code: import sys import os from test_helper import Test baseDir = os.path.join('data') inputPath = os.path.join('cs100', 'lab4', 'small') ratingsFilename = os.path.join(baseDir, inputPath, 'ratings.dat.gz') moviesFilename = os.path.join(baseDir, inputPath, 'movies.dat') Explanation: version 1.0.2 + Introductio...
12,895
Given the following text description, write Python code to implement the functionality described below step by step Description: Logbook Blocking An implementation of the network-based blocking mechanism Step1: Graph Structured Pairwise Comparisons By implementing a graph where person entity nodes are a tuple of (nam...
Python Code: %matplotlib inline import os import sys import random import networkx as nx ## Paths from the file PROJECT = os.path.join(os.getcwd(), "..") FIXTURES = os.path.join(PROJECT, "fixtures") DATASET = os.path.join(FIXTURES, 'activity.csv') ## Append the path for the logbook utilities sys.path.append(PROJE...
12,896
Given the following text description, write Python code to implement the functionality described below step by step Description: Example for using the Pvlib model The Pvlib model can be used to determine the feed-in of a photovoltaic module using the pvlib. The pvlib is a python library for simulating the performance ...
Python Code: from feedinlib import Photovoltaic # suppress warnings import warnings warnings.filterwarnings("ignore") Explanation: Example for using the Pvlib model The Pvlib model can be used to determine the feed-in of a photovoltaic module using the pvlib. The pvlib is a python library for simulating the performance...
12,897
Given the following text description, write Python code to implement the functionality described below step by step Description: Биномиальный критерий для доли Step1: Shaken, not stirred Джеймс Бонд говорит, что предпочитает мартини взболтанным, но не смешанным. Проведём слепой тест (blind test) Step2: Односторонняя...
Python Code: import numpy as np from scipy import stats %pylab inline Explanation: Биномиальный критерий для доли End of explanation n = 16 F_H0 = stats.binom(n, 0.5) x = np.linspace(0,16,17) pylab.bar(x, F_H0.pmf(x), align = 'center') xlim(-0.5, 16.5) pylab.show() Explanation: Shaken, not stirred Джеймс Бонд говорит,...
12,898
Given the following text description, write Python code to implement the functionality described below step by step Description: Mit Datenanalysen Probleme in der Entwicklung aufzeigen <small>Java User Group Hessen, Kassel, 25.04.2019</small> <b>Markus Harrer</b>, Software Development Analyst Twitter Step1: Was haben...
Python Code: import pandas as pd log = pd.read_csv("../dataset/linux_blame_log.csv.gz") log.head() Explanation: Mit Datenanalysen Probleme in der Entwicklung aufzeigen <small>Java User Group Hessen, Kassel, 25.04.2019</small> <b>Markus Harrer</b>, Software Development Analyst Twitter: @feststelltaste Blog: feststelltas...
12,899
Given the following text description, write Python code to implement the functionality described below step by step Description: OIQ Exam Question 2 Question from OIQ Technical Exam, obviously meant to be solved using moment distribution, but here we see how easy it is using slope deflection instead. This version use...
Python Code: from IPython import display display.SVG('oiq-frame-1.svg') Explanation: OIQ Exam Question 2 Question from OIQ Technical Exam, obviously meant to be solved using moment distribution, but here we see how easy it is using slope deflection instead. This version users a newer version of 'sdutil' that computes ...