Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
12,400
Given the following text description, write Python code to implement the functionality described below step by step Description: Using subset-selector Create SubsetSelector with data and plot. y should be a multidimensional array. Each sample from a subset of y is graphed. You can scroll through subsets using the figu...
Python Code: from subset_selector import SubsetSelector ss = SubsetSelector(x, y) ss.plot() Explanation: Using subset-selector Create SubsetSelector with data and plot. y should be a multidimensional array. Each sample from a subset of y is graphed. You can scroll through subsets using the figure's toolbar, select grap...
12,401
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: はじめに マスキングは、シーケンス処理レイヤーに入力...
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...
12,402
Given the following text description, write Python code to implement the functionality described below step by step Description: See quick reference at the bottom See full module reference section for full details In the begining of each analysis, the first step is to load ReproPhylo and its dependencies with the comm...
Python Code: from reprophylo import * Explanation: See quick reference at the bottom See full module reference section for full details In the begining of each analysis, the first step is to load ReproPhylo and its dependencies with the command End of explanation coi = Locus(char_type='dna', feature_type='...
12,403
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 3 Step1: if ... else statement python if &lt;condition&gt; Step2: if ...elif ... else statement python if &lt;condition&gt; Step3: Imagine that in the above program, 23 is the tem...
Python Code: password = input("Please enter the password:") if password == "Simsim": print("\t> Welcome to the cave") x = "Mayank" y = "TEST" if y == "TEST": print(x) if y: print("Hello World") z = None if z: print("TEST") x = 11 if x > 10: print("Hello") if x > 10.999999999999: print("H...
12,404
Given the following text description, write Python code to implement the functionality described below step by step Description: This IPython Notebook is for integrating filter curves with the spectra to show the Si gap's effect size on tranmission in IR imaging. Author Step1: From the Thorlabs website Step2: Normal...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns Explanation: This IPython Notebook is for integrating filter curves with the spectra to show the Si gap's effect size on tranmission in IR imaging. Author: Michael Gully-Santiago, gully@astro.as....
12,405
Given the following text description, write Python code to implement the functionality described below step by step Description: Spark + Python = PySpark Esse notebook introduz os conceitos básicos do Spark através de sua interface com a linguagem Python. Como aplicação inicial faremos o clássico examplo de contador d...
Python Code: from pyspark import SparkContext sc =SparkContext() ListaPalavras = ['gato', 'elefante', 'rato', 'rato', 'gato'] palavrasRDD = sc.parallelize(ListaPalavras, 4) print type(palavrasRDD) Explanation: Spark + Python = PySpark Esse notebook introduz os conceitos básicos do Spark através de sua interface com a l...
12,406
Given the following text description, write Python code to implement the functionality described below step by step Description: Source localization with MNE/dSPM/sLORETA/eLORETA The aim of this tutorial is to teach you how to compute and apply a linear inverse method such as MNE/dSPM/sLORETA/eLORETA on evoked/raw/epo...
Python Code: # sphinx_gallery_thumbnail_number = 10 import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse Explanation: Source localization with MNE/dSPM/sLORETA/eLORETA The aim of this tutorial is to teach you how ...
12,407
Given the following text description, write Python code to implement the functionality described below step by step Description: CrowdTruth for Multiple Choice Tasks Step1: Declaring a pre-processing configuration The pre-processing configuration defines how to interpret the raw crowdsourcing input. To do this, we ne...
Python Code: import pandas as pd test_data = pd.read_csv("../data/relex-multiple-choice.csv") test_data.head() Explanation: CrowdTruth for Multiple Choice Tasks: Relation Extraction In this tutorial, we will apply CrowdTruth metrics to a multiple choice crowdsourcing task for Relation Extraction from sentences. The wor...
12,408
Given the following text description, write Python code to implement the functionality described below step by step Description: GitHub Analiza iz V tem projektu bomo analizirali najpopularnejše odprte repozitorije na priljubljeni strani GitHub. Podatki so bili zajeti iz https Step1: Naložimo zajete podatke in si ogl...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline pd.options.display.max_rows = 20 Explanation: GitHub Analiza iz V tem projektu bomo analizirali najpopularnejše odprte repozitorije na priljubljeni strani GitHub. Podatki so bili zajeti iz https://api.github.com, kar ...
12,409
Given the following text description, write Python code to implement the functionality described below step by step Description: How many movies are listed in the titles dataframe? Step1: What are the earliest two films listed in the titles dataframe? Step2: How many movies have the title "Hamlet"? Step3: How many ...
Python Code: titles.tail() len(titles) Explanation: How many movies are listed in the titles dataframe? End of explanation titles.sort(columns='year', ascending=True).head()[:2] Explanation: What are the earliest two films listed in the titles dataframe? End of explanation titles[titles['title'].str.contains('Hamlet')]...
12,410
Given the following text description, write Python code to implement the functionality described below step by step Description: Conventional "dB-differencing" analysis Step1: Set params and load clean MVBS data Step2: dB-differencing operation Here I used the criteria from Sato et al. 2015 for dB-differencing. The ...
Python Code: import os, sys, glob, re import datetime as dt import numpy as np from matplotlib.dates import date2num,num2date import h5py sys.path.insert(0,'..') sys.path.insert(0,'../mi_instrument/') import db_diff import decomp_plot import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatab...
12,411
Given the following text description, write Python code to implement the functionality described below step by step Description: DATA 643 - Final Project Sreejaya Nair and Suman K Polavarapu Description Step1: Prepare the pySpark Environment Step2: Initialize Spark Context Step3: Load and Analyse Data Step4: Ratin...
Python Code: import os import sys import urllib2 import collections import matplotlib.pyplot as plt import math from time import time, sleep %pylab inline Explanation: DATA 643 - Final Project Sreejaya Nair and Suman K Polavarapu Description: Explore the Apache Spark Cluster Computing Framework by analysing the moviele...
12,412
Given the following text description, write Python code to implement the functionality described below step by step Description: Contents Step1: 2. Millionaires What country are most billionaires from? For the top ones, how many billionaires per billion people? Step2: What's the average wealth of a billionaire? Male...
Python Code: import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv("07-hw-animals.csv") df.columns df.head(3) df.sort_values(by='length', ascending=False).head(3) df['animal'].value_counts() dogs = df[df['animal']=='dog'] dogs df[df['length'] > 40] df['inches'] = .393701 * df['length']...
12,413
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="alert alert-block alert-info" style="margin-top Step1: <a id="ref0"></a> <h2> Helper Functions </h2> Functions used to plot Step2: dataset object Step3: <a id='ref1'> </a> <h2...
Python Code: import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from matplotlib.colors import ListedColormap torch.manual_seed(1) Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="http://cocl.us/NotebooksPython1...
12,414
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Face Generation In this project, you'll use generative adversarial networks to generate new images of faces. Get the Data You'll be using two datasets in this project Step3: Explore ...
Python Code: data_dir = './data' # FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe" #data_dir = '/input/R5KrjnANiKVhLWAkpXhNBe' import time import pylab as pl from IPython import display DON'T MODIFY ANYTHING IN THIS CELL import helper helper.download_extract('mnist', data_dir) helper.download_extract('celeba', dat...
12,415
Given the following text description, write Python code to implement the functionality described below step by step Description: Hadamard Multitask GP Regression Introduction This notebook demonstrates how to perform "Hadamard" multitask regression. This differs from the multitask gp regression example notebook in on...
Python Code: import math import torch import gpytorch from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 Explanation: Hadamard Multitask GP Regression Introduction This notebook demonstrates how to perform "Hadamard" multitask regression. This differs from the multitask gp regre...
12,416
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,417
Given the following text description, write Python code to implement the functionality described below step by step Description: Astropy quantities Astropy quantitites are a great way to handle all sorts of messy unit conversions. Careful unit conversions save lives! https Step1: A brief word of warning, the pretty...
Python Code: print(type(u.Msun)) u.Msun Explanation: Astropy quantities Astropy quantitites are a great way to handle all sorts of messy unit conversions. Careful unit conversions save lives! https://en.wikipedia.org/wiki/Gimli_Glider The simplest way to create a new quantity object is multiply or divide a number by ...
12,418
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', 'fio-ronm', 'sandbox-1', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: FIO-RONM Source ID: SANDBOX-1 Topic: Landice Sub-Topics: Glaciers, Ic...
12,419
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Density Estimation Step1: Introducing Gaussian Mixture Models We previously sa...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats plt.style.use('seaborn') Explanation: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Density Estimation: Gaussian Mixture Models Here we'll explore G...
12,420
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Complexity, Overfitting and Underfitting Step1: Validation Curves Step2: Exercise Plot the validation curve on the digit dataset for
Python Code: from plots import plot_kneighbors_regularization plot_kneighbors_regularization() Explanation: Model Complexity, Overfitting and Underfitting End of explanation from sklearn.datasets import load_digits from sklearn.ensemble import RandomForestClassifier from sklearn.learning_curve import validation_curve d...
12,421
Given the following text description, write Python code to implement the functionality described below step by step Description: A class to represent Phase Noise imports Step1: Introduction This document present a class in the plldesinger python module used to represent phase noise. The class have methods to compute...
Python Code: from __future__ import division # Matrix computation import numpy as np from numpy import sqrt, diff, conj from numpy.random import randn # Signal processing routines import scipy.signal as sig # Symbolic math import sympy as sym sym.init_printing(use_latex='mathjax') # Plotting import matplotlib import ma...
12,422
Given the following text description, write Python code to implement the functionality described below step by step Description: Rabi model fitting Step1: The model According to the Rabi model, the probability of being in the excited state, $p_e$ is given by, \begin{equation} P_e = a_0 + a_1 \frac{\Omega^2}{W^2} ...
Python Code: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats from scipy.optimize import curve_fit %matplotlib inline Explanation: Rabi model fitting End of explanation def rabiModel(time, rabiFreq, T1, Tdec, phi, a0, a1, a2, detuning=0.0): phi_deg = phi*(np.pi/180) W = np.sqrt(rab...
12,423
Given the following text description, write Python code to implement the functionality described below step by step Description: Encontro 03 Step1: Carregando e visualizando o grafo
Python Code: import sys sys.path.append('..') import socnet as sn Explanation: Encontro 03: Grafos Reais Importando a biblioteca: End of explanation sn.node_size = 3 sn.node_color = (0, 0, 0) sn.edge_width = 1 sn.edge_color = (192, 192, 192) sn.node_label_position = 'top center' g = sn.load_graph('twitter.gml') sn.show...
12,424
Given the following text description, write Python code to implement the functionality described below step by step Description: Network Analysis This group exercise is designed to develop an understanding of basic network measures and to start participants thinking about interesting research questions that can be ena...
Python Code: with open('karate_edges_77.txt', 'rb') as file: karate_club = nx.read_edgelist(file) # Read in the edges groups = {} with open('karate_groups.txt', 'r') as file: for line in file: [node, group] = re.split(r'\t+', line.strip()) groups[node] = int(group) nx.set_node_attributes(karate...
12,425
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary The iterative reweighted TF-MxNE solver is a distributed inverse method based on the TF-MxNE solver, which prom...
Python Code: # Author: Mathurin Massias <mathurin.massias@gmail.com> # Yousra Bekhti <yousra.bekhti@gmail.com> # Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import os.path as op import mne from mne.datasets impo...
12,426
Given the following text description, write Python code to implement the functionality described below step by step Description: Reproducing "Observations on the statistical iterations of matrices" by J.H. Hetherington* I. Introduction We can use stochastic iteration to effect the power method for sampling the extrema...
Python Code: # construct an exemplary non-negative matrix A = zeros([2,2]) A[0,0] = 2.0 A[1,1] = 1.0 A[1,0] = 3.0 A[0,1] = 4.0 print 'Matrix A: \n', A # verify that columns do not sum to 1 print 'Column 0 sum: ', sum(A[:,0]) print 'Column 1 sum: ', sum(A[:,1]) print 'Matrix A is non-negative but the columns do not sum ...
12,427
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 4 Step1: If we want to do any "feature engineering" like creating new features or adjusting existing ones we should do this directly using the SFrames as seen in the first n...
Python Code: import graphlab import numpy as np import pandas as pd from sklearn import linear_model import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') %matplotlib inline Explanation: Regression Week 4: Ridge Regression (gradient descent) In this notebook, we will i...
12,428
Given the following text description, write Python code to implement the functionality described below step by step Description: Azimuthal Integral Introduction This tutorial demonstrates how to acquire an azimuthal integral profile from a multidimensional data set in pyXem. The data set is a 10x10x256x256 data set o...
Python Code: %matplotlib inline import hyperspy.api as hs import numpy as np import matplotlib.pyplot as plt Explanation: Azimuthal Integral Introduction This tutorial demonstrates how to acquire an azimuthal integral profile from a multidimensional data set in pyXem. The data set is a 10x10x256x256 data set of a poly...
12,429
Given the following text description, write Python code to implement the functionality described below step by step Description: Parameter selection, Validation & Testing Most models have parameters that influence how complex a model they can learn. Remember using KNeighborsRegressor. If we change the number of neighb...
Python Code: from figures import plot_kneighbors_regularization plot_kneighbors_regularization() Explanation: Parameter selection, Validation & Testing Most models have parameters that influence how complex a model they can learn. Remember using KNeighborsRegressor. If we change the number of neighbors we consider, we ...
12,430
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create The Data The dataset used in this tutorial is the famous iris dataset. The Iris target data contains 50 samples from three species of Iris, y and four feature variables,...
Python Code: import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.feature_selection import SelectFromModel from sklearn.metrics import accuracy_score Explanation: Title: Feature Selection Using Random Forest...
12,431
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Lime with Pytorch In this tutorial we will show how to use Lime framework with Pytorch. Specifically, we will use Lime to explain the prediction generated by one of the pretrained Imag...
Python Code: import matplotlib.pyplot as plt from PIL import Image import torch.nn as nn import numpy as np import os, json import torch from torchvision import models, transforms from torch.autograd import Variable import torch.nn.functional as F Explanation: Using Lime with Pytorch In this tutorial we will show how t...
12,432
Given the following text description, write Python code to implement the functionality described below step by step Description: Training a better model Step1: Are we underfitting? Our validation accuracy so far has generally been higher than our training accuracy. That leads to two obvious questions Step2: ...and l...
Python Code: from theano.sandbox import cuda %matplotlib inline import utils; reload(utils) from utils import * from __future__ import division, print_function #path = os.path.join('input','sample') path = os.path.join('input','sample-10') #path = os.path.join('input') output_path = os.path.join('output','sample') mode...
12,433
Given the following text description, write Python code to implement the functionality described below step by step Description: NormMUSIC Demo The goal of this notebook is to demonstrate the effect of frequency normalization when MUSIC is applied on broadband signals The notebook is structured as follows Step1: <a i...
Python Code: # imports import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.signal import stft from random import uniform, sample from pyroomacoustics import doa, Room, ShoeBox Explanation: NormMUSIC Demo The goal of this notebook is to demonstrate the ef...
12,434
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview Contents Introduction to Python The Python Interpreter First Steps with Python Importing Libraries About the Data Arrays and their Attributes Getting Help More on Arrays Basic Data ...
Python Code: import glob filenames = glob.glob('*.csv') filenames Explanation: Overview Contents Introduction to Python The Python Interpreter First Steps with Python Importing Libraries About the Data Arrays and their Attributes Getting Help More on Arrays Basic Data Visualization Repeating Tasks with Loops Sequences ...
12,435
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Visualizing eclipse data Let us find some interesting data to generate elements from, before we consider how to customize them. Here is a dataset containing information...
Python Code: import pandas as pd import holoviews as hv hv.extension('bokeh', 'matplotlib') Explanation: <a href='http://www.holoviews.org'><img src="assets/hv+bk.png" alt="HV+BK logos" width="40%;" align="left"/></a> <div style="float:right;"><h2>02. Customizing Visual Appearance</h2></div> Section 01 focused on speci...
12,436
Given the following text description, write Python code to implement the functionality described below step by step Description: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review...
Python Code: import numpy as np Explanation: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review before we move on to Lecture 3. Remember, to use the numpy module, first it must be ...
12,437
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I'm using tensorflow 2.10.0.
Problem: import tensorflow as tf A = tf.constant([-0.5, -0.1, 0, 0.1, 0.5, 2], dtype=tf.float32) def g(A): return tf.math.reciprocal(A) result = g(A.__copy__())
12,438
Given the following text description, write Python code to implement the functionality described below step by step Description: Time Maps inspiration from https Step1: the example in the blog post is for a heat map of the amount of time in between events in a sequence. Step2: Our data file includes equal intervals,...
Python Code: import os; os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # for relative imports from utils.nab_data import NABData import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline data = NABData() data.summary().head() data.data.keys() data.plot('nyc_taxi') Explanation:...
12,439
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-mh', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: NCC Source ID: NORESM2-MH Topic: Atmos Sub-Topics: Dynamical Core, Radiation,...
12,440
Given the following text description, write Python code to implement the functionality described below step by step Description: Agents Step2: Conway's Game of Life A simple agent model is Conway's Game of Life, which is an example of Cellular automota. A two-dimensional square grid of cells are either "dead" or "ali...
Python Code: from IPython.core.display import HTML css_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css' HTML(url=css_file) Explanation: Agents: Lab 1 End of explanation %matplotlib inline import numpy from matplotlib import pyplot, animation from matplotlib im...
12,441
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook shows the how tallies can be combined (added, subtracted, multiplied, etc.) using the Python API in order to create derived tallies. Since no covariance information is obtained...
Python Code: import glob from IPython.display import Image import numpy as np import openmc Explanation: This notebook shows the how tallies can be combined (added, subtracted, multiplied, etc.) using the Python API in order to create derived tallies. Since no covariance information is obtained, it is assumed that tall...
12,442
Given the following text description, write Python code to implement the functionality described below step by step Description: Fantasy (first steps) This shows how to use Pandas to manipulate roster data. $\rightarrow$ Use [Control] + [Enter] to evaluate a cell. (Check the 'Help' menu above for more.) Step1: First ...
Python Code: ## # Setup -- import the modules we want and set up inline plotting # from __future__ import print_function import datetime import matplotlib import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # Bigger fonts and figures for the demo matplotlib.rcParams.update({ ...
12,443
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Oregon Curriculum Network <br /> Discovering Math with Python Crystal Ball Sequence The face-centered cubic (FCC) lattice is not always presented in this simplest form, ditto the cubi...
Python Code: from itertools import accumulate, islice def cubocta(): Classic Generator: Cuboctahedral / Icosahedral #s https://oeis.org/A005901 yield 1 # nuclear ball f = 1 while True: elem = 10 * f * f + 2 # f for frequency yield elem # <--- pause / resume here ...
12,444
Given the following text description, write Python code to implement the functionality described below step by step Description: Description Step1: Time to equilibrium Step2: sigma as a function of time & fragment length Step3: Graphing sigma as a function of time & fragment length Step4: Low GC Step5: High GC St...
Python Code: %load_ext rpy2.ipython %%R library(dplyr) library(tidyr) library(ggplot2) library(gridExtra) %%R GC2MW = function(x){ A = 313.2 T = 304.2 C = 289.2 G = 329.2 GC = G + C AT = A + T x = x / 100 x*GC + (1-x)*AT } GC2BD = function(GC){ # GC = percentage BD = GC / 100 ...
12,445
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', 'miroc', 'nicam16-7s', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: MIROC Source ID: NICAM16-7S Topic: Seaice Sub-Topics: Dynamics, Thermodyn...
12,446
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting the location of the North Sea Harding Oil and Gas field This example is taken out of my Ph.D. thesis. It shows the North Sea bathymetry and the topography of the surrounding countri...
Python Code: import shapefile import numpy as np from matplotlib import cm, rcParams import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap rcParams.update({'font.size': 16}) # Increase font-size Explanation: Plotting the location of the North Sea Harding Oil and Gas field This example is taken out of...
12,447
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading data from Excel Let's get some data. Download Sample Superstore Sales .xls file or my local copy and open it in Excel to see what it looks like. Data of interest that we want to proc...
Python Code: with open('data/SampleSuperstoreSales.xls', "rb") as f: txt = f.read() print(txt[0:100]) Explanation: Reading data from Excel Let's get some data. Download Sample Superstore Sales .xls file or my local copy and open it in Excel to see what it looks like. Data of interest that we want to process in ...
12,448
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: 勾配の計算 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: TensorFlow Quantum をインストールします。 Step3:...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
12,449
Given the following text description, write Python code to implement the functionality described below step by step Description: prelim_month - create Reliability_Names data 2016.12.04 - work log - prelim_month - create Reliability_Names original file name Step1: Setup - virtualenv jupyter kernel Back to Table of Con...
Python Code: import datetime print( "packages imported at " + str( datetime.datetime.now() ) ) Explanation: prelim_month - create Reliability_Names data 2016.12.04 - work log - prelim_month - create Reliability_Names original file name: 2016.12.04-work_log-prelim_month-create_Reliability_Names.ipynb This is the noteboo...
12,450
Given the following text description, write Python code to implement the functionality described below step by step Description: Resonances of Jupiter's moons, Io, Europa, and Ganymede Example provided by Deborah Lokhorst. In this example, the four Galilean moons of Jupiter are downloaded from HORIZONS and their orbit...
Python Code: import rebound import numpy as np %matplotlib inline import matplotlib.pyplot as plt sim = rebound.Simulation() sim.units = ('AU', 'days', 'Msun') # We can add Jupiter and four of its moons by name, since REBOUND is linked to the HORIZONS database. labels = ["Jupiter", "Io", "Europa","Ganymede","Callisto"]...
12,451
Given the following text description, write Python code to implement the functionality described below step by step Description: Annotation Consider a binary classification problem. We will fit a predictor and use it to assign a weight score to each node in each instance; this operation is referred to as "annotation"....
Python Code: pos = 'bursi.pos.gspan' neg = 'bursi.neg.gspan' from eden.converter.graph.gspan import gspan_to_eden iterable_pos = gspan_to_eden( pos ) iterable_neg = gspan_to_eden( neg ) #split train/test train_test_split=0.9 from eden.util import random_bipartition_iter iterable_pos_train, iterable_pos_test = random_bi...
12,452
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="#Booleans" data-toc-modified-id="Booleans-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Booleans</a></div><div class="lev2 toc-it...
Python Code: mybool_1 = True print(mybool_1) mybool_2 = False print(mybool_2) Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Booleans" data-toc-modified-id="Booleans-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Booleans</a></div><div class="lev2 toc-item"><a href="#Not-True-/-Not-False?" da...
12,453
Given the following text description, write Python code to implement the functionality described below step by step Description: Recently, I’ve become quite interested in fandoms. In particular, I’m curious about the process through which characters become the collective property of amateur writers. With multiple auth...
Python Code: #1. import from bs4 import BeautifulSoup import nltk with open ('stopwords_names.txt') as f: stopwords_string = f.read() names_tokenizer = nltk.word_tokenize(stopwords_string) names_tokens = [word.lower() for word in names_tokenizer if word[0].isalpha()] stop_words = nltk.corpus.stopwords.words("...
12,454
Given the following text description, write Python code to implement the functionality described below step by step Description: Domestic Load Research Programme Social Survey Exploration This notebook requires access to a data directory with DLR survey data saved as feather objects. The data files must be saved in /d...
Python Code: import processing.procore as pcore import features.socios as s tbls = pcore.loadTables() print("Stored Data Tables\n") for k in sorted(list(tbls.keys())): print(k) Explanation: Domestic Load Research Programme Social Survey Exploration This notebook requires access to a data directory with DLR survey d...
12,455
Given the following text description, write Python code to implement the functionality described below step by step Description: CMEMS Visualization Import packages For this visualization of a sample <i>index_latest.txt</i> dataset of the Copernicus Marine Environment Monitoring Service, we use the two packages Step1:...
Python Code: import numpy as np import folium Explanation: CMEMS Visualization Import packages For this visualization of a sample <i>index_latest.txt</i> dataset of the Copernicus Marine Environment Monitoring Service, we use the two packages: * <a href="https://github.com/python-visualization/folium">folium</a> for th...
12,456
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ...
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n...
12,457
Given the following text description, write Python code to implement the functionality described below step by step Description: Start with our simple example Let's start with $f(x) = x^2$ Step1: Let's assume we start at the top of the curve, at x = -4, and want to get down to x=0. Step2: In this algorithm, alpha is...
Python Code: # make our x array x = np.linspace(-4, 4, 801) # f(x) = x^2 def f(x): return x**2 # derivative of x^2 is 2x def f_prime(x): return 2*x # take a look at the curve plt.plot(x, f(x), c='black') sns.despine(); Explanation: Start with our simple example Let's start with $f(x) = x^2$: End of explanation ...
12,458
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: A Primer Finding Hyperparameters Grid Search? python param_grid = [ {'C' Step4: Setup Assumptions search space for each parameter is random uniform between 0 and 1 200 iterations f...
Python Code: def smbo(generator_fn, score_fn, evaluation_fn, num_dims, num_initial_points=10, num_iter=200, num_generated=10000): general sequential model based optimization to minimize the result of some presumably expensive function generator_fn: ...
12,459
Given the following text description, write Python code to implement the functionality described below step by step Description: Dual CRISPR Screen Analysis Step 1 Step1: Automated Set-Up Step2: Scaffold Trimming Functions Step3: Gzipped FASTQ Filenames Step4: FASTQ Gunzip Execution Step5: FASTQ Filenames Step6: ...
Python Code: g_num_processors = 3 g_fastqs_dir = '~/dual_crispr/test_data/test_set_1' g_trimmed_fastqs_dir = '~/dual_crispr/test_outputs/test_set_1' g_full_5p_r1 = 'TATATATCTTGTGGAAAGGACGAAACACCG' g_full_5p_r2 = 'CCTTATTTTAACTTGCTATTTCTAGCTCTAAAAC' g_full_3p_r1 = 'GTTTCAGAGCTATGCTGGAAACTGCATAGCAAGTTGAAATAAGGCTAGTCCGTTA...
12,460
Given the following text description, write Python code to implement the functionality described below step by step Description: What are the ten most common movie names of all time? Step1: Which three years of the 1930s saw the most films released? Step2: Plot the number of films that have been released each decade...
Python Code: titles['title'].value_counts()[:10] Explanation: What are the ten most common movie names of all time? End of explanation titles[(titles['year']<1940)&(titles['year']>=1930)]['year'].value_counts() Explanation: Which three years of the 1930s saw the most films released? End of explanation dec=((titles['yea...
12,461
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Exercises Recreate the plots below using the titanic dataframe. There are very few hints since most of the plots can be done with just one or two lines of code and a h...
Python Code: import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline sns.set_style('whitegrid') titanic = sns.load_dataset('titanic') titanic.head() titanic.shape Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Seaborn Exercises Time to practice your new se...
12,462
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework Part 1 Step1: that is a cue to use a particular command, in this case, plot. Run the cell to see documentation for that command. (To quickly close the Help window, press q.) For m...
Python Code: plt.plot? Explanation: Homework Part 1: Understanding Audio Features through Sonification There is no written component to be submitted for this part, Part 1. This section is intended to acquaint you with Python, the IPython notebook, and librosa. When you see a cell that looks like this: End of explanatio...
12,463
Given the following text description, write Python code to implement the functionality described below step by step Description: Feature engineering on NCAA data Domain knowledge is critical to getting the best out of data analysis and machine learning. In the case of basketball, Dean Oliver identified four factors th...
Python Code: %%bigquery df1 SELECT team_code, AVG(SAFE_DIVIDE(fgm + 0.5 * fgm3,fga)) AS offensive_shooting_efficiency, AVG(SAFE_DIVIDE(opp_fgm + 0.5 * opp_fgm3,opp_fga)) AS opponents_shooting_efficiency, AVG(win) AS win_rate, COUNT(win) AS num_games FROM lab_dev.team_box WHERE fga IS NOT NULL GROUP BY team_c...
12,464
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Exercise 3 Imports Step2: Contour plots of 2d wavefunctions The wavefunction of a 2d quantum well is Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib ...
Python Code: %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np Explanation: Matplotlib Exercise 3 Imports End of explanation def well2d(x, y, nx, ny, L=1): Compute the 2d quantum well wave function. return (2.0/L*np.sin((nx*np.pi*x)/L)*np.sin((ny*np.pi*y)/L)) ?np.zeros psi ...
12,465
Given the following text description, write Python code to implement the functionality described below step by step Description: Big Data Applications and Analytics Step1: Explore data frames to check headers Look at columns headers, variable information, type, etc. Step2: Explore data frames to check headers and da...
Python Code: import seaborn as sns import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv('~/project-data.csv') df.drop(df.columns[[0,1]], axis=1, inplace=True) df.shape Explanation: Big Data Applications and Analytics: Term Project Sean M. Shiverick Fall 2017 D...
12,466
Given the following text description, write Python code to implement the functionality described below step by step Description: Profiling Step2: timeit module Step3: cProfile Step4: Use pstats.Stats to parse and print cProfile output You can sort the records Step5: Networking Standard library provides some module...
Python Code: # EXERCISE: # Execute the following command: !python -m timeit '"-".join([str(n) for n in range(100)])' # Now execute the following: !python -m timeit '"-".join(map(str, range(100)))' # Now execute: !python -m timeit --setup 'func = lambda n: "-".join(map(str, range(n)))' 'func(100)' # And finally: !python...
12,467
Given the following text description, write Python code to implement the functionality described below step by step Description: CNN transfer learning - Keras+TensorFlow This is for CNN models transferred from pretrained model, using Keras based on TensorFlow. First, some preparation work. Step1: Read the MNIST data....
Python Code: from keras.layers import Conv2D, MaxPooling2D, Input, Dense, Flatten, Activation, add, Lambda from keras.layers.normalization import BatchNormalization from keras.layers.pooling import GlobalAveragePooling2D from keras.optimizers import RMSprop from keras.backend import tf as ktf from keras.models import M...
12,468
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-3', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: INPE Source ID: SANDBOX-3 Sub-Topics: Radiative Forcings. Properties: ...
12,469
Given the following text description, write Python code to implement the functionality described below step by step Description: Data pre-processing in python, using Pima Indians diabetes dataset from National Institute of Diabetes and Digestive and Kidney Diseases Citation Step1: 2.0 Split data into feature (input) ...
Python Code: import pandas as pd from pandas import read_csv pd.set_option('precision', 3) # set display precision to 3 significant figures filename = 'C:/Users/craigrshenton/Desktop/Dropbox/python/python_pro/machine_learning_mastery_with_python/machine_learning_mastery_with_python_code/chapter_07/pima-indians-diabetes...
12,470
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing logistic regression from scratch The goal of this notebook is to implement your own logistic regression classifier. You will Step1: Load review dataset For this assignment, we ...
Python Code: import graphlab Explanation: Implementing logistic regression from scratch The goal of this notebook is to implement your own logistic regression classifier. You will: Extract features from Amazon product reviews. Convert an SFrame into a NumPy array. Implement the link function for logistic regression. Wr...
12,471
Given the following text description, write Python code to implement the functionality described below step by step Description: <p><font size="6"><b>03 - Pandas Step1: <div class="alert alert-info" style="font-size Step2: Reversing this operation, is reset_index Step3: Selecting data based on the index <div class=...
Python Code: import pandas as pd # redefining the example dataframe data = {'country': ['Belgium', 'France', 'Germany', 'Netherlands', 'United Kingdom'], 'population': [11.3, 64.3, 81.3, 16.9, 64.9], 'area': [30510, 671308, 357050, 41526, 244820], 'capital': ['Brussels', 'Paris', 'Berlin', 'Amst...
12,472
Given the following text description, write Python code to implement the functionality described below step by step Description: High Schools dataset cleaning and exploration In this notebook we will clean and explore the 2017 High Schools dataset by the NYC Department of Education. Let's start by opening and examinin...
Python Code: import pandas as pd all_high_schools = pd.read_csv('data/DOE_High_School_Directory_2017.csv') all_high_schools.shape pd.set_option('display.max_columns', 453) all_high_schools.head(3) Explanation: High Schools dataset cleaning and exploration In this notebook we will clean and explore the 2017 High Schools...
12,473
Given the following text description, write Python code to implement the functionality described below step by step Description: Cônicas na forma polar A forma geral de uma cônica na forma polar é $$ r = \frac{de}{e\cos{\theta} + 1} $$ Vamos fazer dois exemplos Step1: A Hipérbole Note que na definição de uma hipérb...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np theta = np.arange(-1.7,1.7,0.1) r = lambda x: 2.0/(1+np.cos(x)) theta rho =r(theta) rho ## primeiro vou tentar um grafico polar ax=plt.subplot(111,projection='polar') ax.plot(theta,rho) ponto = lambda x: [r(x)*np.cos(x) , r(x)*np.sin(x)]...
12,474
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: 1. Data Manipulation and Cleaning 1.1 Data Ingestion We read the file 'data/vgsales.csv' using the pandas read_csv() function, and store it into the variable data. Ste...
Python Code: # IF YOU ARE RUNNING THIS NOTEBOOK VIA GOOGLE COLAB, PLEASE UNCOMMENT and RUN THIS CELL # from google.colab import drive # drive.mount('/content/drive') import matplotlib.pyplot as plt import numpy as np import pandas as pd import warnings warnings.simplefilter(action='ignore', category=FutureWarning) pd.s...
12,475
Given the following text description, write Python code to implement the functionality described below step by step Description: VARMAX models This is a notebook stub for VARMAX models. Full development will be done after impulse response functions are available. Step1: Model specification The VARMAX class in Statsmo...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt dta = sm.datasets.webuse('lutkepohl2', 'http://www.stata-press.com/data/r12/') dta.index = dta.qtr endog = dta.ix['1960-04-01':'1978-10-01', ['dln_inv', 'dln_inc', 'dln_consump']] Explanat...
12,476
Given the following text description, write Python code to implement the functionality described below step by step Description: List comprehensions Jedná se o zápis s Pythonu s jehož pomocí se dají jednoduše vytvářet seznamy. Step1: Tabulka s hracím polem Řešení 1 Step2: Řešení 2 Step3: Správné řešení Step4: Krát...
Python Code: [x for x in range(10)] [x**2 for x in range(10)] [x**2 for x in range(10) if x % 2 == 0] [(x, x**2) for x in range(10)] [[y for y in range(3)] for x in range(10)] Explanation: List comprehensions Jedná se o zápis s Pythonu s jehož pomocí se dají jednoduše vytvářet seznamy. End of explanation def vytvor_tab...
12,477
Given the following text description, write Python code to implement the functionality described below step by step Description: <p> <img src="http Step1: <center><img src="https Step2: past and present From https Step3: For a nicer description evaluate the following cell Step4: %%bash To start a Jupyter process t...
Python Code: __AUTHORS__ = {'am': ("Andrea Marino", "andrea.marino@unifi.it",), 'mn': ("Massimo Nocentini", "massimo.nocentini@unifi.it", "https://github.com/massimo-nocentini/",)} __KEYWORDS__ = ['Python', 'Jupyter', 'notebooks', 'keyn...
12,478
Given the following text description, write Python code to implement the functionality described below step by step Description: Demonstration for setting up an ODE system PyGOM — A Python Package for Simplifying Modelling with Systems of Ordinary Differential Equations https Step1: The following parameterization, ru...
Python Code: # import required packages from pygom import DeterministicOde, Transition, SimulateOde, TransitionType import os from sympy import symbols, init_printing import numpy as np import matplotlib.pyplot as mpl import sympy import itertools # Add graphvis path (N.B. set to your local circumstances) graphvis_pat...
12,479
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Data Step2: Detect Outliers EllipticEnvelope assumes the data is normally distributed and based on that assumption "draws" an ellipse around the data, classifying any o...
Python Code: # Load libraries import numpy as np from sklearn.covariance import EllipticEnvelope from sklearn.datasets import make_blobs Explanation: Title: Detecting Outliers Slug: detecting_outliers Summary: How to detect outliers for machine learning in Python. Date: 2016-09-06 12:00 Category: Machine Learning T...
12,480
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="#Raw-data-stats" data-toc-modified-id="Raw-data-stats-1"><span class="toc-ite...
Python Code: %matplotlib ipympl import seaborn as sns sns.set() sns.set_context('paper') sns.set_palette('colorblind') from planet4 import io, stats, markings, plotting, region_data from planet4.catalog_production import ReleaseManager fans = pd.read_csv("/Users/klay6683/Dropbox/data/planet4/p4_analysis/P4_catalog_v1.0...
12,481
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', 'cmcc', 'cmcc-esm2-sr5', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-ESM2-SR5 Topic: Aerosol Sub-Topics: Transport, E...
12,482
Given the following text description, write Python code to implement the functionality described below step by step Description: # Getting Started with gensim This section introduces the basic concepts and terms needed to understand and use gensim and provides a simple usage example. Core Concepts and Simple Example A...
Python Code: raw_corpus = ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", "Relati...
12,483
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Text Classification using TensorFlow/Keras on AI Platform </h1> This notebook illustrates Step1: Note Step2: We will look at the titles of articles and figure out whether the article ...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip install --user google-cloud-bigquery==1.25.0 Explanation: <h1> Text Classification using TensorFlow/Keras on AI Platform </h1> This notebook illustrates: <ol> <li> Creating datasets for AI Platform using BigQuery <li> Creating a text c...
12,484
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Efficient programming for parallel computing Timing and profiling Step11: Profiling your code Step12: Not covered Step13: Pointers versus copies Step14: Choosing the right contain...
Python Code: %%file timing.py some simple things to time import time def _list_comprehension(N): return [x*x for x in xrange(N)] def _for_append(N): L = [] for x in xrange(N): L.append(x*x) return L def _for_setitem(N): L = [None]*N i = 0 for x in xrange(N): L[i] = x*x ...
12,485
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Python and Natural Language Technologies Lecture 04, Week 04 February 28, 2018 List comprehension transform any iterable into a list in one line syntactic sugar example Step1...
Python Code: l = [] for i in range(10): l.append(2*i+1) l Explanation: Introduction to Python and Natural Language Technologies Lecture 04, Week 04 February 28, 2018 List comprehension transform any iterable into a list in one line syntactic sugar example: create a list of the first N odd numbers starting from 1 En...
12,486
Given the following text description, write Python code to implement the functionality described below step by step Description: Network analysis of the data. The goal of this notebook is to uncover several constructions inside the dataset which may help us to uncover fraud. With that, we can see whether we can create...
Python Code: %matplotlib inline import pandas as pd import numpy as np import networkx as nx import matplotlib.pyplot as plt Explanation: Network analysis of the data. The goal of this notebook is to uncover several constructions inside the dataset which may help us to uncover fraud. With that, we can see whether we ca...
12,487
Given the following text description, write Python code to implement the functionality described below step by step Description: Cropping2D [convolutional.Cropping2D.0] cropping ((1,1),(1,1)) on 3x5x4 input, data_format='channels_last' Step1: [convolutional.Cropping2D.1] cropping ((1,1),(1,1)) on 3x5x4 input, data_fo...
Python Code: data_in_shape = (3, 5, 4) L = Cropping2D(cropping=((1,1),(1, 1)), data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(250) data_in = 2 * np.random.random(d...
12,488
Given the following text description, write Python code to implement the functionality described below step by step Description: Some Basic Statistics This module will cover the calculation of some basic statistical parameters using numpy and scipy, starting with a 'by hand' or from textbook formulas and using built-i...
Python Code: from numpy.random import normal,rand import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats %matplotlib inline Explanation: Some Basic Statistics This module will cover the calculation of some basic statistical parameters using numpy and scipy, starting with a 'by hand' or from text...
12,489
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> 2. Creating a sampled dataset </h1> This notebook illustrates Step2: <h2> Create ML dataset by sampling using BigQuery </h2> <p> Let's sample the BigQuery data to create smaller datase...
Python Code: # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REG...
12,490
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction tutorial In this tutorial we will perform handwriting recognition by training a multilayer perceptron (MLP) on the MNIST handwritten digit database. The Task MNIST is a dataset ...
Python Code: from theano import tensor x = tensor.matrix('features') Explanation: Introduction tutorial In this tutorial we will perform handwriting recognition by training a multilayer perceptron (MLP) on the MNIST handwritten digit database. The Task MNIST is a dataset which consists of 70,000 handwritten digits. Ea...
12,491
Given the following text description, write Python code to implement the functionality described below step by step Description: Manual Commands Workbook This notebook is a workbook for testing hardware with manual FPE commands, and general empirical testing. It turns out that it's also a handy command reference. Sta...
Python Code: from tessfpe.dhu.fpe import FPE from tessfpe.dhu.unit_tests import check_house_keeping_voltages fpe1 = FPE(1, debug=False, preload=True, FPE_Wrapper_version='6.1.1') print fpe1.version fpe1.cmd_start_frames() fpe1.cmd_stop_frames() if check_house_keeping_voltages(fpe1): print "Wrapper load complete. In...
12,492
Given the following text description, write Python code to implement the functionality described below step by step Description: Named Entity Recognition using Transformers Author Step1: We will be using the transformer implementation from this fantastic example. Let's start by defining a TransformerBlock layer Step2...
Python Code: !pip3 install datasets !wget https://raw.githubusercontent.com/sighsmile/conlleval/master/conlleval.py import os import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from datasets import load_dataset from collections import Counter from conlleval impor...
12,493
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutor Magic in IPython This notebook demonstrates the %%tutor magic as used in IPython notebook. First, you'll need the following installed Step1: Finally, put a %%tutor at the top of any c...
Python Code: from metakernel import register_ipython_magics register_ipython_magics() Explanation: Tutor Magic in IPython This notebook demonstrates the %%tutor magic as used in IPython notebook. First, you'll need the following installed: IPython/Jupyter Metakernel Next, you'll need to use the magics in IPython: End o...
12,494
Given the following text description, write Python code to implement the functionality described below step by step Description: Supervised learning for classification 給一堆 $x$, 和他的分類,我們找出計算 x 的分類的方式 One hot encoding 如果我們有三類種類別, 我們可以來編碼這三個類別 * $(1,0,0)$ * $(0,1,0)$ * $(0,0,1)$ 問題 為什麼不直接用 1,2,3 這樣的編碼呢? Softmax Regressio...
Python Code: # Weight W = Matrix([1,2],[3,4], [5,6]) W # Bias b = Vector(1,0,-1) b # 輸入 x = Vector(2,-1) x Explanation: Supervised learning for classification 給一堆 $x$, 和他的分類,我們找出計算 x 的分類的方式 One hot encoding 如果我們有三類種類別, 我們可以來編碼這三個類別 * $(1,0,0)$ * $(0,1,0)$ * $(0,0,1)$ 問題 為什麼不直接用 1,2,3 這樣的編碼呢? Softmax Regression 的模型是這樣的 ...
12,495
Given the following text description, write Python code to implement the functionality described below step by step Description: Detección de anomalías La detección de anomalías (anomaly detection, AD) es una tarea de aprendizaje automático que consiste en detectar outliers o datos fuera de rango. An outlier is an obs...
Python Code: %matplotlib inline import warnings warnings.filterwarnings("ignore") import numpy as np import matplotlib import matplotlib.pyplot as plt Explanation: Detección de anomalías La detección de anomalías (anomaly detection, AD) es una tarea de aprendizaje automático que consiste en detectar outliers o datos fu...
12,496
Given the following text description, write Python code to implement the functionality described below step by step Description: The $k$-Nearest Neighbor Classification Algorithm Notebook version Step1: 1. The binary classification problem. In a binary classification problem, we are given an observation vector ${\bf ...
Python Code: # To visualize plots in the notebook %matplotlib inline # Import some libraries that will be necessary for working with data and displaying plots import csv # To read csv files import random import matplotlib.pyplot as plt import numpy as np from scipy import spatial from sklearn import neighbors, dat...
12,497
Given the following text description, write Python code to implement the functionality described below step by step Description: Converting on OSX Keychain into Text Notes The purpose of this notebook is to export the secured notes from an Apple keychain into separate files. It is pretty rough, but generally this only...
Python Code: path = '/Volumes/---/keychains' #!ls -l $path Explanation: Converting on OSX Keychain into Text Notes The purpose of this notebook is to export the secured notes from an Apple keychain into separate files. It is pretty rough, but generally this only needs to be done once (at least for me this was the case...
12,498
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src='https Step1: Locally and Remote Run locally Connect to the cloud (e.g AWS) Connect to supercomputer (e.g. XSEDE Resource) Add compute power Step2: Plot a Histogram of x Step3: N...
Python Code: 2+4 print("hello") a=2 print("Hello world!") Explanation: <img src='https://raw.githubusercontent.com/scientific-visualization-2016/ClassMaterials/master/Images/rc_logo.png' style="height:75px"> Data Analysis and Visualization with the IPython Notebook <img src='https://raw.githubusercontent.com/scientific...
12,499
Given the following text description, write Python code to implement the functionality described below step by step Description: Parameter Estimation of RIG Roll Experiments Setup and descriptions Without ACM model Turn on wind tunnel Only 1DoF for RIG roll movement Use small-amplitude aileron command of CMP as inputs...
Python Code: %run matt_startup %run -i matt_utils button_qtconsole() #import other needed modules in all used engines #with dview.sync_imports(): # import os Explanation: Parameter Estimation of RIG Roll Experiments Setup and descriptions Without ACM model Turn on wind tunnel Only 1DoF for RIG roll movement Use small...