Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
11,700
Given the following text description, write Python code to implement the functionality described below step by step Description: ISCpy ISCpy a robust ISC config file parser. It has virtually unlimited possibilities for depth and quantity of ISC config files. ISC config files include BIND and DHCP config files among a ...
Python Code: import iscpy with open('named.conf') as fp: s = fp.read() config = iscpy.ParseISCString(s) type(config) Explanation: ISCpy ISCpy a robust ISC config file parser. It has virtually unlimited possibilities for depth and quantity of ISC config files. ISC config files include BIND and DHCP config files amon...
11,701
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Automatic Differentiation in JAX Authors Step1: The higher-order derivatives of $f$ are Step2: Evaluating the above in $x=1$ would give us Step3: In the multivariable case, highe...
Python Code: import jax f = lambda x: x**3 + 2*x**2 - 3*x + 1 dfdx = jax.grad(f) Explanation: Advanced Automatic Differentiation in JAX Authors: Vlatimir Mikulik & Matteo Hessel Computing gradients is a critical part of modern machine learning methods. This section considers a few advanced topics in the areas of automa...
11,702
Given the following text description, write Python code to implement the functionality described below step by step Description: The curse of hunting rare things What are the chances of intersecting features with a grid of cross-sections? I'd like to know the probability of intersecting features with a grid of cross-s...
Python Code: area = 120000.0 # km^2, area covered by transects population = 120 # Total number of features (guess) no_lines = 250 # Total number of transects line_length = 150 # km, mean length of a transect feature_width = 0.5 # km, width of features density = population / area length = no_lines * l...
11,703
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple interactive bacgkround jobs with IPython We start by loading the backgroundjobs library and defining a few trivial functions to illustrate things with. Step1: Now, we can create a jo...
Python Code: from IPython.lib import backgroundjobs as bg import sys import time def sleepfunc(interval=2, *a, **kw): args = dict(interval=interval, args=a, kwargs=kw) time.sleep(interval) return args def diefunc(interval=2, *a, **kw): time.sleep(interval) raise Excep...
11,704
Given the following text description, write Python code to implement the functionality described below step by step Description: Presented Below are two plots in subplot configuration. The upper plot is a sum of the cusp crossings. The lower plot is a plot of the cusp latitude and the spacecraft latitude/longitude p...
Python Code: import tsyganenko as tsyg import pandas as pd import numpy as np import matplotlib.pyplot as plt from spacepy import coordinates as coord import spacepy.time as spt from spacepy.time import Ticktock import datetime as dt from mpl_toolkits.mplot3d import Axes3D import sys #adding the year data here so I don...
11,705
Given the following text description, write Python code to implement the functionality described below step by step Description: Content and Objective Show approximations by using gaussian approximation Additionally, applying Gram-Schmidt for "orthonormalizing" a set of functions Step1: definitions Step2: Define Gra...
Python Code: # importing import numpy as np import scipy.signal import scipy as sp import sympy as sym from sympy.plotting import plot Explanation: Content and Objective Show approximations by using gaussian approximation Additionally, applying Gram-Schmidt for "orthonormalizing" a set of functions End of explanation #...
11,706
Given the following text description, write Python code to implement the functionality described below step by step Description: CS228 Python Tutorial Adapted by Volodymyr Kuleshov and Isaac Caswell from the CS231n Python tutorial by Justin Johnson (http Step1: Python versions There are currently two different suppor...
Python Code: def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) / 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) print quicksort([3,6,8,10,1,2,1]) ...
11,707
Given the following text description, write Python code to implement the functionality described below step by step Description: A method to use the present_load to balance the leg of poppy Step1: A trick to switch from real time to simulated time using time function (because my VREP is not in real time - about 3 tim...
Python Code: from poppy.creatures import PoppyHumanoid poppy = PoppyHumanoid(simulator='vrep') %pylab inline #import time Explanation: A method to use the present_load to balance the leg of poppy End of explanation import time as real_time class time: def __init__(self,robot): self.robot=robot def time(...
11,708
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework Step1: Task Replace previous model with equivalent in prettytensor or tf.slim Try to make you code as compact as possible Step2: You can play generated sample using any midi playe...
Python Code: import numpy as np from music21 import stream, midi, tempo, note from grammar import unparse_grammar from preprocess import get_musical_data, get_corpus_data from qa import prune_grammar, prune_notes, clean_up_notes from generator import __sample, __generate_grammar, __predict import tflearn N_epochs = 128...
11,709
Given the following text description, write Python code to implement the functionality described below step by step Description: Today's Objectives 0. Cloning LectureNotes 1. Opening & Navigating the Jupyter Notebook 2. Data type basics 3. Loading data with pandas 4. Cleaning and Manipulating data with pandas 5. Visua...
Python Code: # Integer arithematic 1 + 1 # Integer division version floating point division print (6 // 4, 6/ 4) Explanation: Today's Objectives 0. Cloning LectureNotes 1. Opening & Navigating the Jupyter Notebook 2. Data type basics 3. Loading data with pandas 4. Cleaning and Manipulating data with pandas 5. Visualizi...
11,710
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 3b Step1: Verify tables exist Run the following cells to verify that we previously created the dataset and data tables. If not, go back to lab 1b_prepare_data_babyweight to create them....
Python Code: %%bash sudo pip freeze | grep google-cloud-bigquery==1.6.1 || \ sudo pip install google-cloud-bigquery==1.6.1 Explanation: LAB 3b: BigQuery ML Model Linear Feature Engineering/Transform. Learning Objectives Create and evaluate linear model with BigQuery's ML.FEATURE_CROSS Create and evaluate linear model ...
11,711
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="http Step1: Tutorial - How to work with the OpenEnergy Platform (OEP) <br> <div class="alert alert-block alert-danger"> This is an important information! </div> <div class="alert ...
Python Code: __copyright__ = "Zentrum für nachhaltige Energiesysteme Flensburg" __license__ = "GNU Affero General Public License Version 3 (AGPL-3.0)" __url__ = "https://github.com/openego/data_processing/blob/master/LICENSE" __author__ = "wolfbunke" Explanation: <img src="http://193.175.187.164/static/OEP_l...
11,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Load Iris Dataset Step2: Make Iris Dataset Imbalanced Step3: Upsampling Minority Class To Match Majority
Python Code: # Load libraries import numpy as np from sklearn.datasets import load_iris Explanation: Title: Handling Imbalanced Classes With Upsampling Slug: handling_imbalanced_classes_with_upsampling Summary: How to handle imbalanced classes with upsampling during machine learning in Python. Date: 2016-09-06 12:00 C...
11,713
Given the following text description, write Python code to implement the functionality described below step by step Description: Random Forest In random forests, each tree in the ensemble is built from a sample drawn with replacement (i.e., a bootstrap sample) from the training set. In addition, when splitting a node ...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use('fivethirtyeight') df = pd.read_csv("data/historical_loan.csv") # refine the data df.years = df.years.fillna(np.mean(df.years)) #Load the preprocessing module from sklearn import preprocessing categorica...
11,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Py-EMDE Python Email Data Entry The following code can gather data from weather stations reporting to the CHORDS portal, package it up into the proper format for GLOBE Email Data Entry , and...
Python Code: import requests import json r = requests.get('http://3d-kenya.chordsrt.com/instruments/2.geojson?start=2017-03-01T00:00&end=2017-05-01T00:00') if r.status_code == 200: d = r.json()['Data'] else: print("Please verify that the URL for the weather station is correct. You may just have to try again wit...
11,715
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Experimenting with CV Scores CVScores displays cross validation scores as a bar chart with the average of the scores as a horizontal line. Step2: Classification Step3: Regression
Python Code: import pandas as pd import matplotlib.pyplot as plt from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import StratifiedKFold from yellowbrick.model_selection import CVScores import os from yellowbrick.download import download_all ## The path to the test data sets FIXTURES = os.pat...
11,716
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details. Step2: And we'll attach some dummy datasets. See Datasets fo...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Advanced: Alternate Backends Setup Let's first make sure we have the latest version of PHOEBE 2.1 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 import ph...
11,717
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Part 18 Step1: Next we create a network to implement the policy. We begin with two convolutional layers to process the image. That is followed by a dense (fully connected) layer ...
Python Code: %tensorflow_version 1.x !curl -Lo deepchem_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import deepchem_installer %time deepchem_installer.install(version='2.3.0') !pip install 'gym[atari]' import deepchem as dc import numpy as np class PongEnv(dc.rl.GymE...
11,718
Given the following text description, write Python code to implement the functionality described below step by step Description: TUTORIAL 04 - Graetz problem 1 Keywords Step1: 3. Affine decomposition In order to obtain an affine decomposition, we proceed as in the previous tutorial and recast the problem on a fixed, ...
Python Code: from dolfin import * from rbnics import * Explanation: TUTORIAL 04 - Graetz problem 1 Keywords: successive constraints method 1. Introduction This Tutorial addresses geometrical parametrization and the successive constraints method (SCM). In particular, we will solve the Graetz problem, which deals with fo...
11,719
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: For the sake of visualizing values at nodes on our grid, we'll define a handy little function Step2: Let's review the numbering of nodes and links. The lines below wil...
Python Code: from landlab import RasterModelGrid import numpy as np mg = RasterModelGrid((3, 4), xy_spacing=100.0) h = mg.add_zeros('surface_water__depth', at='node') h[:] = 7 - np.abs(6 - np.arange(12)) Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../landlab_header.png"></a> Mapping...
11,720
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="#Strings-and-Text" data-toc-modified-id="Strings-and-Text-1"><span class="toc...
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(plot_style=False) os.chdir(path) # magic to print version %load_ext waterma...
11,721
Given the following text description, write Python code to implement the functionality described below step by step Description: This example demonstrates one possible way to cluster data sets that are too large to fit into memory using MDTraj and scipy.cluster. The idea for the algorithim is that we'll cluster every ...
Python Code: from __future__ import print_function import random from collections import defaultdict import mdtraj as md import numpy as np import scipy.cluster.hierarchy stride = 5 subsampled = md.load('ala2.h5', stride=stride) print(subsampled) Explanation: This example demonstrates one possible way to cluster data s...
11,722
Given the following text description, write Python code to implement the functionality described below step by step Description: Diagonalizing a Matrix $ \mathbf{A} x_1 = \lambda_1 x_1 \ \mathbf{A} x_2 = \lambda_2 x_2 \ \mathbf{A} \times \begin{vmatrix} x_1 & x_2 \end{vmatrix} = \begin{vmatrix} \lambda_1 x_1 & \lambda...
Python Code: import numpy as np from scipy.linalg import eig, inv from diffmaps_util import k, diag, sort_eigens m = np.array([.8, .2, .5, .5]).reshape(2,2) m u0 = np.array([0,1]) for i in range(0,50): u0 = u0.dot(m) print u0 w, v = eig(m) print w.real print v v.dot(inv(v).dot(u0)) Explanation: Diagonalizing a Matr...
11,723
Given the following text description, write Python code to implement the functionality described below step by step Description: Regularization Step1: We have referred to regularization in earlier sections, but we want to develop this important idea more fully. Regularization is the mechanism by which we navigate the...
Python Code: from IPython.display import Image Image('../../../python_for_probability_statistics_and_machine_learning.jpg') Explanation: Regularization End of explanation import sympy as S S.var('x:2 l',real=True) J=S.Matrix([x0,x1]).norm()**2 + l*(1-x0-2*x1) sol=S.solve(map(J.diff,[x0,x1,l])) print(sol) Explanation: ...
11,724
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Simple Query This is a simple single-level query. Default Columns Step2: The system also supports Pan-STARRS1 and 2MASS cross-matches using the panstarrs1 and twomass keywords Step3:...
Python Code: circle = --Selections: Cluster RA 1=CONTAINS(POINT('ICRS',gaia.ra,gaia.dec), CIRCLE('ICRS',{ra:.4f},{dec:.4f},{rad:.2f})) .format(ra=230, dec=0, rad=4) df = make_simple_query( WHERE=circle, # The WHERE part of the SQL random_index=1e4, # a shortcut to use the random_index...
11,725
Given the following text description, write Python code to implement the functionality described below step by step Description: Meetup 1 Going to parse texts for most used words. Step1: We want to "tokenize" the text and discard "stopwords" like 'a', 'the', 'in'. These words aren't relevant for our analysis. To toke...
Python Code: # Lets see how many lines are in the PDF # We can use the '!' special character to run Linux commands inside of our notebook !wc -l test.txt # Now lets see how many words !wc -w test.txt import nltk from nltk import tokenize # Lets open the file so we can access the ascii contents # fd stands for file desc...
11,726
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean 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', 'cnrm-cerfacs', 'sandbox-1', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: CNRM-CERFACS Source ID: SANDBOX-1 Topic: Ocean Sub-Topics: Timesteppi...
11,727
Given the following text description, write Python code to implement the functionality described below step by step Description: Representational Similarity Analysis Representational Similarity Analysis is used to perform summary statistics on supervised classifications where the number of classes is relatively high. ...
Python Code: # Authors: Jean-Remi King <jeanremi.king@gmail.com> # Jaakko Leppakangas <jaeilepp@student.jyu.fi> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import os.path as op import numpy as np from pandas import read_csv import matplotlib.pyplot as plt...
11,728
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with sensor locations This tutorial describes how to read and plot sensor locations, and how the physical location of sensors is handled in MNE-Python. Step1: About montages and...
Python Code: import os import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') ...
11,729
Given the following text description, write Python code to implement the functionality described below step by step Description: syncID Step1: Next, we read in the example data. Note that you will need to update the filepaths below to work on your machine. Step2: Now we can plot the data. Step3: Save this project w...
Python Code: import numpy as np import matplotlib import matplotlib.pyplot as mplt from scipy import linalg from scipy import io ### Ordinary Least Squares ### SOLVES 2-CLASS LEAST SQUARES PROBLEM ### LOAD DATA ### ### IF LoadClasses IS True, THEN LOAD DATA FROM FILES ### ### OTHERSIE, RANDOMLY GENERATE DATA ### LoadCl...
11,730
Given the following text description, write Python code to implement the functionality described below step by step Description: An RNN for short-term predictions This model will try to predict the next value in a short sequence based on historical data. This can be used for example to forecast demand based on a coupl...
Python Code: import numpy as np import utils_datagen import utils_display from matplotlib import pyplot as plt import tensorflow as tf print("Tensorflow version: " + tf.__version__) Explanation: An RNN for short-term predictions This model will try to predict the next value in a short sequence based on historical data....
11,731
Given the following text description, write Python code to implement the functionality described below step by step Description: Adding a Data Set to pods Open Data Science Initiative 28th May 2014 Neil D. Lawrence Adding a data set to GPy should be done in two stages. Firstly, you need to edit the data_resources.json...
Python Code: def boston_housing(data_set='boston_housing'): if not data_available(data_set): download_data(data_set) all_data = np.genfromtxt(os.path.join(data_path, data_set, 'housing.data')) X = all_data[:, 0:13] Y = all_data[:, 13:14] return data_details_return({'X' : X, 'Y': Y}, data_set...
11,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the nlputils library In this iPython Notebook are some examples of how various parts of the nlputils library can be used with text and other datasets. General knowledge of common machi...
Python Code: from __future__ import unicode_literals, division, print_function, absolute_import from builtins import str, range import numpy as np import matplotlib.pyplot as plt from matplotlib import offsetbox from scipy.spatial.distance import pdist, squareform from sklearn.datasets import fetch_20newsgroups, load_d...
11,733
Given the following text description, write Python code to implement the functionality described below step by step Description: Marvin Maps Marvin Maps is how you deal with the DAP MAPS FITS files easily. You can retrieve maps in several ways. Let's take a took. From a Marvin Maps Marvin Maps takes the same inputs...
Python Code: # import the maps from marvin.tools.maps import Maps # Load a MPL-5 map mapfile = '/Users/Brian/Work/Manga/analysis/v2_0_1/2.0.2/SPX-GAU-MILESHC/8485/1901/manga-8485-1901-MAPS-SPX-GAU-MILESHC.fits.gz' # Let's get a default map of maps = Maps(filename=mapfile) print(maps) Explanation: Marvin Maps Marvin Map...
11,734
Given the following text description, write Python code to implement the functionality described below step by step Description: 🏭 Coal Plant ON/OFF Step1: 🛎️ [DON’T PANIC] It’s safe to ignore the warnings. When we pip install the requirements, there might be some warnings about conflicting dependency versions. For...
Python Code: # Get the sample source code. !git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git ~/python-docs-samples %cd ~/python-docs-samples/people-and-planet-ai/geospatial-classification !pip install -r requirements.txt -c constraints.txt Explanation: 🏭 Coal Plant ON/OFF: Predictions Time esti...
11,735
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started with Images cv2.imread, cv2.imshow, cv2.imwrite Reading an image - cv2.imread() cv2.imread() has two arguments, one address of the image and the other as following arguments ...
Python Code: import numpy as np import cv2 ls file_adr = 'Me1.png' img = cv2.imread(file_adr,cv2.IMREAD_GRAYSCALE) # Alternate- 0 cv2.IMREAD_GRAYSCALE - 0 cv2.imwrite('Me1_gray.jpg', img) # img2 = cv2.imread('Me1_gray.jpg', cv2.IMREAD_COLOR) Explanation: Getting Started with Images cv2.imread, cv2.imshow, cv2.imwrite...
11,736
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Given a pandas DataFrame, how does one convert several binary columns (where 1 denotes the value exists, 0 denotes it doesn't) into a single categorical column?
Problem: import pandas as pd df = pd.DataFrame({'A': [1, 0, 0, 0, 1, 0], 'B': [0, 1, 0, 0, 0, 1], 'C': [0, 0, 1, 0, 0, 0], 'D': [0, 0, 0, 1, 0, 0]}) df["category"] = df.idxmax(axis=1)
11,737
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', 'pcmdi', 'pcmdi-test-1-0', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: PCMDI Source ID: PCMDI-TEST-1-0 Topic: Seaice Sub-Topics: Dynamics, T...
11,738
Given the following text description, write Python code to implement the functionality described below step by step Description: Общая информация Срок сдачи Step1: IRIS Step2: MNIST Step3: Задание 5
Python Code: import numpy as np import matplotlib.pyplot as plt from line_profiler import LineProfiler from sklearn.metrics.pairwise import pairwise_distances import seaborn as sns from sklearn import datasets from sklearn.base import ClassifierMixin from sklearn.datasets import fetch_mldata from sklearn.neighbors.base...
11,739
Given the following text description, write Python code to implement the functionality described below step by step Description: A transformada discreta de Fourier (DFT) Caso unidimensional Transformada Discreta de Fourier em uma dimensão Step1: Para exemplificar o caso unidimensional, vamos pegar uma imagem bidimens...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from numpy.fft import * import sys,os ia898path = os.path.abspath('../../') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia Explanation: A transformada discreta de Four...
11,740
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.ml - Pipeline pour un réduction d'une forêt aléatoire - énoncé Le modèle Lasso permet de sélectionner des variables, une forêt aléatoire produit une prédiction comme étant la moyenne d'ar...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline Explanation: 2A.ml - Pipeline pour un réduction d'une forêt aléatoire - énoncé Le modèle Lasso permet de sélectionner des variables, une forêt aléatoire produit une prédiction comme étant la moyenne d'arbres de régression. C...
11,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to Pynq Audio This notebook shows the basic recording and playback features of the Pynq-Z1. It uses the audio jack to play back recordings from the built-in microphone, as well as a ...
Python Code: from pynq import Overlay from pynq.drivers import Audio Overlay('base.bit').download() pAudio = Audio() Explanation: Welcome to Pynq Audio This notebook shows the basic recording and playback features of the Pynq-Z1. It uses the audio jack to play back recordings from the built-in microphone, as well as a ...
11,742
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I am using python and scikit-learn to find cosine similarity between item descriptions.
Problem: import numpy as np import pandas as pd import sklearn from sklearn.feature_extraction.text import TfidfVectorizer df = load_data() tfidf = TfidfVectorizer() from sklearn.metrics.pairwise import cosine_similarity response = tfidf.fit_transform(df['description']).toarray() tf_idf = response cosine_similarity_mat...
11,743
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to data munging with Jupyter and pandas PyGotham 2015 Step1: The case for open source data tools Reproducibility and Transparency Cost -- compare capabilities between software ...
Python Code: from __future__ import division import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import rpy2 from IPython.display import display, Image, YouTubeVideo %matplotlib inline Explanation: Introduction to data munging with Jupyter and pandas PyG...
11,744
Given the following text description, write Python code to implement the functionality described below step by step Description: This is the <a href="https Step1: How do we define direction of an earth magnetic field? Earth magnetic field is a vector. To define a vector we need to choose a coordinate system. We use r...
Python Code: import numpy as np from geoscilabs.mag import Mag, Simulator from SimPEG.potential_fields import magnetics as mag from SimPEG import utils, data from discretize import TensorMesh Explanation: This is the <a href="https://jupyter.org/">Jupyter Notebook</a>, an interactive coding and computation environment....
11,745
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Astro 283 Homework 5</h1> Bijan Pourhamzeh Step1: <h3>Random Sampling</h3> Here we sample from a distribution given by the equation $$ p(x\mid \alpha,\beta) = \left{ \begin{array}{ll} \...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy.special import iv import scipy.stats from csv import reader from __future__ import print_function Explanation: <h1>Astro 283 Homework 5</h1> Bijan Pourhamzeh End of explanation #Choose parameters and plot to see what it looks ...
11,746
Given the following text description, write Python code to implement the functionality described below step by step Description: Definition of the problem We need to develop a model that can classify breast cells as bningn (non harmful) or malignant (cancerous). The list of attribues are Step1: Clean data missing dat...
Python Code: # 1 Read dataset cols = [ 'clump thickness', 'uniformity of cell size', 'uniformity of cell shape', 'marginal adhesion', 'single epithelial cell size', 'bare nuclei', 'bland chromatin', 'normal nucleoli', 'mitoses', 'class'] df = pd.read...
11,747
Given the following text description, write Python code to implement the functionality described below step by step Description: How to handle models from Python? In this tutorial you will learn how to handle models from Python. This is done using the GammaLib classes GModels, GModel, GModelSpatial, GModelSpectral, an...
Python Code: import gammalib Explanation: How to handle models from Python? In this tutorial you will learn how to handle models from Python. This is done using the GammaLib classes GModels, GModel, GModelSpatial, GModelSpectral, and GModelTemporal. You can find all the information on the GammaLib classes in the Doxyge...
11,748
Given the following text description, write Python code to implement the functionality described below step by step Description: When I first ran this, my dataframes weren't "aligned". So it's very important to check your datasets after every load. The correspondence between dates and topics and numerical features is ...
Python Code: print(len(dates)) print(len(topics)) print(len(nums)) print(sum(nums.favorite_count >= 1)) sum(nums.index == dates.index) == len(dates) sum(nums.index == topics.index) == len(dates) sgd = SGDRegressor() sgd sgd = SGDRegressor().fit(topics.values, nums.favorite_count) Explanation: When I first ran this, my ...
11,749
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: What's this TensorFlow business? You've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are ...
Python Code: import tensorflow as tf import numpy as np import math import timeit import matplotlib.pyplot as plt %matplotlib inline from cs231n.data_utils import load_CIFAR10 def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=10000): Load the CIFAR-10 dataset from disk and perform preproce...
11,750
Given the following text description, write Python code to implement the functionality described below step by step Description: Boston Housing Prediction Author Step1: Loading the boston dataset - Train and Test Step2: Understanding the distribution and relationship of the data Describing the data to understand the...
Python Code: import pandas as pd import numpy as np Explanation: Boston Housing Prediction Author: Rishu Shrivastava, Babu Sivaprakasam Link: https://www.kaggle.com/c/boston-housing Last Update: 02 Apr 2018 Importing libraries End of explanation data_path = "C:/Users/Rishu/Desktop/dATA/boston/" boston_data=pd.read_csv(...
11,751
Given the following text description, write Python code to implement the functionality described below step by step Description: You are currently looking at version 1.0 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ...
Python Code: import pandas as pd df = pd.read_csv('olympics.csv', index_col=0, skiprows=1) for col in df.columns: if col[:2]=='01': df.rename(columns={col:'Gold'+col[4:]}, inplace=True) if col[:2]=='02': df.rename(columns={col:'Silver'+col[4:]}, inplace=True) if col[:2]=='03': df.ren...
11,752
Given the following text description, write Python code to implement the functionality described below step by step Description: Evolutionary game theory - solutions Assume the frequency dependent selection model for a population with two types of individuals Step1: B. $f_1(x)=x_1x_2 - x_2\qquad f_2(x)=x_2 - x_1 + 1/...
Python Code: import sympy as sym x_1 = sym.symbols("x_1") sym.solveset(3 * x_1 - 2 * (1 - x_1), x_1) Explanation: Evolutionary game theory - solutions Assume the frequency dependent selection model for a population with two types of individuals: $x=(x_1, x_2)$ such that $x_1 + x_2 = 1$. Obtain all the stable distributi...
11,753
Given the following text description, write Python code to implement the functionality described below step by step Description: My installtion instructions Step1: Import Policy, RL agent, ... Step3: Define a Callback Function Step5: Create and wrap the environment Step6: Define and train the PPO agent Step9: Plo...
Python Code: import stable_baselines stable_baselines.__version__ Explanation: My installtion instructions: https://gitlab.com/-/snippets/2057703 Source: https://colab.research.google.com/github/Stable-Baselines-Team/rl-colab-notebooks/blob/master/monitor_training.ipynb See also: https://stable-baselines.readthedocs.io...
11,754
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Arrays and Vectorization Frequently, matrices and vectors are needed for computation and are a convenient way to store and access data. Vectors are more commonly many rows with a singl...
Python Code: # Python imports import numpy as np Explanation: Numpy Arrays and Vectorization Frequently, matrices and vectors are needed for computation and are a convenient way to store and access data. Vectors are more commonly many rows with a single column. A significant amount of work has been done to make compute...
11,755
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling Protein-Ligand Interactions with Atomic Convolutions By Nathan C. Frey | Twitter and Bharath Ramsundar | Twitter This DeepChem tutorial introduces the Atomic Convolutional Neural Ne...
Python Code: !pip install -q condacolab import condacolab condacolab.install() !/usr/local/bin/conda info -e !/usr/local/bin/conda install -c conda-forge pycosat mdtraj pdbfixer openmm -y -q # needed for AtomicConvs !pip install --pre deepchem import deepchem deepchem.__version__ import deepchem as dc import os import...
11,756
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutions and sliding windows Plots inline Step1: Imports Step2: Some utility functions for making an image montage for display and padding images Step3: Load a photo of some fruit Ste...
Python Code: %matplotlib inline Explanation: Convolutions and sliding windows Plots inline: End of explanation import os import numpy as np from matplotlib import pyplot as plt from scipy.ndimage import convolve from skimage.filters import gabor_kernel from skimage.color import rgb2grey from skimage.util.montage import...
11,757
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating a chord progression with a genetic algorithm This work is the result of an experiment done some months ago. I used a simple genetic algorithm to find a solution to a classic exercis...
Python Code: from IPython import display display.Image('img/simple.jpg', width=400) Explanation: Creating a chord progression with a genetic algorithm This work is the result of an experiment done some months ago. I used a simple genetic algorithm to find a solution to a classic exercise of harmony: given a certain voi...
11,758
Given the following text description, write Python code to implement the functionality described below step by step Description: First, I made a mistake naming the data set! It's 2015 data, not 2014 data. But yes, still use 311-2014.csv. You can rename it. Importing and preparing your data Import your data, but only t...
Python Code: #df = pd.read_csv("small-311-2015.csv") df = pd.read_csv("311-2014.csv", nrows=200000) df.head(2) df.info() def parse_date (str_date): return dateutil.parser.parse(str_date) df['created_dt']= df['Created Date'].apply(parse_date) df.head(3) df.info() Explanation: First, I made a mistake naming the data ...
11,759
Given the following text description, write Python code to implement the functionality described below step by step Description: Configuring MNE python This tutorial gives a short introduction to MNE configurations. Step1: MNE-python stores configurations to a folder called .mne in the user's home directory, or to Ap...
Python Code: import os.path as op import mne from mne.datasets.sample import data_path fname = op.join(data_path(), 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(fname).crop(0, 10) original_level = mne.get_config('MNE_LOGGING_LEVEL', 'INFO') Explanation: Configuring MNE python This tutorial gives ...
11,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Probabilitic Graphical Models Step1: Contents What is machine learning Different ways of learning from data Why probabilistic graphical models Major types of PGMs 1. What is...
Python Code: from IPython.display import Image Explanation: Introduction to Probabilitic Graphical Models End of explanation %run ../scripts/1/discretize.py data Explanation: Contents What is machine learning Different ways of learning from data Why probabilistic graphical models Major types of PGMs 1. What is machine ...
11,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Training Code for finding the best predictive model Author Step1: The default directory is the code subdirectory. Changing to the main repo directory above. Upload Data Step2: Rando...
Python Code: import os import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import json from IPython.display import Image from IPython.core.display import HTML Explanation: Model Training Code for finding the best predictive model Author: Jimmy Charité Email: jimmy.charite@gmail...
11,762
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Let's download and import our primary Canadian Immigration dataset using pandas read_excel() method. Normally, before we can do that, we would need to download a modul...
Python Code: import numpy as np # useful for many scientific computing in Python import pandas as pd # primary data structure library from PIL import Image # converting images into arrays Explanation: <a href="https://cognitiveclass.ai"><img src = "https://ibm.box.com/shared/static/9gegpsmnsoo25ikkbl4qzlvlyjbgxs5x.png...
11,763
Given the following text description, write Python code to implement the functionality described below step by step Description: Artifact correction with Maxwell filter This tutorial shows how to clean MEG data with Maxwell filtering. Maxwell filtering in MNE can be used to suppress sources of external intereference a...
Python Code: import mne from mne.preprocessing import maxwell_filter data_path = mne.datasets.sample.data_path() Explanation: Artifact correction with Maxwell filter This tutorial shows how to clean MEG data with Maxwell filtering. Maxwell filtering in MNE can be used to suppress sources of external intereference and c...
11,764
Given the following text description, write Python code to implement the functionality described below step by step Description: initialize the Cosmological models Step1: Define proxy modelling Use a mass proxy, define the probability for observing a proxy given a mass and redhsift $$ P(\log\lambda|M,z) = N(\mu(M,z),...
Python Code: #CCL cosmology cosmo_ccl = ccl.Cosmology(Omega_c = 0.30711 - 0.048254, Omega_b = 0.048254, h = 0.677, sigma8 = 0.8822714165197718, n_s=0.96, Omega_k = 0, transfer_function='eisenstein_hu') #ccl_cosmo_set_high_prec (cosmo_ccl) cosmo_numcosmo, dist, ps_lin, ps_nln, hmfunc = create_nc_obj (cosmo_ccl) psf = hm...
11,765
Given the following text description, write Python code to implement the functionality described below step by step Description: Limpieza de datos sobre edificios con certificacion LEED 1. Introduccion EL United States Green Building Council (USGBG) tiene una base de datos de edificios que cuentan con certificación LE...
Python Code: # Librerias utilizadas import pandas as pd import sys import os import csv from lxml import html import requests import time # Configuracion del sistema print('Python {} on {}'.format(sys.version, sys.platform)) print('Pandas version: {}'.format(pd.__version__)) import platform; print('Running on {} {}'.fo...
11,766
Given the following text description, write Python code to implement the functionality described below step by step Description: Ronica Reddick & Nick Pulito in association with "Those Data Bootcamp Guys" -- Professors Backus and Coleman present "3 Guys Named Chris" Scene 1 Step1: Scene 2 Step2: Chris Hemsworth “The...
Python Code: #This guided coding excercise requires associated .csv files: CE1.csv, CH1.csv, CP1.csv, Arnold1.csv, Bruce1.csv, and Tom1.csv #make sure you have these supplemental materials ready to go in your active directory before proceeding #Let's start coding! We first need to make sure our preliminary packages are...
11,767
Given the following text description, write Python code to implement the functionality described below step by step Description: property Python has a great concept called property, which makes the life of an object oriented programmer much simpler. Before defining and going into details of what a property in Python i...
Python Code: CONST = 10 # some constant class Weather_balloon(): temp = 222 def convert_temp_to_f(self): return self.temp * CONST w = Weather_balloon() w.temp = 122 print(w.convert_temp_to_f()) class Circle(): area = None radius = None def __init__(self, radius): self.radiu...
11,768
Given the following text description, write Python code to implement the functionality described below step by step Description: MLE 모수 추정의 예 베르누이 분포의 모수 추정 이 과정을 스스로 쓸 줄 알아야 돼 각각의 시도 $x_i$에 대한 확률은 베르누이 분포 $$ P(x | \theta ) = \text{Bern}(x | \theta ) = \theta^x (1 - \theta)^{1-x}$$ 샘플이 $N$개 있는 경우, Likelihood $$ L = P(...
Python Code: theta0 = 0.6 x = sp.stats.bernoulli(theta0).rvs(1000) N0, N1 = np.bincount(x, minlength=2) N = N0 + N1 theta = N1 / N theta Explanation: MLE 모수 추정의 예 베르누이 분포의 모수 추정 이 과정을 스스로 쓸 줄 알아야 돼 각각의 시도 $x_i$에 대한 확률은 베르누이 분포 $$ P(x | \theta ) = \text{Bern}(x | \theta ) = \theta^x (1 - \theta)^{1-x}$$ 샘플이 $N$개 있는 경우, ...
11,769
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...
11,770
Given the following text description, write Python code to implement the functionality described below step by step Description: Krisk also introduced a very simplistic for you to resync data or create a reproducible charts. Consider this plot, Step1: Executing this code below Step2: Would let you to modify the plot...
Python Code: p = kk.bar(df[df.year == 1952],'continent',y='pop', how='mean') p.set_size(width=800) Explanation: Krisk also introduced a very simplistic for you to resync data or create a reproducible charts. Consider this plot, End of explanation p.resync_data(df[df.year == 2007]) Explanation: Executing this code below...
11,771
Given the following text description, write Python code to implement the functionality described below step by step Description: Excercises Electric Machinery Fundamentals Chapter 5 Problem 5-2 Step1: Description Assume that the motor of Problem 5-1 is operating at rated conditions. Step2: (a) What are the magnitude...
Python Code: %pylab notebook %precision %.4g import cmath Explanation: Excercises Electric Machinery Fundamentals Chapter 5 Problem 5-2 End of explanation Vt = 480 # [V] PF = 0.8 fse = 60 # [Hz] p = 8.0 Pout = 400 * 746 # [W] Xs = 0.6 # [Ohm] Explanation: Description Assume that the mot...
11,772
Given the following text description, write Python code to implement the functionality described below step by step Description: Dimensionality Reduction The sheer size of data in the modern age is not only a challenge for computer hardware but also a main bottleneck for the performance of many machine learning algori...
Python Code: import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter import numpy as np import pandas as pd import seaborn as sns import sklearn from sklearn import datasets from sklearn.decomposition import PCA from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_int...
11,773
Given the following text description, write Python code to implement the functionality described below step by step Description: Introdução ao Numpy master Step1: Observe que mesmo no retorno de uma função, a cópia explícita pode não acontecer. Veja o exemplo a seguir de uma função que apenas retorna a variável de en...
Python Code: import numpy as np a = np.arange(6) b = a print "a =\n",a print "b =\n",b b.shape = (2,3) # mudança no shape de b, print "\na shape =",a.shape # altera o shape de a b[0,0] = -1 # mudança no conteúdo de b print "a =\n",a ...
11,774
Given the following text description, write Python code to implement the functionality described below step by step Description: Nursery School Dataset Team Members Sharan Srikanth Kalyan Nursery Database was derived from a hierarchical decision model originally developed to rank applications for nursery schools. It w...
Python Code: # Importing the libraries which we need now. import pandas from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt %matplotlib inline # Dataset from - https://archive.ics.uci.edu/ml/datasets/Nursery df = pandas.read_table('nursery.txt', sep=',', header=None, names=['parents', 'has_nurs',...
11,775
Given the following text description, write Python code to implement the functionality described below step by step Description: Connecting Job Titles by Their Similarity Scores Step1: Data loading Step2: After fixing some bugs with parsing job titles, we re-parsed job titles with problem by title_parse.py script. T...
Python Code: import my_util as my_util; from my_util import * import cluster_skill_helpers as cluster_skill_helpers from cluster_skill_helpers import * import os import random from time import time import gc # Turn on auto garbage collection gc.enable() HOME_DIR = 'd:/larc_projects/job_analytics/' DATA_DIR = HOME_DIR +...
11,776
Given the following text description, write Python code to implement the functionality described below step by step Description: Будем совсем неразумно обучаться на всем train'е, так как тогда мы переобучимся, то есть наш алгоритм "подгониться" под закономерности, присущие только train'у, а на реальных данных будет не...
Python Code: # Выделяем outdoor'ы и indoor'ы. sample_out = sample[result[:, 0] == 1] sample_in = sample[result[:, 1] == 1] result_out = result[result[:, 0] == 1] result_in = result[result[:, 1] == 1] # Считаем размер indoor- и outdoor-частей в train'е. train_size_in = int(sample_in.shape[0] * 0.75) train_size_out = int...
11,777
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Exo from 'Intro to Pandas' Step1: we decide to only take the 'confirmed' cases and not the suspected or probable ones since 'suspected' and 'probable' are very subjective terms and...
Python Code: # load all data and parse the 'date' column def load_data(): sl_files=glob.glob('Data/ebola/sl_data/*.csv') guinea_files=glob.glob('Data/ebola/guinea_data/*.csv') liberia_files=glob.glob('Data/ebola/liberia_data/*.csv') sl = pd.concat((pd.read_csv(file, parse_dates=['date']) for file in sl...
11,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Please find torch implementation of this notebook here Step1: Get data We use a binarized version of MNIST. Step2: Training Step3: We use add-one smoothing for class conditional Bernoulli...
Python Code: import numpy as np try: import torchvision except ModuleNotFoundError: %pip install -qq torchvision import torchvision import jax import jax.numpy as jnp import matplotlib.pyplot as plt !mkdir figures # for saving plots key = jax.random.PRNGKey(1) # helper function to show images def show_image...
11,779
Given the following text description, write Python code to implement the functionality described below step by step Description: <p> <img src="http Step1: Step2: know the difference Let ${y_{n}}{n\in\mathbb{N}}$ be a sequence, where $y{n}=f(n)$ for some function $f$. Assume that each coefficient $y_{n}$ is not know...
Python Code: from sympy import * from sympy.abc import n, i, N, x, k, y init_printing() %run src/commons.py Explanation: <p> <img src="http://www.cerm.unifi.it/chianti/images/logo%20unifi_positivo.jpg" alt="UniFI logo" style="float: left; width: 20%; height: 20%;"> <div align="right"> Massimo Nocentini<br> <sm...
11,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Cloud Computing Basics What is Cloud Computing? On-demand services, delivered over the network. Relevant Services Step1: Setting up a Cloud Service Step2: Create Storage Account Step3: Wo...
Python Code: # standard library import os import time import shutil # Load Python SDK from azure import * from azure.servicemanagement import * from azure.storage import * # Subscription details subscription_id = '1a61650c-ada5-4173-a8da-2a4ffcfab747' certificate_path = 'mycert.pem' # Initialize connection sms = Servi...
11,781
Given the following text description, write Python code to implement the functionality described below step by step Description: PyGeM Tutorial 1 Step1: We need to read a parameters file. If does not exist the FFDParameters() class creates a default prm file that you have to edit for your problem specifications. Step...
Python Code: %matplotlib inline import pygem as pg Explanation: PyGeM Tutorial 1: Free Form Deformation on a sphere in stl file format In this tutorial we will show the typical workflow. In particular we are going to parse the parameters file for the FFD, read an stl file of a sphere, perform the FFD and write the resu...
11,782
Given the following text description, write Python code to implement the functionality described below step by step Description: <br><p style="font-family Step1: This is a really large dataset, at least in terms of the number of rows. But with 6 columns, what does this hold? Step2: Looks like it has different indic...
Python Code: import pandas as pd import numpy as np import random import matplotlib.pyplot as plt data = pd.read_csv(r'C:\Users\hrao\Documents\Personal\HK\Python\world-development-indicators\Indicators.csv') data.shape Explanation: <br><p style="font-family: Arial; font-size:3.75em;color:purple; font-style:bold"> Matpl...
11,783
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I'm trying to create a 2-dimensional array in Scipy/Numpy where each value represents the Manhattan distance from the center. It's supposed to have the same shape as the first two d...
Problem: import numpy as np from scipy.spatial import distance shape = (6, 6) xs, ys = np.indices(shape) xs = xs.reshape(shape[0] * shape[1], 1) ys = ys.reshape(shape[0] * shape[1], 1) X = np.hstack((xs, ys)) mid_x, mid_y = (shape[0]-1)/2.0, (shape[1]-1)/2.0 result = distance.cdist(X, np.atleast_2d([mid_x, mid_y]), 'mi...
11,784
Given the following text description, write Python code to implement the functionality described below step by step Description: CORDEX ESGF submission form General Information Data to be submitted for ESGF data publication must follow the rules outlined in the Cordex Archive Design Document <br /> (https Step1: S...
Python Code: from dkrz_forms import form_widgets form_widgets.show_status('form-submission') Explanation: CORDEX ESGF submission form General Information Data to be submitted for ESGF data publication must follow the rules outlined in the Cordex Archive Design Document <br /> (https://verc.enes.org/data/projects/doc...
11,785
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas Visualization Step1: DataFrame.plot Step2: We can select which plot we want to use by passing it into the 'kind' parameter. Step3: You can also choose the plot kind by using the Da...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib notebook # see the pre-defined styles provided. plt.style.available # use the 'seaborn-colorblind' style plt.style.use('seaborn-colorblind') Explanation: Pandas Visualization End of explanation np.random.seed(123) df = pd.Da...
11,786
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating Customer Segments In this project you, will analyze a dataset containing annual spending amounts for internal structure, to understand the variation in the different types of custom...
Python Code: import warnings warnings.filterwarnings('ignore') # Import libraries: NumPy, pandas, matplotlib import numpy as np import pandas as pd import matplotlib.pyplot as plt # Tell iPython to include plots inline in the notebook %matplotlib inline # Read dataset data = pd.read_csv("wholesale-customers.csv") print...
11,787
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Preprocessing using Cloud Dataflow </h1> <h2>Learning Objectives</h2> <ol> <li>Create ML dataset using <a href="https Step1: After installing Apache Beam, restart your kernel by se...
Python Code: %pip install apache-beam[gcp]==2.13.0 Explanation: <h1> Preprocessing using Cloud Dataflow </h1> <h2>Learning Objectives</h2> <ol> <li>Create ML dataset using <a href="https://cloud.google.com/dataflow/">Cloud Dataflow</a></li> <li>Simulate a dataset where no ultrasound is performed (i.e. male or femal...
11,788
Given the following text description, write Python code to implement the functionality described below step by step Description: Load the spectroscopic data Step1: Hmm, the specobjid's are floats, but they should be integers to avoid possible rounding errors during comparison. Lets fix that Step2: Find matches Firs...
Python Code: spec_data_raw = table.Table.read('SAGADropbox/data/saga_spectra_raw.fits.gz') spec_data_raw Explanation: Load the spectroscopic data End of explanation # Just setting the dtype does *not* do the conversion of the values. It instead tells numpy to # re-interpret the same set of bits as thought they were i...
11,789
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup Step1: Periodic Yield The thread periodic_yeild is woken up at 30ms intervals where it calls sched_yield and relinquishes its time-slice. The expectation is that the task will have a ...
Python Code: from trappy.stats.Topology import Topology from bart.sched.SchedMultiAssert import SchedMultiAssert from bart.sched.SchedAssert import SchedAssert import trappy import os import operator import json #Define a CPU Topology (for multi-cluster systems) BIG = [1, 2] LITTLE = [0, 3, 4, 5] CLUSTERS = [BIG, LITTL...
11,790
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id="top"></a> UN SDG Indicator 6.6.1 Step1: <a id="plat_prod"></a>Choose Platforms and Products &#9652; List available products for each platform Step2: Choose products Step3: <a id="e...
Python Code: # Supress Warning import warnings warnings.filterwarnings('ignore') %matplotlib inline import warnings import matplotlib.pyplot as plt # Allow importing of our utilities. import sys import os sys.path.append(os.environ.get('NOTEBOOK_ROOT')) # Import the datacube and the API import datacube from utils.data...
11,791
Given the following text description, write Python code to implement the functionality described below step by step Description: Explicit 2D Benchmarks This file demonstrates how to generate, plot, and output data for 1d benchmarks Choose from Step1: Generate the data with noise Step2: Plot inline and save image Ste...
Python Code: from pypge.benchmarks import explicit import numpy as np # visualization libraries import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import gridspec # plot the visuals in ipython %matplotlib inline Explanation: Explicit 2D Benchmarks This file demonstrates how to gener...
11,792
Given the following text description, write Python code to implement the functionality described below step by step Description: Step4: Improving the Search Index (Inspired by and borrowed heavily from Step5: Stemming As we could see from the results of the last assignment, our simple index doesn't handle punctuation...
Python Code: import pickle, bz2, re from collections import namedtuple, defaultdict, Counter from IPython.display import display, HTML from math import log10 Summaries_file = 'data/air__Summaries.pkl.bz2' Abstracts_file = 'data/air__Abstracts.pkl.bz2' Summaries = pickle.load( bz2.BZ2File( Summaries_file, 'rb' ) ) Abstr...
11,793
Given the following text description, write Python code to implement the functionality described below step by step Description: Constraint Satisfaction Problems (CSPs) This IPy notebook acts as supporting material for topics covered in Chapter 6 Constraint Satisfaction Problems of the book Artificial Intelligence Ste...
Python Code: from csp import * Explanation: Constraint Satisfaction Problems (CSPs) This IPy notebook acts as supporting material for topics covered in Chapter 6 Constraint Satisfaction Problems of the book Artificial Intelligence: A Modern Approach. We make use of the implementations in csp.py module. Even though this...
11,794
Given the following text description, write Python code to implement the functionality described below step by step Description: Template Scan Analysis This notebook is the 2nd part of the template scan analysis. Its input are the output files of the template_scan_analysis.sh shell script, which is simply a little scr...
Python Code: ls template_scan_dac_*.h5 Explanation: Template Scan Analysis This notebook is the 2nd part of the template scan analysis. Its input are the output files of the template_scan_analysis.sh shell script, which is simply a little script calling the digicam-template command on a defined set of raw-data files fo...
11,795
Given the following text description, write Python code to implement the functionality described below step by step Description: Exports nodes and edges from tweets (Retweets, Mentions, or Replies) [CSV] Exports nodes and edges from tweets (either from retweets or mentions) in json format that can be exported from SFM...
Python Code: import sys import json import re import numpy as np from datetime import datetime import pandas as pd tweetfile = '/home/soominpark/sfmproject/Work/Network Graphs/food_security.csv' tweets = pd.read_csv(tweetfile) Explanation: Exports nodes and edges from tweets (Retweets, Mentions, or Replies) [CSV] Exp...
11,796
Given the following text description, write Python code to implement the functionality described below step by step Description: Natural Language Processing in a Kaggle Competition Step1: Now set up our function. This will clean all of the reviews for us. Step2: Great! Now it is time to go ahead and load our data in...
Python Code: import re from bs4 import BeautifulSoup Explanation: Natural Language Processing in a Kaggle Competition: Movie Reviews <img src='Movie_thtr.jpg', width = 800, height = 600> Source I decided to try playing around with a Kaggle competition. In this case, I entered the "When bag of words meets bags of popco...
11,797
Given the following text description, write Python code to implement the functionality described below step by step Description: Why Objects? Provide modularity and reuse through hierarchical structures Object oriented programming is a different way of thinking. Programming With Objects Step1: Initial concepts An obj...
Python Code: from IPython.display import Image Image(filename='Classes_vs_Objects.png') Explanation: Why Objects? Provide modularity and reuse through hierarchical structures Object oriented programming is a different way of thinking. Programming With Objects End of explanation # Definiting a Car class class Car(objec...
11,798
Given the following text description, write Python code to implement the functionality described below step by step Description: Scikit-Learn 朴素贝叶斯分类 朴素贝叶斯分类是机器学习中常见的分类方法之一,本节将带大家深入学习一下 Scikit-Learn 中朴素贝叶斯分类工具包的相关使用方法。 首先,我们导入相关的库,并构建第一个示例数据集: Step1: Scikit-Learn 中的 make_blobs 方法常被用来生成聚类算法的测试数据,直观地说,make_blobs 会根据用户指...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set() from sklearn.datasets import make_blobs X, y = make_blobs(100, 2, centers=2, random_state=2, cluster_std=1.5) plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='RdBu'); Explanation: Scikit-Learn 朴素贝叶斯分类 朴素贝叶斯...
11,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Vectorization and JIT compilation in Python Examples for the QuantEcon 2017 PhD workshops John Stachurski Step1: Problem 1 Step2: Here's a typical time series Step3: Here's a function tha...
Python Code: import numpy as np from numba import vectorize, jit, float64 from quantecon.util import tic, toc import matplotlib.pyplot as plt Explanation: Vectorization and JIT compilation in Python Examples for the QuantEcon 2017 PhD workshops John Stachurski End of explanation α = 4 Explanation: Problem 1: A Time Ser...