Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
2,800
Given the following text description, write Python code to implement the functionality described below step by step Description: STELLAB and OMEGA (Stellar yields + Faint Supernovae) Documented by Jacob Brazier. Note This notebooks require an experimental yields table, which is not part of NuPyCEE. See Côté et al. (20...
Python Code: #import modules #sygma and omega share the same chem_evol class from NuPyCEE import chem_evol from NuPyCEE import sygma from NuPyCEE import omega from NuPyCEE import stellab #import Python plotting packages import matplotlib import matplotlib.pyplot as plt #Define Stellab stellab = stellab.stellab() %matpl...
2,801
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Step1: Create Folder Structure Step7: Things to keep in mind (Troubleshooting) Choose always verbosity=2 when training. Otherwise the notebook will crash. Monitor the RAM whi...
Python Code: %matplotlib inline import os import sys import math import zipfile import glob import numpy as np import utils; reload(utils) from utils import * from keras.models import Sequential from keras.layers import Lambda, Dense from keras import backend as K from matplotlib import pyplot as plt Explanation: Deep ...
2,802
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: Note Step2: Include the input file that contains all input parameters needed for all components. This file can either be a python dictionary or a text file that can be...
Python Code: from __future__ import print_function %matplotlib inline import time import numpy as np from landlab import RasterModelGrid as rmg from landlab import load_params from Ecohyd_functions_flat import ( Initialize_, Empty_arrays, Create_PET_lookup, Save_, Plot_, ) Explanation: <a href="http...
2,803
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 2 Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset. The goal of this assignm...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range Explanation: Deep Learning Assignment 2 Previousl...
2,804
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute source power spectral density (PSD) in a label Returns an STC file containing the PSD (in dB) of each of the sources within a label. Step1: Set parameters Step2: View PSD of source...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, compute_source_psd print(__doc__) Explanation: Compute source power spectra...
2,805
Given the following text description, write Python code to implement the functionality described below step by step Description: Sale price distribution First step is to look at the target sale price for the training data set, i.e. the column we're trying to predict. Step1: The sale price is in hte hundreds of thousa...
Python Code: target = pd.read_csv('../data/train_target.csv') target.describe() Explanation: Sale price distribution First step is to look at the target sale price for the training data set, i.e. the column we're trying to predict. End of explanation target = target / 1000 sns.distplot(target); plt.title('SalePrice') i...
2,806
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Optimization Bayesian optimization is a powerful strategy for minimizing (or maximizing) objective functions that are costly to evaluate. It is an important component of automated ...
Python Code: import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import torch import torch.autograd as autograd import torch.optim as optim from torch.distributions import constraints, transform_to import pyro import pyro.contrib.gp as gp assert pyro.__version__.startswith('1.7.0') pyro.set_rng_seed(...
2,807
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to pybids pybids is a tool to query, summarize and manipulate data using the BIDS standard. In this tutorial we will use a pybids test dataset to illustrate some of the functio...
Python Code: from bids import BIDSLayout from bids.tests import get_test_data_path import os Explanation: Introduction to pybids pybids is a tool to query, summarize and manipulate data using the BIDS standard. In this tutorial we will use a pybids test dataset to illustrate some of the functionality of pybids.layout ...
2,808
Given the following text description, write Python code to implement the functionality described below step by step Description: Colorization AutoEncoder PyTorch Demo using CIFAR10 In this demo, we build a simple colorization autoencoder using PyTorch. Step1: CNN Encoder using PyTorch We use 3 CNN layers to encode th...
Python Code: import torch import torchvision import wandb import time from torch import nn from einops import rearrange, reduce from argparse import ArgumentParser from pytorch_lightning import LightningModule, Trainer, Callback from pytorch_lightning.loggers import WandbLogger from torch.optim import Adam from torch.o...
2,809
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting sentiment from product reviews The goal of this first notebook is to explore logistic regression and feature engineering with existing GraphLab functions. In this notebook you wil...
Python Code: from __future__ import division import graphlab import math import string import numpy Explanation: Predicting sentiment from product reviews The goal of this first notebook is to explore logistic regression and feature engineering with existing GraphLab functions. In this notebook you will use product rev...
2,810
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step3: Action Recognition with an Inflated 3D CNN <table class="tfo-notebook-butto...
Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
2,811
Given the following text description, write Python code to implement the functionality described below step by step Description: The following script extracts the (more) helpful reviews from the swiss reviews and saves them locally. From the extracted reviews it also saves a list with their asin identifiers. The list ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np import yaml Explanation: The following script extracts the (more) helpful reviews from the swiss reviews and saves them locally. From the extracted reviews it also saves a list with their asin identifiers. The list of...
2,812
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="#First-Foray-Into-Discrete/Fast-Fourier-Transformation" data-toc-modified-id=...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(css_style='custom2.css', plot_style=False) os.chdir(path) # 1. magic for in...
2,813
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: SLD gradients For the moment, BornAgain does not support input of SLD profiles. However, one can approximate the smooth SLD profile by a large number of layers. See the example script...
Python Code: # %load density_grad.py import numpy as np import bornagain as ba from bornagain import deg, angstrom, nm # define used SLDs sld_D2O = 6.34e-06 sld_polymer = 4.0e-06 sld_Si = 2.07e-06 h = 100.0*nm # thickness of the non-uniform polymer layer nslices = 100 # number of slices to slice the polymer layer de...
2,814
Given the following text description, write Python code to implement the functionality described below step by step Description: How to Load CSV and Numpy File Types in TensorFlow 2.0 Learning Objectives Load a CSV file into a tf.data.Dataset. Load Numpy data Introduction In this lab, you load CSV data from a file in...
Python Code: import functools import numpy as np import tensorflow as tf print("TensorFlow version: ", tf.version.VERSION) TRAIN_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/train.csv" TEST_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/eval.csv" train_file_path = tf.keras.utils.get_fi...
2,815
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...
2,816
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 sys print(sys.version) 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 f...
2,817
Given the following text description, write Python code to implement the functionality described below step by step Description: Style Transfer Our Changes Step1: Imports Step2: This was developed using Python 3.5.2 (Anaconda) and TensorFlow version Step3: The VGG-16 model is downloaded from the internet. This is t...
Python Code: from IPython.display import Image, display Image('images/15_style_transfer_flowchart.png') Explanation: Style Transfer Our Changes: We are just saving the mixed image every 10 iterations. End of explanation %matplotlib inline import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import...
2,818
Given the following text description, write Python code to implement the functionality described below step by step Description: Network queries veneer-py supports a number topological queries on the Source node-link network and including identifying outlets, upstream and downstream nodes, links and catchments. These ...
Python Code: import veneer %matplotlib inline v = veneer.Veneer() Explanation: Network queries veneer-py supports a number topological queries on the Source node-link network and including identifying outlets, upstream and downstream nodes, links and catchments. These queries operate on the network object returned by v...
2,819
Given the following text description, write Python code to implement the functionality described below step by step Description: Kaggle Step1: Data exploration First we load and explore the dataset a little. Step2: There are strong differences in the frequencies in which the different categories of crime occur. Lare...
Python Code: # imports import math import datetime import matplotlib import matplotlib.pyplot as plt import osmnx as ox import pandas as pd import numpy as np import pprint import requests import gmaps import seaborn as sns import os import numpy as np from sklearn.model_selection import train_test_split from sklearn.m...
2,820
Given the following text description, write Python code to implement the functionality described below step by step Description: Wave Packets Step2: A particle with total energy $E$ in a region of constant potential $V_0$ has a wave number $$ k = \pm \frac{2m}{\hbar^2}(E - V_0) $$ and dispersion relation $$ \omega(k)...
Python Code: %pylab inline import matplotlib.animation from IPython.display import HTML Explanation: Wave Packets End of explanation def solve(k0=10., sigmax=0.25, V0=0., mass=1., tmax=0.25, nwave=15, nx=500, nt=10): Solve for the evolution of a 1D Gaussian wave packet. Parameters ---------- k...
2,821
Given the following text description, write Python code to implement the functionality described below step by step Description: Plot sensor denoising using oversampled temporal projection This demonstrates denoising using the OTP algorithm Step1: Plot the phantom data, lowpassed to get rid of high-frequency artifac...
Python Code: # Author: Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause import os.path as op import mne import numpy as np from mne import find_events, fit_dipole from mne.datasets.brainstorm import bst_phantom_elekta from mne.io import read_raw_fif print(__doc__) Explanation: Plot sensor denoising using...
2,822
Given the following text description, write Python code to implement the functionality described below step by step Description: Convert training sessions to labeled examples, each example will have a seq_size sequence size, we will include three features per data point, the timestamp, the x position and the y positio...
Python Code: df_train = sessions_to_dataframe(training_sessions) df_val = sessions_to_dataframe(validation_sessions) df_train.head() df_train = preprocess_data(df_train) df_val = preprocess_data(df_val) #### SPECIAL CASE ##### # There isnt any XButton data in the validation set so we better drop this column for the tra...
2,823
Given the following text description, write Python code to implement the functionality described below step by step Description: Saving and Loading Models In this bite-sized notebook, we'll go over how to save and load models. In general, the process is the same as for any PyTorch module. Step1: Saving a Simple Model...
Python Code: import math import torch import gpytorch from matplotlib import pyplot as plt Explanation: Saving and Loading Models In this bite-sized notebook, we'll go over how to save and load models. In general, the process is the same as for any PyTorch module. End of explanation train_x = torch.linspace(0, 1, 100) ...
2,824
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 2 assignment This assignment will get you familiar with the basic elements of Python by programming a simple card game. We will create a custom class to represent each player in the game...
Python Code: import random Explanation: Lab 2 assignment This assignment will get you familiar with the basic elements of Python by programming a simple card game. We will create a custom class to represent each player in the game, which will store information about their current pot, as well as a series of methods def...
2,825
Given the following text description, write Python code to implement the functionality described below step by step Description: Correção de exercício Cap 03 - Exercício 14 Step1: Método dos Mínimos Quadrados Para achar a função de calibração \( D = N\sum{Y^{2}} - (\sum{Y})^2 \) \( c_{0} = (\sum{X}\sum{Y^2}\,-\,\sum{...
Python Code: %matplotlib notebook import numpy as np import matplotlib from matplotlib import pyplot as plt import pandas as pd df=pd.read_table('./data/temperatura.txt',sep='\s',header=0, engine='python') df.head() fig, ax1 = plt.subplots() ax1.plot(df.Xi, 'b') ax1.plot(df.Y1, 'y') #ax1.set_xlabel('time (s)') # Make t...
2,826
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementation of the Thornthwaite-Mather procedure to map groundwater recharge Author Step1: Other libraries Import other libraries/modules used in this notebook. pandas Step2: Some input...
Python Code: import ee # Trigger the authentication flow. ee.Authenticate() # Initialize the library. ee.Initialize() Explanation: Implementation of the Thornthwaite-Mather procedure to map groundwater recharge Author: guiattard Groundwater recharge represents the amount of water coming from precipitation reaching the ...
2,827
Given the following text description, write Python code to implement the functionality described below step by step Description: Guided Project 1 Learning Objectives Step1: Step 1. Environment setup tfx and kfp tools setup Step2: You may need to restart the kernel at this point. skaffold tool setup Step3: Modify th...
Python Code: import os Explanation: Guided Project 1 Learning Objectives: Learn how to generate a standard TFX template pipeline using tfx template Learn how to modify and run a templated TFX pipeline Note: This guided project is adapted from Create a TFX pipeline using templates). End of explanation %%bash TFX_PKG="t...
2,828
Given the following text description, write Python code to implement the functionality described below step by step Description: <b>This notebook divide a single mailing list corpus into threads.</b> What it does Step1: First, collect data from a public email archive. Step2: Let's check the number of threads in thi...
Python Code: %matplotlib inline from bigbang.archive import Archive from bigbang.archive import load as load_archive from bigbang.thread import Thread from bigbang.thread import Node from bigbang.utils import remove_quoted import matplotlib.pyplot as plt import datetime import csv from collections import defaultdict Ex...
2,829
Given the following text description, write Python code to implement the functionality described below step by step Description: Processing a single Spectrum Specdal provides readers which loads [.asd, .sig, .sed] files into a common Spectrum object. Step1: The print output shows the four components of the Spectrum o...
Python Code: s = specdal.Spectrum(filepath="/home/young/data/specdal/aidan_data/SVC/ACPA_F_B_SU_20160617_003.sig") print(s) Explanation: Processing a single Spectrum Specdal provides readers which loads [.asd, .sig, .sed] files into a common Spectrum object. End of explanation print(type(s.measurement)) print(s.measure...
2,830
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 5 Step1: Load in house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2: Create new features As in Week 2, ...
Python Code: import sys sys.path.append('C:\Anaconda2\envs\dato-env\Lib\site-packages') import graphlab Explanation: Regression Week 5: Feature Selection and LASSO (Interpretation) In this notebook, you will use LASSO to select features, building on a pre-implemented solver for LASSO (using GraphLab Create, though you ...
2,831
Given the following text description, write Python code to implement the functionality described below step by step Description: Inference of the dispersion of a Gaussian with Gaussian data errors Suppose we have data draw from a delta function with Gaussian uncertainties (all equal). How well do we limit the dispersi...
Python Code: ndata= 24 data= numpy.random.normal(size=ndata) Explanation: Inference of the dispersion of a Gaussian with Gaussian data errors Suppose we have data draw from a delta function with Gaussian uncertainties (all equal). How well do we limit the dispersion? Sample data: End of explanation def loglike(sigma,da...
2,832
Given the following text description, write Python code to implement the functionality described below step by step Description: Limpieza de Estructura Organica del PEN Se utilizan data-cleaner y pandas para codificar la limpieza de los datos de un archivo CSV. Primero se realiza una exploración de la tabla aplicando ...
Python Code: from __future__ import unicode_literals from __future__ import print_function from data_cleaner import DataCleaner import pandas as pd input_path = "estructura-organica-raw.csv" output_path = "estructura-organica-clean.csv" dc = DataCleaner(input_path) Explanation: Limpieza de Estructura Organica del PEN S...
2,833
Given the following text description, write Python code to implement the functionality described below step by step Description: Note Step1: Before we continue, note that we'll be using your Qwiklabs project id a lot in this notebook. For convenience, set it as an environment variable using the command below Step2: ...
Python Code: import datetime import pickle import os import pandas as pd import xgboost as xgb import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.pipeline import FeatureUnion, make_pipeline from sklearn.utils import shuffle from sklearn.base import clone from sklearn.model_selection import...
2,834
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Analysis Tools Assignment Step1: Data management Step2: First, the distribution of both the use of cannabis and the ethnicity will be shown. Step3: Variance analysis Now that the uni...
Python Code: # Magic command to insert the graph directly in the notebook %matplotlib inline # Load a useful Python libraries for handling data import pandas as pd import numpy as np import statsmodels.formula.api as smf import seaborn as sns import scipy.stats as stats import matplotlib.pyplot as plt from IPython.disp...
2,835
Given the following text description, write Python code to implement the functionality described below step by step Description: FloPy Using FloPy to simplify the use of the MT3DMS SSM package A multi-component transport demonstration Step1: First, we will create a simple model structure Step2: Create the MODFLOW pa...
Python Code: import os import numpy as np from flopy import modflow, mt3d, seawat Explanation: FloPy Using FloPy to simplify the use of the MT3DMS SSM package A multi-component transport demonstration End of explanation nlay, nrow, ncol = 10, 10, 10 perlen = np.zeros((10), dtype=np.float) + 10 nper = len(perlen) ibound...
2,836
Given the following text description, write Python code to implement the functionality described below step by step Description: Web Scraping in Python Source In this appendix lecture we'll go over how to scrape information from the web using Python. We'll go to a website, decide what information we want, see where a...
Python Code: from bs4 import BeautifulSoup import requests import pandas as pd from pandas import Series,DataFrame Explanation: Web Scraping in Python Source In this appendix lecture we'll go over how to scrape information from the web using Python. We'll go to a website, decide what information we want, see where and...
2,837
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 4 - Current induced domain wall motion In this tutorial we show how spin transfer torque (STT) can be included in micromagnetic simulations. To illustrate that, we will try to move ...
Python Code: # Definition of parameters L = 500e-9 # sample length (m) w = 20e-9 # sample width (m) d = 2.5e-9 # discretisation cell size (m) Ms = 5.8e5 # saturation magnetisation (A/m) A = 15e-12 # exchange energy constant (J/) D = 3e-3 # Dzyaloshinkii-Moriya energy constant (J/m**2) K = 0.5e6 # uniaxial anisot...
2,838
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial of how to use scikit-criteria AHP extension module Author Step1: In other hand AHP uses as an in put 2 totally different $$ AHP(CvC, AvA) $$ Where Step2: The function ahp.t (from...
Python Code: from skcriteria import Data, MIN, MAX mtx = [ [1, 2, 3], # alternative 1 [4, 5, 6], # alternative 2 ] mtx # let's says the first two alternatives are # for maximization and the last one for minimization criteria = [MAX, MAX, MIN] criteria # et’s asume we know in our case, that the importance of ...
2,839
Given the following text description, write Python code to implement the functionality described below step by step Description: Overfitting demo Create a dataset based on a true sinusoidal relationship Let's look at a synthetic dataset consisting of 30 points drawn from the sinusoid $y = \sin(4x)$ Step1: Create rand...
Python Code: import graphlab import math import random import numpy from matplotlib import pyplot as plt %matplotlib inline Explanation: Overfitting demo Create a dataset based on a true sinusoidal relationship Let's look at a synthetic dataset consisting of 30 points drawn from the sinusoid $y = \sin(4x)$: End of expl...
2,840
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Neural Networks With BatchFlow Now it's time to talk about convolutional neural networks and in this notebook you will find out how to do Step1: You don't need to implement a ...
Python Code: import sys import warnings warnings.filterwarnings("ignore") import numpy as np import PIL from matplotlib import pyplot as plt from tqdm import tqdm %matplotlib inline # the following line is not required if BatchFlow is installed as a python package. sys.path.append('../..') from batchflow import D, B, V...
2,841
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Preprocessing for Machine Learning Learning Objectives * Understand the different approaches for data preprocessing in developing ML models * Use Dataflow to perform data preprocessing ...
Python Code: #Ensure that we have the correct version of Apache Beam installed !pip freeze | grep apache-beam || sudo pip install apache-beam[gcp]==2.12.0 import tensorflow as tf import apache_beam as beam import shutil import os print(tf.__version__) Explanation: Data Preprocessing for Machine Learning Learning Object...
2,842
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing PDF function in dmdd over time for SI and Anapole On the colormaps near Q = 0, the pdf function seems to be predicting the wrong number of events for the SI and anapole models. SI sh...
Python Code: pdf_list = [] times = np.linspace(0, 365, 366) #365 days to test #test all days at same energies, where energy = 3 for i,time in enumerate(times): value = dmdd.PDF(Q=[5.], time=time, element = 'xenon', mass = 50., sigma_si= 75.5, sigma_anapole = 0., ...
2,843
Given the following text description, write Python code to implement the functionality described below step by step Description: Spectrometer accuracy assesment using validation tarps Background In this lesson we will be examing the accuracy of the Neon Imaging Spectrometer (NIS) against targets with known reflectance...
Python Code: import h5py import csv import numpy as np import os import gdal import matplotlib.pyplot as plt import sys from math import floor import time import warnings warnings.filterwarnings('ignore') %matplotlib inline Explanation: Spectrometer accuracy assesment using validation tarps Background In this lesson we...
2,844
Given the following text description, write Python code to implement the functionality described below step by step Description: Units and unit conversions are BIG in engineering. Engineers solve the world's problems in teams. Any problem solved has to have a context. How heavy can a rocket be and still make it off th...
Python Code: import platform print('Operating System: ' + platform.system() + platform.release()) print('Python Version: '+ platform.python_version()) Explanation: Units and unit conversions are BIG in engineering. Engineers solve the world's problems in teams. Any problem solved has to have a context. How heavy can a ...
2,845
Given the following text description, write Python code to implement the functionality described below step by step Description: Example Step4: The individual data instances come in chunks seperated by blank lines. Each chunk consists of a few starting comments, and then lines of tab-seperated fields. The fields we a...
Python Code: !wget https://raw.githubusercontent.com/UniversalDependencies/UD_English/master/en-ud-dev.conllu !wget https://raw.githubusercontent.com/UniversalDependencies/UD_English/master/en-ud-test.conllu !wget https://raw.githubusercontent.com/UniversalDependencies/UD_English/master/en-ud-train.conllu Explanation: ...
2,846
Given the following text description, write Python code to implement the functionality described below step by step Description: Pick an example to test if load.cc works Step1: Inspect the protobuf containing the model's architecture and logic
Python Code: # -- inputs X_test[0] # -- predicted output (using Keras) yhat[0] Explanation: Pick an example to test if load.cc works End of explanation from tensorflow.core.framework import graph_pb2 # -- read in the graph f = open("models/graph.pb", "rb") graph_def = graph_pb2.GraphDef() graph_def.ParseFromString(f.re...
2,847
Given the following text description, write Python code to implement the functionality described below step by step Description: Demonstration of SMPS Calculations The SMPS calculations require two main packages from atmPy - smps and dma. dma contains the DMA class and its children. The children of DMA simply contai...
Python Code: from atmPy.instruments.DMA import smps from atmPy.instruments.DMA import dma from matplotlib import colors import matplotlib.pyplot as plt from numpy import meshgrid import numpy as np import pandas as pd from matplotlib.dates import date2num from matplotlib import dates from atmPy import sizedistribution ...
2,848
Given the following text description, write Python code to implement the functionality described below step by step Description: ==================================================================== Decoding in sensor space data using the Common Spatial Pattern (CSP) ====================================================...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Romain Trachel <romain.trachel@inria.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample print(__doc__) data_path = sample.data_pat...
2,849
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook a simple Q learner will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantity (in fact it determines t...
Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error from multiprocessing import Pool %matplotlib inline %pylab inline ...
2,850
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started Before starting here, all the instructions on the installation page should be completed! Here you will learn how to Step1: Make sure that your environment path is set to ma...
Python Code: import warnings warnings.filterwarnings('ignore') import pandexo.engine.justdoit as jdi # THIS IS THE HOLY GRAIL OF PANDEXO import numpy as np import os #pip install pandexo.engine --upgrade Explanation: Getting Started Before starting here, all the instructions on the installation page should be completed...
2,851
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading data Simple stuff. We're loading in a CSV here, and we'll run the describe function over it to get the lay of the land. Step1: In journalism, we're primarily concerned with using da...
Python Code: df = pd.read_csv('data/ontime_reports_may_2015_ny.csv') df.describe() Explanation: Loading data Simple stuff. We're loading in a CSV here, and we'll run the describe function over it to get the lay of the land. End of explanation df.sort('ARR_DELAY', ascending=False).head(1) Explanation: In journalism, we'...
2,852
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Data augmentation <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Download a dataset This t...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
2,853
Given the following text description, write Python code to implement the functionality described below step by step Description: Extracting the time series of activations in a label We first apply a dSPM inverse operator to get signed activations in a label (with positive and negative values) and we then compare diffe...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects import mne from mne.datasets import sample from mne.minimum_norm import read_inverse_operato...
2,854
Given the following text description, write Python code to implement the functionality described below step by step Description: Input pipeline Zastosowano tu następującą strategie Step1: test queue Step2: Testing Możemy wykorzystać feed_dict by wykonać graf operacji na ndanych testowych.
Python Code: def read_data(filename_queue): reader = tf.TFRecordReader() _, se = reader.read(filename_queue) f = tf.parse_single_example(se,features={'image/encoded':tf.FixedLenFeature([],tf.string), 'image/class/label':tf.FixedLenFeature([],tf.int64), ...
2,855
Given the following text description, write Python code to implement the functionality described below step by step Description: Hypsometric analysis of Mountain Ranges Carlos H. Grohmann Institute of Energy and Environment University of São Paulo, São Paulo, Brazil guano -at- usp -dot- br Hypsometry Hypsometric anal...
Python Code: import sys, os import numpy as np import math as math import numpy.ma as ma from matplotlib import cm from matplotlib.colors import LightSource from scipy import ndimage import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap %matplotlib inline # import osgeo libs after basemap, so it # w...
2,856
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Model Evaluation & Validation Project Step1: Data Exploration In this first section of this project, you will make a cursory investigation about the Bos...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd #from sklearn.cross_validation import ShuffleSplit # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the Boston housing dataset data = pd.re...
2,857
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', 'cccma', 'sandbox-3', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: CCCMA Source ID: SANDBOX-3 Topic: Seaice Sub-Topics: Dynamics, Thermodynam...
2,858
Given the following text description, write Python code to implement the functionality described below step by step Description: 2. kolokvij 2011/2012, rešitve 1. naloga Poišči največjo in najmanjšo vrednost, ki jo zavzame funkcija $$f(x) = x^4 + 2x^3 - 2x^2 + 1.$$ Step1: Kandadati za ekstreme so stacionarne točke i...
Python Code: f = lambda x: x**4 + 2*x**3 - 2*x**2 + 1 x = sympy.Symbol('x', real=True) Explanation: 2. kolokvij 2011/2012, rešitve 1. naloga Poišči največjo in najmanjšo vrednost, ki jo zavzame funkcija $$f(x) = x^4 + 2x^3 - 2x^2 + 1.$$ End of explanation eq = Eq(f(x).diff(), 0) eq critical_points = sympy.solve(eq) cr...
2,859
Given the following text description, write Python code to implement the functionality described below step by step Description: Viscoelastic wave equation implementation on a staggered grid This is a first attempt at implementing the viscoelastic wave equation as described in [1]. See also the FDELMODC implementation...
Python Code: # Required imports: import numpy as np import sympy as sp from devito import * from examples.seismic.source import RickerSource, TimeAxis from examples.seismic import ModelViscoelastic, plot_image Explanation: Viscoelastic wave equation implementation on a staggered grid This is a first attempt at implemen...
2,860
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples and Exercises from Think Stats, 2nd Edition http Step1: Scatter plots I'll start with the data from the BRFSS again. Step2: The following function selects a random subset of a Dat...
Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import brfss import thinkstats2 import thinkplot Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thinkstats2.com Copyright 2016 Allen B. Downey MIT License: https://opensource.org/licenses/MIT End...
2,861
Given the following text description, write Python code to implement the functionality described below step by step Description: Random Graphs Step1: Introduction A graph $G=(V,E)$ is a collection of vertices $V$ and edges $E$ between the vertices in $V$. Graphs often model interactions such as social networks, a net...
Python Code: import networkx as nx import numpy as np import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') #NetworkX has some deprecation warnings Explanation: Random Graphs End of explanation params = [(10,0.1),(10,.5),(10,0.9),(20,0.1),(20,.5),(20,0.9)] plt.figure(figsize=(15,10)) idx = 1...
2,862
Given the following text description, write Python code to implement the functionality described below step by step Description: Python pandas Q&A video series by Data School YouTube playlist and GitHub repository Table of contents <a href="#1.-What-is-pandas%3F-%28video%29">What is pandas?</a> <a href="#2.-How-do-I-r...
Python Code: # conventional way to import pandas import pandas as pd # get Pansda's vesrion # print ('Pandas version', pd.__version__) Explanation: Python pandas Q&A video series by Data School YouTube playlist and GitHub repository Table of contents <a href="#1.-What-is-pandas%3F-%28video%29">What is pandas?</a> <a hr...
2,863
Given the following text description, write Python code to implement the functionality described below step by step Description: Two implementations of heterodyne detection Step1: Introduction Homodyne and hetrodyne detection are techniques for measuring the quadratures of a field using photocounters. Homodyne detect...
Python Code: %matplotlib inline import numpy as np import scipy as sp import matplotlib.pyplot as plt from qutip import * Explanation: Two implementations of heterodyne detection: direct heterodyne and as two homodyne measurements Copyright (C) 2011 and later, Paul D. Nation & Robert J. Johansson End of explanation N =...
2,864
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize Epochs data Step1: This tutorial focuses on visualization of epoched data. All of the functions introduced here are basically high level matplotlib functions with built in intelli...
Python Code: import os.path as op import mne data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample') raw = mne.io.read_raw_fif( op.join(data_path, 'sample_audvis_raw.fif'), preload=True) raw.load_data().filter(None, 9, fir_design='firwin') raw.set_eeg_reference('average', projection=True) # set EEG a...
2,865
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: Generate music with an RNN <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Download the Mae...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
2,866
Given the following text description, write Python code to implement the functionality described below step by step Description: xbatch and batch Step1: peek Step2: bracket Step3: <pre> 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 0----5----0----5----0----5----0----5--...
Python Code: for x in utils.xbatch(2, range(10)): print(x) for x in utils.xbatch(3, ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']): print(x) for x in utils.xbatch(3, ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug'...
2,867
Given the following text description, write Python code to implement the functionality described below step by step Description: Rozwiązywanie stochastycznych równań różniczkowych z CUDA Równania stochastyczne są niezwykle pożytecznym narzędziem w modelowaniu zarówno procesów fizycznych, biolgicznych czy chemicznych a...
Python Code: print('%(language)04d a nawiasy {} ' % {"language": 1234, "number": 2}) Explanation: Rozwiązywanie stochastycznych równań różniczkowych z CUDA Równania stochastyczne są niezwykle pożytecznym narzędziem w modelowaniu zarówno procesów fizycznych, biolgicznych czy chemicznych a nawet ekonomicznych (wycena ins...
2,868
Given the following text description, write Python code to implement the functionality described below step by step Description: Does Trivers-Willard apply to people? This notebook contains a "one-day paper", my attempt to pose a research question, answer it, and publish the results in one work day. Copyright 2016 All...
Python Code: from __future__ import print_function, division import thinkstats2 import thinkplot import pandas as pd import numpy as np import statsmodels.formula.api as smf %matplotlib inline Explanation: Does Trivers-Willard apply to people? This notebook contains a "one-day paper", my attempt to pose a research ques...
2,869
Given the following text description, write Python code to implement the functionality described below step by step Description: Diagnostics for approximate likelihood ratios Kyle Cranmer, Juan Pavez, Gilles Louppe, March 2016. This is an extension of the example in Parameterized inference from multidimensional data. ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import theano from scipy.stats import chi2 from itertools import product np.random.seed(314) Explanation: Diagnostics for approximate likelihood ratios Kyle Cranmer, Juan Pavez, Gilles Louppe, March 2016. This is an extension of the exam...
2,870
Given the following text description, write Python code to implement the functionality described below step by step Description: Plots the NINO Sea Surface Temperature indices (data from the Bureau of Meteorology) and the real-time Southern Oscillation Index (SOI) from LongPaddock Nicolas Fauchereau Step1: set up pro...
Python Code: %matplotlib inline import os, sys import pandas as pd from datetime import datetime, timedelta from cStringIO import StringIO import requests import matplotlib as mpl from matplotlib import pyplot as plt from IPython.display import Image Explanation: Plots the NINO Sea Surface Temperature indices (data fro...
2,871
Given the following text description, write Python code to implement the functionality described below step by step Description: De connectie met Lizard is gemaakt en bovenstaand zijn alle beschikbare endpoints. Nu gaan we de metadata verzamelen van de timeseries met uuid 867b166a-fa39-457d-a9e9-4bcb2ff04f61 Step1: ...
Python Code: result = cli.timeseries.get(uuid="867b166a-fa39-457d-a9e9-4bcb2ff04f61") result.metadata Explanation: De connectie met Lizard is gemaakt en bovenstaand zijn alle beschikbare endpoints. Nu gaan we de metadata verzamelen van de timeseries met uuid 867b166a-fa39-457d-a9e9-4bcb2ff04f61: End of explanation que...
2,872
Given the following text description, write Python code to implement the functionality described below step by step Description: Thermal equilibrium of a single particle In a large ensemble of identical systems each member will have a different state due to thermal fluctuations, even if all the systems were initialise...
Python Code: import numpy as np # anisotropy energy of the system def anisotropy_e(theta, sigma): return -sigma*np.cos(theta)**2 # numerator of the Boltzmann distribution # (i.e. without the partition function Z) def p_unorm(theta, sigma): return np.sin(theta)*np.exp(-anisotropy_e(theta, sigma)) Explanation: Th...
2,873
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', 'cccr-iitm', 'iitm-esm', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: CCCR-IITM Source ID: IITM-ESM Topic: Seaice Sub-Topics: Dynamics, Therm...
2,874
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 2 Step1: Evaluating a Heptagon Number We are almost ready to look at Python code for drawing these figures. The last step is to provide a mapping from heptagon numbers to real numbers...
Python Code: # load the definitions from the previous notebook %run HeptagonNumbers.py # represent points or vertices as pairs of heptagon numbers p0 = ( zero, zero ) p1 = ( sigma, zero ) p2 = ( sigma+1, rho ) p3 = ( sigma, rho*sigma ) p4 = ( zero, sigma*sigma ) p5 = ( -rho, rho*sigma ) p6 = ( -rho, rho ) heptagon = [ ...
2,875
Given the following text description, write Python code to implement the functionality described below step by step Description: Scores First let's take a look at the ratings users can give to images. This is just for warming up since this is a feature that's not so much used on Danbooru. Step1: Status Now we take a ...
Python Code: scores = %sql SELECT score, COUNT(*) FROM posts GROUP BY score ORDER BY score DESC worst_post = %sql SELECT id FROM posts WHERE score = (SELECT MIN(score) FROM posts) best_post = %sql SELECT id FROM posts WHERE score = (SELECT MAX(score) FROM posts) pd_count = scores.DataFrame()["count"] pd_count.index = s...
2,876
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Unsupervised Learning Project Step1: Data Exploration In this section, you will begin exploring the data through visualizations and code to understand h...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd from IPython.display import display # Allows the use of display() for DataFrames # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the whole...
2,877
Given the following text description, write Python code to implement the functionality described below step by step Description: AXON Step1: JSON is subset of AXON Here is well known example of JSON message Step2: One can see that content of json_vals and axon_vals are equal. Step3: AXON supports more readable and ...
Python Code: from __future__ import unicode_literals, print_function, division from pprint import pprint import axon import json import xml.etree as etree from IPython.display import HTML, display, display_html Explanation: AXON: Tutorial Let's import inventory for playing with AXON with python. End of explanation !cat...
2,878
Given the following text description, write Python code to implement the functionality described below step by step Description: 'rv' Datasets and Options Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't w...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: 'rv' Datasets and Options Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matplotlib ...
2,879
Given the following text description, write Python code to implement the functionality described below step by step Description: Feedback k domácím projektům Jde tento kód napsat jednodušeji, aby ale dělal úplně totéž? Step1: Ano, lze Step2: A co tento? Step3: Ten taky Step4: A do třetice Step5: A jeden nepodaře...
Python Code: for radek in range(4): radek += 1 for value in range(radek): print('X', end=' ') print('') Explanation: Feedback k domácím projektům Jde tento kód napsat jednodušeji, aby ale dělal úplně totéž? End of explanation for radek in range(1, 5): print('X ' * radek) Explanation: Ano, lze :-) End of exp...
2,880
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizing data is awesome. In this post, I decided to use D3 in iPython notebook to visualize the "network of frequent associations between 62 dolphins in a community living off Doubtful S...
Python Code: import networkx as nx G = nx.read_gml('dolphins.gml') ##downloaded from above link category = {} for i,k in G.edge.iteritems(): if len(k) < 4: category[i] = '< 4 neighbors' elif len(k) < 11: category[i] = '5-10 neighbors' else: category[i] = '> 10 neighbors' _nodes = [] ...
2,881
Given the following text description, write Python code to implement the functionality described below step by step Description: Interaktives Übungsblatt Vorgeplänkel Step1: Systemmatrizen Wir werden im Weiteren pyMG nutzen um die Systemmatrix für gegebene Parameter $ n$ und $\sigma$ für das Helmholtz-Problem in 1D a...
Python Code: import sys # Diese Zeile muss angepasst werden! sys.path.append("/home/moser/MG_2016/pyMG-2016/") import scipy as sp import numpy as np import matplotlib.pyplot as plt %matplotlib inline import pymg from project.helmholtz1d import Helmholtz1D from project.helmholtz1d_periodic import Helmholtz1D_Periodic fr...
2,882
Given the following text description, write Python code to implement the functionality described below step by step Description: Afinação e Notas Musicais Objetivo Após esta unidade, o aluno será capaz de aplicar modelos matemáticos para relacionar o fenômeno perceptual da altura, o fenômeno físico da frequência funda...
Python Code: referencia_inicial = 440.0 # Hz frequencias = [] # Esta lista recebera todas as frequencias de uma escala f = referencia_inicial while len(frequencias) < 12: if f > (referencia_inicial * 2): f /= 2. frequencias.append(f) f *= (3/2.) frequencias.sort() print frequencias print f Explanati...
2,883
Given the following text description, write Python code to implement the functionality described. Description: Minimum number of elements which are not part of Increasing or decreasing subsequence in array Python3 program to return minimum number of elements which are not part of increasing or decreasing subsequences ....
Python Code: MAX = 102 def countMin(arr , dp , n , dec , inc , i ) : if dp[dec ][inc ][i ] != - 1 : return dp[dec ][inc ][i ]  if i == n : return 0  if arr[i ] < arr[dec ] : dp[dec ][inc ][i ] = countMin(arr , dp , n , i , inc , i + 1 )  if arr[i ] > arr[inc ] : if dp[dec ][inc ][i ] == - 1 : ...
2,884
Given the following text description, write Python code to implement the functionality described below step by step Description: Step4: Recurrent Neural Networks For an introduction to RNN take a look at this great article. Basic RNNs Step5: Manual RNN Step6: Using rnn() The static_rnn() function creates an unrolle...
Python Code: # Common imports import numpy as np import numpy.random as rnd import os # to make this notebook's output stable across runs rnd.seed(42) # To plot pretty figures %matplotlib inline import matplotlib import matplotlib.pyplot as plt plt.rcParams['axes.labelsize'] = 14 plt.rcParams['xtick.labelsize'] = 12 pl...
2,885
Given the following text description, write Python code to implement the functionality described below step by step Description: record schedules for 2 weeks, then augment count with weekly flight numbers. seasonal and seasonal charter will count as once per week for 3 months, so 12/52 per week. TGM separate, since it...
Python Code: for i in locations: print i if i not in sch:sch[i]={} #march 11-24 = 2 weeks for d in range (11,25): if d not in sch[i]: try: url=airportialinks[i] full=url+'arrivals/201703'+str(d) m=requests.get(full).content ...
2,886
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook provides an example on how to use a custom class within Flexcode. <br> In order to be compatible, a regression method needs to have a fit and predict method implemented - i.e. ...
Python Code: import flexcode import numpy as np import xgboost as xgb from flexcode.regression_models import XGBoost, CustomModel Explanation: This notebook provides an example on how to use a custom class within Flexcode. <br> In order to be compatible, a regression method needs to have a fit and predict method implem...
2,887
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Long Short-Term Memory Network Example Licensed under the Apache License, Version 2.0. This example implements a Bayesian version of LSTM (Hochreiter, Schmidhuber, 1997) using tf.ke...
Python Code: import numpy as np import seaborn as sns import pandas as pd import tensorflow as tf import edward2 as ed import matplotlib.pyplot as plt from tqdm import tqdm from sklearn.model_selection import train_test_split, ParameterGrid from tensorflow.keras.preprocessing import sequence import embedded_reber_gramm...
2,888
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--BOOK_INFORMATION--> <a href="https Step1: Because of all the noise we added, the two half moons might not be apparent at first glance. That's a perfect scenario for our current intentio...
Python Code: from sklearn.datasets import make_moons X, y = make_moons(n_samples=100, noise=0.25, random_state=100) import matplotlib.pyplot as plt %matplotlib inline plt.style.use('ggplot') plt.figure(figsize=(10, 6)) plt.scatter(X[:, 0], X[:, 1], s=100, c=y) plt.xlabel('feature 1') plt.ylabel('feature 2'); Explanatio...
2,889
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial - Assemble the data on the wikitext dataset Using Datasets, Pipeline, TfmdLists and Transform in text In this tutorial, we explore the mid-level API for data collection in the text ...
Python Code: path = untar_data(URLs.WIKITEXT_TINY) Explanation: Tutorial - Assemble the data on the wikitext dataset Using Datasets, Pipeline, TfmdLists and Transform in text In this tutorial, we explore the mid-level API for data collection in the text application. We will use the bases introduced in the pets tutorial...
2,890
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Scientific Programming in Python</h1> <h2 align="center">Topic 2 Step1: Table of Contents 1.- Useful Magics 2.- Basic NumPy Operations 3.- Internals of NumPy 4.- Efficien...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import scipy as sp Explanation: <h1 align="center">Scientific Programming in Python</h1> <h2 align="center">Topic 2: NumPy and Efficient Numerical Programming</h2> Notebook created by Martín Villanueva - martin.villanueva@usm.cl - DI UTF...
2,891
Given the following text description, write Python code to implement the functionality described below step by step Description: Purpose Step2: Input Step3: Workflow Tokenization to break text into units e.g. words, phrases, or symbols Stop word removal to get rid of common words e.g. this, a, is Step4: About stem...
Python Code: import pandas as pd import nltk from nltk.corpus import stopwords from nltk.stem import SnowballStemmer from collections import Counter Explanation: Purpose: To experiment with Python's Natural Language Toolkit. NLTK is a leading platform for building Python programs to work with human language data End of...
2,892
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebook Problem Step1: Unit Test The following unit test is expected to fa...
Python Code: class Node(object): def __init__(self, data): # TODO: Implement me pass def insert(root, data): # TODO: Implement me pass Explanation: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebook Problem: Implement a ...
2,893
Given the following text description, write Python code to implement the functionality described below step by step Description: Apriori 算法 - (1) 把各项目放到只包含自己的项集中,生成最初的频繁项集。只使用达到最小支持度的项目。 - (2) 查找现有频繁项集的超集,发现新的频繁项集,并用其生成新的备选项集。 - (3) 测试新生成的备选项集的频繁程度,如果不够频繁,则舍弃。如果没有新的频繁项集,就跳到最后一步。 - (4) 存储新发现的频繁项集,跳到步骤(2)。 - (5) 返回发现的所有...
Python Code: frequent_itemsets = {} min_support = 50 Explanation: Apriori 算法 - (1) 把各项目放到只包含自己的项集中,生成最初的频繁项集。只使用达到最小支持度的项目。 - (2) 查找现有频繁项集的超集,发现新的频繁项集,并用其生成新的备选项集。 - (3) 测试新生成的备选项集的频繁程度,如果不够频繁,则舍弃。如果没有新的频繁项集,就跳到最后一步。 - (4) 存储新发现的频繁项集,跳到步骤(2)。 - (5) 返回发现的所有频繁项集。 End of explanation frequent_itemsets[1] = dict((frozenset...
2,894
Given the following text description, write Python code to implement the functionality described below step by step Description: Feature selection Step1: Our first step is to count up all of the words in each of the documents. This conditional frequency distribution should look familiar by now.
Python Code: documents = nltk.corpus.PlaintextCorpusReader('../data/EmbryoProjectTexts/files', 'https.+') metadata = zotero.read('../data/EmbryoProjectTexts', index_by='link', follow_links=False) Explanation: Feature selection: keywords A major problem-area in text mining is determining the thematic or topical content ...
2,895
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Image Processing Image processing is a very useful tool for scientists in the lab, and for everyday uses as well. For, example, an astronomer may use image processing to help...
Python Code: # set exercise1 equal to your matrix exercise1 = #your matrix goes here Explanation: Introduction to Image Processing Image processing is a very useful tool for scientists in the lab, and for everyday uses as well. For, example, an astronomer may use image processing to help find and recognize stars, or a ...
2,896
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting the occupancies of Belgian trains In this lab, we will go over some of the typical steps in a data science pipeline Step1: 0. Create a kaggle account! https Step2: Processing th...
Python Code: import os os.getcwd() %matplotlib inline %pylab inline import pandas as pd import numpy as np from collections import Counter, OrderedDict import json import matplotlib import matplotlib.pyplot as plt import re from scipy.misc import imread from sklearn.linear_model import LogisticRegression from sklearn....
2,897
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize Epochs data Step1: This tutorial focuses on visualization of epoched data. All of the functions introduced here are basically high level matplotlib functions with built in intelli...
Python Code: import os.path as op import mne data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample') raw = mne.io.read_raw_fif(op.join(data_path, 'sample_audvis_raw.fif')) raw.set_eeg_reference() # set EEG average reference event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3, ...
2,898
Given the following text description, write Python code to implement the functionality described below step by step Description: The Easy "Hard" Way Step1: 1. A Quick Introduction to Cython Cython is a compiler and a programming language used to generate C extension modules for Python. The Cython language is a Python...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import sympy as sym sym.init_printing() Explanation: The Easy "Hard" Way: Cythonizing In this notebook, we'll build on the previous work where we used SymPy's code printers to generate code for evaluating expressions numerically. As a la...
2,899
Given the following text description, write Python code to implement the functionality described. Description: Largest Sum Contiguous Subarray having unique elements Function to calculate required maximum subarray sum ; Initialize two pointers ; Stores the unique elements ; Insert the first element ; Current max sum ; ...
Python Code: def maxSumSubarray(arr ) : i = 0 j = 1 set = { } set[arr[0 ] ] = 1 sum = arr[0 ] maxsum = sum while(i < len(arr ) - 1 and j < len(arr ) ) : if arr[j ] not in set : sum = sum + arr[j ] maxsum = max(sum , maxsum ) set[arr[j ] ] = 1 j += 1  else : sum -= arr[i ] del set[arr[...