Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
100
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow, Mini-Batch/Stochastic GradientDescent With Moment Step1: Input Generamos la muestra de grado 5 Step2: Problema Calcular los coeficientes que mejor se ajusten a la muestra sabie...
Python Code: import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) %matplotlib inline import sys import time from IPython.display import Image sys.path.append('/home/pedro/git/ElCuadernillo/ElCuadernillo/20160301_TensorFlowGradientDescentWithMomentum'...
101
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
102
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the Licens...
Python Code: import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd Explanation: Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at ht...
103
Given the following text description, write Python code to implement the functionality described below step by step Description: Jupyter Notebooks Share the compute process with everyone How to Install pip3 install jupyter How to Run jupyter notebook Uses PDF books Blog posts Inline graphics Multiple languages availab...
Python Code: %%%timeit maths = list() for x in range(10): maths.append(x**x) %%%timeit maths = [x**x for x in range(10)] # maths Explanation: Jupyter Notebooks Share the compute process with everyone How to Install pip3 install jupyter How to Run jupyter notebook Uses PDF books Blog posts Inline graphics Multiple ...
104
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"). DCGAN Step1: Import TensorFlow and enable eager execution Step2: Load the dataset We ...
Python Code: # to generate gifs !pip install imageio Explanation: Copyright 2018 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"). DCGAN: An example with tf.keras and eager <table class="tfo-notebook-buttons" align="left"><td> <a target="_blank" href="https://colab.research.google...
105
Given the following text description, write Python code to implement the functionality described below step by step Description: My First Query One of the most powerful features of Marvin 2.0 is ability to query the newly created DRP and DAP databases. You can do this in two ways Step1: Let's search for galaxies with...
Python Code: # Python 2/3 compatibility from __future__ import print_function, division, absolute_import from marvin import config config.mode = 'remote' config.setRelease('MPL-4') from marvin.tools.query import Query Explanation: My First Query One of the most powerful features of Marvin 2.0 is ability to query the ne...
106
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', 'bnu', 'bnu-esm-1-1', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: BNU Source ID: BNU-ESM-1-1 Topic: Ocean Sub-Topics: Timestepping Framework, ...
107
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Create a TFX pipeline using templates with Local orchestrator <div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="lef...
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...
108
Given the following text description, write Python code to implement the functionality described below step by step Description: Indexing and Selection | Operation | Syntax | Result | |-------------------------------|----------------|-----------| | Select column | df[col]...
Python Code: import pandas as pd import numpy as np produce_dict = {'veggies': ['potatoes', 'onions', 'peppers', 'carrots'],'fruits': ['apples', 'bananas', 'pineapple', 'berries']} produce_df = pd.DataFrame(produce_dict) produce_df Explanation: Indexing and Selection | Operation | Syntax | R...
109
Given the following text description, write Python code to implement the functionality described below step by step Description: Breadth First Search, Queue Based Implementation Implementation deque is the constructor for a double ended queue. Step1: The function search takes three arguments to solve a search problem...
Python Code: from collections import deque Explanation: Breadth First Search, Queue Based Implementation Implementation deque is the constructor for a double ended queue. End of explanation def search(start, goal, next_states): Frontier = deque([start]) Parent = { start: start } while Frontier: st...
110
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.data - Matplotlib Tutoriel sur matplotlib. Step1: Aparté Les librairies de visualisation en python se sont beaucoup développées (10 plotting librairies). La référence reste matplotlib, ...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 2A.data - Matplotlib Tutoriel sur matplotlib. End of explanation #Pour intégrer les graphes à votre notebook, il suffit de faire %matplotlib inline #ou alors %pylab inline #pylab charge également numpy. C'est la commande du calcul...
111
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep learning loss functions Inline plots Step1: We want to use Theano so that we can use it's auto-differentiation, since I'm too lazy to work out the derivatives of these functions by han...
Python Code: %matplotlib inline Explanation: Deep learning loss functions Inline plots: End of explanation import os import numpy as np import pandas as pd import torch, torch.nn as nn, torch.nn.functional as F from matplotlib import pyplot as plt import seaborn as sns sns.set() EPSILON = 1.0e-12 SAVE_PLOTS = True Expl...
112
Given the following text description, write Python code to implement the functionality described below step by step Description: Graded = 7/8 Step1: & for multiple parameters Step2: 2) What genres are most represented in the search results? Edit your previous printout to also display a list of their genres in the fo...
Python Code: import requests response = requests.get('https://api.spotify.com/v1/search?query=lil&type=artist&market=US&limit=50') Explanation: Graded = 7/8 End of explanation data = response.json() data.keys() artist_data = data['artists'] artist_data.keys() lil_names = artist_data['items'] #lil_names = list of dictio...
113
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 4 Step1: Load dataset Step2: Figure 4.1 - Default data set Step3: 4.3 Logistic Regression Figure 4.2 Step4: Table 4.1 Step5: scikit-learn Step6: statsmodels Step7: Table 4.2 Step8...
Python Code: # %load ../standard_import.txt import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import sklearn.linear_model as skl_lm from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import Quadratic...
114
Given the following text description, write Python code to implement the functionality described below step by step Description: Filtragem no domínio da frequência As operações de filtragem podem ser realizadas tanto no domínio do espaço quanto de frequência, Os filtros em frequência são normalmente classificados em tr...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import scipy.signal as sci from numpy.fft import fft2, ifft2 import sys,os ia898path = os.path.abspath('../../') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia f = mpi...
115
Given the following text description, write Python code to implement the functionality described below step by step Description: Tvorba obchodní strategie - křížení klouzavých průměrů Informace o notebooku a modulech Step1: Rychlý přehled základních běžných typů strategií Pro automatické obchodování, které využívá an...
Python Code: NB_VERSION = 1,0 import sys import datetime import numpy as np import pandas as pd import pandas_datareader as pdr import pandas_datareader.data as pdr_web import quandl as ql from matplotlib import __version__ as matplotlib_version from seaborn import __version__ as seaborn_version import statsmodels.api ...
116
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: # You can use any Python source file as a module by executing an import statement in some other Python source file. # The import statement combines two operations; it searches for the named module, then it binds the # results of that search to a name in the local scope. import functools import numpy as np ...
117
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem set 3 (90 pts) Important note Step1: Algorithm must halt before num_iter_fix + num_iter_adapt iterations if the following condition is satisfied $$ \boxed{\|\lambda_k - \lambda_{k-1...
Python Code: import numpy as np import scipy as sp from scipy import sparse from scipy.sparse import linalg import networkx as nx from networkx.linalg.algebraicconnectivity import fiedler_vector import matplotlib.pyplot as plt # INPUT: # A - adjacency matrix (scipy.sparse.csr_matrix) # num_iter_fix - number of iteratio...
118
Given the following text description, write Python code to implement the functionality described below step by step Description: Red Hat Insights Core Insights Core is a framework for collecting and processing data about systems. It allows users to write components that collect and transform sets of raw data into type...
Python Code: import sys sys.path.insert(0, "../..") from insights.core import dr # Here's our component type with the clever name "component." # Insights Core provides several types that we'll come to later. class component(dr.ComponentType): pass Explanation: Red Hat Insights Core Insights Core is a framework for ...
119
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook was created by Mykola Veremchuk (mykola.veremchuk@xfel.eu), Svitozar Serkez. Source and license info is on GitHub. June 2019. PFS tutorial N4. Converting synchrotron radiation ...
Python Code: import numpy as np import logging from ocelot import * from ocelot.rad import * from ocelot.optics.wave import dfl_waistscan, screen2dfl, RadiationField from ocelot.gui.dfl_plot import plot_dfl, plot_dfl_waistscan from ocelot import ocelog ocelog.setLevel(logging.ERROR) #suppress logger output # Activate i...
120
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Statistical inference and Estimation Theory Motivation Much of data science and machine learning (ML) is concerned with estimation Step2: Now let us import some Python libraries an...
Python Code: # Copyright (c) Thalesians Ltd, 2018-2019. All rights reserved # Copyright (c) Paul Alexander Bilokon, 2018-2019. All rights reserved # Author: Paul Alexander Bilokon <paul@thalesians.com> # Version: 1.1 (2019.01.24) # Previous versions: 1.0 (2018.08.31) # Email: paul@thalesians.com # Platform: Tested on W...
121
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'pcmdi', 'sandbox-3', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: PCMDI Source ID: SANDBOX-3 Topic: Ocnbgchem Sub-Topics: Tracers. Pr...
122
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.algo - La distance d'édition (correction) Correction. Step1: Exercice 1 Step2: Exercice 2 Step3: Que se passe-t-il lorsqu'on enlève la condition or min(len(m1), len(m2)) &lt;= 1 ? ve...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() def dist_hamming(m1,m2): d = 0 for a,b in zip(m1,m2): if a != b : d += 1 return d dist_hamming("close", "cloue") Explanation: 1A.algo - La distance d'édition (correction) Correction. End of explanation def dist...
123
Given the following text description, write Python code to implement the functionality described below step by step Description: Evolution d'indicateurs dans les communes Step1: Jointure entre 2 fichiers Step2: Il y a bien les colonnes "status", "mean_altitude", "superficie", "is_metropole" et "metropole_name" Nom...
Python Code: commune_metropole = pd.read_csv('data/commune_metropole.csv', encoding='utf-8') commune_metropole.shape commune_metropole.head() insee = pd.read_csv('data/insee.csv', sep=";", # séparateur du fichier dtype={'COM' : np.dtype(str)}, # On force la ...
124
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Load software and filenames definitions Step2: Data folder Step3: List of data files Step4: Data load Initial loading of the data Step5: Laser alternation selection At t...
Python Code: ph_sel_name = "all-ph" data_id = "7d" # ph_sel_name = "all-ph" # data_id = "7d" Explanation: Executed: Mon Mar 27 11:34:11 2017 Duration: 8 seconds. usALEX-5samples - Template This notebook is executed through 8-spots paper analysis. For a direct execution, uncomment the cell below. End of explanation from...
125
Given the following text description, write Python code to implement the functionality described below step by step Description: Spectral Clustering Algorithms Notebook version Step1: 1. Introduction The key idea of spectral clustering algorithms is to search for groups of connected data. I.e, rather than pursuing co...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats # use seaborn plotting defaults import seaborn as sns; sns.set() from sklearn.cluster import KMeans from sklearn.datasets.samples_generator import make_blobs, make_circles from sklearn.utils import shuffle from sk...
126
Given the following text description, write Python code to implement the functionality described below step by step Description: List manipulation in Python Goal for this assignment The goal for this assignment is to learn to use the various methods for Python's list data type. Your name // put your name here! Part 1 ...
Python Code: even_numbers = [2, 4, 6, 8, 10, 12, 14] s1 = even_numbers[1:5] # returns the 2nd through 4th elements print("s1:", s1) s2 = even_numbers[2:] # returns the 3rd element thorugh the end print("s2:", s2) s3 = even_numbers[:-2] # returns everything but the last two elements print("s3:", s3) s4 = even_number...
127
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 1 of 3 Step1: A detailed tutorial on dictionaries can be found here. The dict does not offer much functionality aside from basic storage of arbitrary objects, and it is meant to b...
Python Code: foo = dict() # Create an empty dict foo['bar'] = 1 # Store an integer under the key 'bar' print(foo['bar']) # Retrieve the integer stored in 'bar' Explanation: Tutorial 1 of 3: Getting Started with OpenPNM This tutorial is intended to show the basic outline of how OpenPNM works, and necessarily ...
128
Given the following text description, write Python code to implement the functionality described below step by step Description: Autoencoder This notebook demonstrates the invocation of the SystemML autoencoder script, and alternative ways of passing in/out data. This notebook is supported with SystemML 0.14.0 and abo...
Python Code: !pip show systemml import pandas as pd from systemml import MLContext, dml ml = MLContext(sc) print(ml.info()) sc.version Explanation: Autoencoder This notebook demonstrates the invocation of the SystemML autoencoder script, and alternative ways of passing in/out data. This notebook is supported with Syste...
129
Given the following text description, write Python code to implement the functionality described below step by step Description: #0 Journal paper critique <center> <img src=hw_2_data/bale_2005.png width="400"></img> <img src=hw_2_data/bale_2005_caption.png width="400"></img> </center> The figure trying to three messag...
Python Code: from bokeh.plotting import figure, output_notebook, show from bokeh.models import HoverTool from bokeh.layouts import row import numpy as np output_notebook() Explanation: #0 Journal paper critique <center> <img src=hw_2_data/bale_2005.png width="400"></img> <img src=hw_2_data/bale_2005_caption.png width="...
130
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I want to process a gray image in the form of np.array.
Problem: import numpy as np im = np.array([[0,0,0,0,0,0], [0,0,5,1,2,0], [0,1,8,0,1,0], [0,0,0,7,1,0], [0,0,0,0,0,0]]) mask = im == 0 rows = np.flatnonzero((~mask).sum(axis=1)) cols = np.flatnonzero((~mask).sum(axis=0)) if rows.shape[0] == 0: result = np.a...
131
Given the following text description, write Python code to implement the functionality described below step by step Description: Enhanced Deep Residual Networks for single-image super-resolution Author Step1: Download the training dataset We use the DIV2K Dataset, a prominent single-image super-resolution dataset wit...
Python Code: import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import matplotlib.pyplot as plt from tensorflow import keras from tensorflow.keras import layers AUTOTUNE = tf.data.AUTOTUNE Explanation: Enhanced Deep Residual Networks for single-image super-resolution Author: Gitesh Chawda<br>...
132
Given the following text description, write Python code to implement the functionality described below step by step Description: Fire up graphlab create Step1: Load some house value vs. crime rate data Dataset is from Philadelphia, PA and includes average house sales price in a number of neighborhoods. The attribute...
Python Code: import graphlab Explanation: Fire up graphlab create End of explanation sales = graphlab.SFrame.read_csv('Philadelphia_Crime_Rate_noNA.csv/') sales Explanation: Load some house value vs. crime rate data Dataset is from Philadelphia, PA and includes average house sales price in a number of neighborhoods. T...
133
Given the following text description, write Python code to implement the functionality described below step by step Description: Robust Kalman filtering for vehicle tracking We will try to pinpoint the location of a moving vehicle with high accuracy from noisy sensor data. We'll do this by modeling the vehicle state a...
Python Code: import matplotlib import matplotlib.pyplot as plt import numpy as np def plot_state(t,actual, estimated=None): ''' plot position, speed, and acceleration in the x and y coordinates for the actual data, and optionally for the estimated data ''' trajectories = [actual] if estimated is...
134
Given the following text description, write Python code to implement the functionality described below step by step Description: Energy Meter Examples Linux Kernel HWMon More details can be found at https Step1: Import required modules Step2: Target Configuration The target configuration is used to describe and conf...
Python Code: import logging from conf import LisaLogging LisaLogging.setup() Explanation: Energy Meter Examples Linux Kernel HWMon More details can be found at https://github.com/ARM-software/lisa/wiki/Energy-Meters-Requirements#linux-hwmon. End of explanation # Generate plots inline %matplotlib inline import os # Supp...
135
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
136
Given the following text description, write Python code to implement the functionality described below step by step Description: 2D Fast Accurate Fourier Transform with an extra gpu array for the 33th complex values Step1: Loading FFT routines Step2: Initializing Data Gaussian Step3: $W$ TRANSFORM FROM AXES-0 After...
Python Code: import numpy as np import ctypes from ctypes import * import pycuda.gpuarray as gpuarray import pycuda.driver as cuda import pycuda.autoinit from pycuda.compiler import SourceModule import matplotlib.pyplot as plt import matplotlib.mlab as mlab import math %matplotlib inline Explanation: 2D Fast Accura...
137
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of contents Mathematical Background The Null space and its orthogonal Probabilistic interpretation of the curvature Code documentation A convenient basis The Markov chain Computation o...
Python Code: import numpy as np, random, scipy.linalg Explanation: Table of contents Mathematical Background The Null space and its orthogonal Probabilistic interpretation of the curvature Code documentation A convenient basis The Markov chain Computation of the curvature Appendix Lemmas: the structure of zero modes Ma...
138
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to the jupyter notebook! To run any cell, press Shift+Enter or Ctrl+Enter. IMPORTANT Step1: Notebook Basics A cell contains any type of python inputs (expression, function definiti...
Python Code: # Useful starting lines %matplotlib inline import numpy as np import matplotlib.pyplot as plt %load_ext autoreload %autoreload 2 Explanation: Welcome to the jupyter notebook! To run any cell, press Shift+Enter or Ctrl+Enter. IMPORTANT : Please have a look at Help-&gt;User Interface Tour and Help-&gt;Keyboa...
139
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting Blood Donations Step1: Clean Data Are there any missing values? Step2: Visualize Data Table Step3: Insights from Summary stats table Step4: Plot data as a scatter plot (w/r 'M...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np data_dir = '../data/raw/' data_filename = 'blood_train.csv' df_blood = pd.read_csv(data_dir+data_filename) df_blood.head() Explanation: Predicting Blood Donations: Initial Data Exploration To do: - Import ...
140
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 4 Ryan Rose Scientific Computing 9/21/2016 Step1: Loading Fifty Books First, we load all fifty books from their text files. Step2: Cleaning up the Data Next, we create a mapping of tit...
Python Code: ## Imports! %matplotlib inline import os import re import string import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.mlab import PCA from scipy.cluster.vq import kmeans, vq Explanation: Lab 4 Ryan Rose Scientific Computing 9/21/2016 End of explanation os.chdir("/home/ryan...
141
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', 'mri', 'mri-esm2-0', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: MRI Source ID: MRI-ESM2-0 Topic: Ocean Sub-Topics: Timestepping Framework, Ad...
142
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 4 Imports Step2: Line with Gaussian noise Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from random import randint from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 4 Imports End of explanation def random_line(m, b, sigma, size=10): Create a ...
143
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading MDAnalysis Step1: The Universe The basic object to load structures and trajectories into MDAnalysis are Universes. Universe take a topology and a trajectory (optional) as arguments ...
Python Code: import MDAnalysis as mda mda.__version__ Explanation: Loading MDAnalysis End of explanation TOPOLOGY = 'data/adk.psf' u = mda.Universe(TOPOLOGY) Explanation: The Universe The basic object to load structures and trajectories into MDAnalysis are Universes. Universe take a topology and a trajectory (optional)...
144
Given the following text description, write Python code to implement the functionality described below step by step Description: Hosted Settings Step1: Part 1 Step2: Question 3.1. Some stufff <img src="https
Python Code: from client.api.notebook import Notebook ok = Notebook('ipy.ok') ok.auth(force=True) Explanation: Hosted Settings: In a hosted environment such as jupyterhub: - run pip install okpy&gt;=1.8.2 --upgrade Local Setting For Local Dev: run jupyter notebook from the root ok-client folder Running from a distr...
145
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of using pygosa We illustrate hereafter the use of the pygosa module. Step1: We define Sobol use-case, which is very common in case of sensitivity analysis Step2: Design of experim...
Python Code: import openturns as ot import numpy as np import pygosa %pylab inline Explanation: Example of using pygosa We illustrate hereafter the use of the pygosa module. End of explanation model = ot.SymbolicFunction(["x1","x2","x3"], ["sin(x1) + 7*sin(x2)^2 + 0.1*(x3^4)*sin(x1)"]) dist = ot.ComposedDistribution( 3...
146
Given the following text description, write Python code to implement the functionality described below step by step Description: <pre> 함수의 return은 오직 한개의 객체만 리턴한다. 보통 튜플로 리턴을 할 경우 여러개의 변수로 한번에 받게 할 수 있어 마치 return이 여러개의 값을 동시에 리턴하는 것처럼 보이지만 튜플이라는 객체 하나를 리턴하는 것이다. </pre> Step1: 함수가 생성되면 함수 자체도 객체이다. 그리고 그객체의 주소를 swap라...
Python Code: def swap(a,b): return b,a #튜플이 반환된다. a = 1 b = 2 a,b = swap(a,b) print(a,b) print(swap) Explanation: <pre> 함수의 return은 오직 한개의 객체만 리턴한다. 보통 튜플로 리턴을 할 경우 여러개의 변수로 한번에 받게 할 수 있어 마치 return이 여러개의 값을 동시에 리턴하는 것처럼 보이지만 튜플이라는 객체 하나를 리턴하는 것이다. </pre> End of explanation def intersect(prelist, postlist): re...
147
Given the following text description, write Python code to implement the functionality described below step by step Description: Сравнение S4G и 2MASS массовых моделей Идея в том, чтобы сравнить полные массы галактик из S4G и из 2MASS фотометрии, чтобы понять, почему диски так недооцениваются. Данные из https Step1: ...
Python Code: sun_abs_mags = {'U' : 5.61, 'B' : 5.48, 'V' : 4.83, 'R' : 4.42, 'I' : 4.08, 'J' : 3.64, 'H' : 3.32, 'K' : 3.28, '3.6' : 3.24, # Oh et al. 2008 'u' : 6.77, #SDSS ba...
148
Given the following text description, write Python code to implement the functionality described below step by step Description: Revision control software J.R. Johansson (jrjohansson at gmail.com) The latest version of this IPython notebook lecture is available at http Step1: In any software development, one of the m...
Python Code: from IPython.display import Image Explanation: Revision control software J.R. Johansson (jrjohansson at gmail.com) The latest version of this IPython notebook lecture is available at http://github.com/jrjohansson/scientific-python-lectures. The other notebooks in this lecture series are indexed at http://j...
149
Given the following text description, write Python code to implement the functionality described below step by step Description: 0. Preparation and setup One Python library that makes GraphX support available to our Jupyter notebooks is not yet bound to the runtime by default. To get it added to the Spark context you...
Python Code: !pip install --user --upgrade --no-deps pixiedust Explanation: 0. Preparation and setup One Python library that makes GraphX support available to our Jupyter notebooks is not yet bound to the runtime by default. To get it added to the Spark context you have to use the !pip magic cell command install first...
150
Given the following text description, write Python code to implement the functionality described below step by step Description: Tiingo-Python This notebook shows basic usage of the tiingo-python library. If you're running this on mybinder.org, you can run this code without installing anything on your computer. You ca...
Python Code: TIINGO_API_KEY = 'REPLACE-THIS-TEXT-WITH-A-REAL-API-KEY' # This is here to remind you to change your API key. if not TIINGO_API_KEY or (TIINGO_API_KEY == 'REPLACE-THIS-TEXT-WITH-A-REAL-API-KEY'): raise Exception("Please provide a valid Tiingo API key!") from tiingo import TiingoClient config = { 'a...
151
Given the following text description, write Python code to implement the functionality described below step by step Description: General info on the fullCyc dataset (as it pertains to SIPSim validation) Simulating 12C gradients Determining if simulated taxon abundance distributions resemble the true distributions Simu...
Python Code: %load_ext rpy2.ipython %%R workDir = '/home/nick/notebook/SIPSim/dev/fullCyc/' physeqDir = '/home/nick/notebook/SIPSim/dev/fullCyc_trim/' physeqBulkCore = 'bulk-core_trm' physeqSIP = 'SIP-core_unk_trm' ampFragFile = '/home/nick/notebook/SIPSim/dev/bac_genome1147/validation/ampFrags_kde.pkl' Explanation: Ge...
152
Given the following text description, write Python code to implement the functionality described below step by step Description: Here I'm process by chunks the entire region. Step1: Algorithm for processing Chunks Make a partition given the extent Produce a tuple (minx ,maxx,miny,maxy) for each element on the partiti...
Python Code: # Load Biospytial modules and etc. %matplotlib inline import sys sys.path.append('/apps') import django django.setup() import pandas as pd import numpy as np import matplotlib.pyplot as plt ## Use the ggplot style plt.style.use('ggplot') from external_plugins.spystats import tools %run ../testvariogram.py ...
153
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Project Step1: Read in an Image Step10: Ideas for Lane Detection Pipeline Some OpenCV functions (beyond those introduced in the lesson) that might be u...
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline import pdb Explanation: Self-Driving Car Engineer Nanodegree Project: Finding Lane Lines on the Road In this project, you will use the tools you learned about in...
154
Given the following text description, write Python code to implement the functionality described below step by step Description: Country Converter The country converter (coco) is a Python package to convert country names into different classifications and between different naming versions. Internally it uses regular e...
Python Code: import country_converter as coco converter = coco.CountryConverter() Explanation: Country Converter The country converter (coco) is a Python package to convert country names into different classifications and between different naming versions. Internally it uses regular expressions to match country names. ...
155
Given the following text description, write Python code to implement the functionality described below step by step Description: Case study Step1: 3. Normalization of dataset A with entry sensing Step2: 3. Normalization of dataset B with blind normalization
Python Code: # Setup of general parameters for the recovery experiment. n_restarts = 10 rank = 6 n_measurements = 2800 shape = (50, 70) # samples, features missing_fraction = 0.1 noise_amplitude = 2.0 m_blocks_size = 5 # size of each block correlation_threshold = 0.75 correlation_strength = 1.0 bias_model = 'image' # C...
156
Given the following text description, write Python code to implement the functionality described below step by step Description: Hand Following example In this notebook, you will use Pypot and an Inverse Kinematics toolbox to make Torso's hands follow each other. Your Torso has two arms, and you can use simple methods...
Python Code: import time import numpy as np from pypot.creatures import PoppyTorso Explanation: Hand Following example In this notebook, you will use Pypot and an Inverse Kinematics toolbox to make Torso's hands follow each other. Your Torso has two arms, and you can use simple methods to get and set the position of ea...
157
Given the following text description, write Python code to implement the functionality described below step by step Description: Tramp Steamer Problem Al Duke 3/11/2022 <p style="text-align Step1: I will encode the graph as a python dictionary. Each vertex is a key. The value for this key is another dictionary. Thi...
Python Code: graph = { "A": {"B": (12, 3), "C":(25, 6), }, "B": {"C": (11, 2), }, "C": {"A": (30, 6), "D": (16, 4), }, "D": {"A": (12, 2), }, } Explanation: Tramp Steamer Problem Al Duke 3/11/2022 <p style="text-align: center"> <b>Figure 1. Tramp Steamer</b> </p> Imagine you own a cargo ship that ...
158
Given the following text description, write Python code to implement the functionality described below step by step Description: Setting up a PEST interface from MODFLOW6 using the PstFrom class The PstFrom class is a generalization of the prototype PstFromFlopy class. The generalization in PstFrom means users need to...
Python Code: import os import shutil import numpy as np import pandas as pd import matplotlib.pyplot as plt import pyemu import flopy Explanation: Setting up a PEST interface from MODFLOW6 using the PstFrom class The PstFrom class is a generalization of the prototype PstFromFlopy class. The generalization in PstFrom me...
159
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize the hyperparameter tuning process Author Step1: Introduction KerasTuner prints the logs to screen including the values of the hyperparameters in each trial for the user to monitor...
Python Code: !pip install keras-tuner -q Explanation: Visualize the hyperparameter tuning process Author: Haifeng Jin<br> Date created: 2021/06/25<br> Last modified: 2021/06/05<br> Description: Using TensorBoard to visualize the hyperparameter tuning process in KerasTuner. End of explanation import numpy as np import k...
160
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 ...
161
Given the following text description, write Python code to implement the functionality described below step by step Description: Non-linear power flow after LOPF In this example, the dispatch of generators is optimised using the linear OPF, then a non-linear power flow is run on the resulting dispatch. Data sources Gr...
Python Code: import pypsa import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import cartopy.crs as ccrs %matplotlib inline network = pypsa.examples.scigrid_de(from_master=True) Explanation: Non-linear power flow after LOPF In this example, the dispatch of generators is optimised using the ...
162
Given the following text description, write Python code to implement the functionality described below step by step Description: 문서 전처리 모든 데이터 분석 모형은 숫자로 구성된 고정 차원 벡터를 독립 변수로 하고 있으므로 문서(document)를 분석을 하는 경우에도 숫자로 구성된 특징 벡터(feature vector)를 문서로부터 추출하는 과정이 필요하다. 이러한 과정을 문서 전처리(document preprocessing)라고 한다. BOW (Bag of W...
Python Code: from sklearn.feature_extraction.text import CountVectorizer corpus = [ 'This is the first document.', 'This is the second second document.', 'And the third one.', 'Is this the first document?', 'The last document?', ] vect = CountVectorizer() vect.fit(corpus) vect.vocabulary_ vect.t...
163
Given the following text description, write Python code to implement the functionality described below step by step Description: Euler's method We look at numerically solving differential equations. Most scientific software packages already include a wide variety of numerical integrators. Here we'll write our own simp...
Python Code: %matplotlib inline import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt def input(t): f = np.cos(t) return f def msd(state, t, m, c, k): x, xd = state pos_dot = xd vel_dot = 1/m*(input(t) - c*xd - k*x) state_dot = [pos_dot, vel_dot] return state_...
164
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Introduction to Tensors <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Tensors are multi-d...
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...
165
Given the following text description, write Python code to implement the functionality described below step by step Description: DAT210x - Programming with Python for DS Module5- Lab6 Step1: A Convenience Function This method is for your visualization convenience only. You aren't expected to know how to put this toge...
Python Code: import random, math import pandas as pd import numpy as np import scipy.io from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt matplotlib.style.use('ggplot') # Look Pretty # Leave this alone until indicated: Test_PCA = False Explanation: DAT210x - Programming with Python for DS Module5-...
166
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Linear Regression Step1: From Step2: Next, let's create vectors of our ages and heights. Step3: Now let's visualize our data to make sure that linear regression is appropriate fo...
Python Code: from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import math import numpy as np from thinkbayes2 import Pmf, Cdf, Suite, Joint, EvalNormalPdf import thinkplot import pandas as pd import matplotlib.pyplot as plt Explanation: Bayesian Linea...
167
Given the following text description, write Python code to implement the functionality described. Description: Find a triplet that sum to a given value returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Sort the elements ; Now fix the first element one by one and f...
Python Code: def find3Numbers(A , arr_size , sum ) : A . sort() for i in range(0 , arr_size - 2 ) : l = i + 1 r = arr_size - 1 while(l < r ) : if(A[i ] + A[l ] + A[r ] == sum ) : print("Triplet ▁ is ", A[i ] , ' , ▁ ' , A[l ] , ' , ▁ ' , A[r ] ) ; return True  elif(A[i ] + A[l ] + A[r ] < sum ) :...
168
Given the following text description, write Python code to implement the functionality described below step by step Description: 3 Types, Functions and Flow Control Data types Step1: Numbers Step2: If this should not make sense, you can print some documentation Step3: Strings Step4: Slicing Step5: String Operatio...
Python Code: x_int = 3 x_float = 3. x_string = 'three' x_list = [3, 'three'] type(x_float) type(x_string) type(x_list) Explanation: 3 Types, Functions and Flow Control Data types End of explanation abs(-1) import math math.floor(4.5) math.exp(1) math.log(1) math.log10(10) math.sqrt(9) round(4.54,1) Explanation: Numbers...
169
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Get the Data Step2: Get the regions and color them Step5: Build the plot We build it using html to use the html slider widget instead of the ipython widget. This makes the plot more...
Python Code: # Links via http://www.gapminder.org/data/ population_url = "http://spreadsheets.google.com/pub?key=phAwcNAVuyj0XOoBL_n5tAQ&output=xls" fertility_url = "http://spreadsheets.google.com/pub?key=phAwcNAVuyj0TAlJeCEzcGQ&output=xls" life_expectancy_url = "http://spreadsheets.google.com/pub?key=tiAiXcrneZrUnnJ9...
170
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Binary logistic regression using Sklearn Step2: PyTorch data and model Step3: BFGS Step4: SGD Step5: Momentum Step6: SPS
Python Code: !pip install git+https://github.com/IssamLaradji/sps.git import sklearn import scipy import scipy.optimize import matplotlib.pyplot as plt from mpl_toolkits import mplot3d from mpl_toolkits.mplot3d import Axes3D import seaborn as sns import warnings warnings.filterwarnings("ignore") import itertools import...
171
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Numerical Summaries of Data Congratulations, you have some data. Now what? Well, ideally, you'll have a research question to match. In practice, that's not always true or even possibl...
Python Code: import os import requests # get some CSV data from the SDSS SQL server URL = "http://skyserver.sdss.org/dr12/en/tools/search/x_sql.aspx" cmd = SELECT TOP 10000 p.u, p.g, p.r, p.i, p.z, s.class, s.z, s.zerr FROM PhotoObj AS p JOIN SpecObj AS s ON s.bestobjid = p.objid WHERE p.u BETWEEN 0 A...
172
Given the following text description, write Python code to implement the functionality described below step by step Description: Definition of model variables Model domain / grid parameters Step1: Definition of wave parameters Step2: Definition of sediment parameters Step3: Model initialisation function Loading the...
Python Code: file1='../data/gbr_south.csv' file2='../data/topoGBR1000.csv' # Bathymetric filename bfile = file1 # Resolution factor rfac = 4 Explanation: Definition of model variables Model domain / grid parameters End of explanation # Wave heights (m) H0 = 2 # Define wave source direction at boundary # (angle in degr...
173
Given the following text description, write Python code to implement the functionality described below step by step Description: Using FISSA with Suite2p suite2p is a blind source separation toolbox for cell detection and signal extraction. Here we illustrate how to use suite2p to detect cell locations, and then use ...
Python Code: # FISSA toolbox import fissa # suite2p toolbox import suite2p # For plotting our results, use numpy and matplotlib import matplotlib.pyplot as plt import numpy as np Explanation: Using FISSA with Suite2p suite2p is a blind source separation toolbox for cell detection and signal extraction. Here we illustr...
174
Given the following text description, write Python code to implement the functionality described below step by step Description: EITC Housing Benefits In this notebook, we try to estimate the cost of a hypothetical EITC program to aid with rental housing payments. The aim is to supply a family with enough EITC to have...
Python Code: ##Load modules and set data path: import pandas as pd import numpy as np import numpy.ma as ma import re data_path = "C:/Users/SpiffyApple/Documents/USC/RaphaelBostic/EITChousing" output_container = {} ################################################################# ################### load tax data #####...
175
Given the following text description, write Python code to implement the functionality described below step by step Description: <hr> <h1>Predicting Benign and Malignant Classes in Mammograms Using Thresholded Data</h1> <p>Jay Narhan</p> June 2017 This is an application of the best performing models but using threshol...
Python Code: import os import sys import time import numpy as np from tqdm import tqdm import sklearn.metrics as skm from sklearn import metrics from sklearn.svm import SVC from sklearn.model_selection import train_test_split from skimage import color import keras.callbacks as cb import keras.utils.np_utils as np_utils...
176
Given the following text description, write Python code to implement the functionality described below step by step Description: Fast chem_evol Created by Benoit Côté This notebook presents and tests the pre_calculate_SSPs implementation in chem_evol.py. When many timesteps are required in OMEGA, the computational ti...
Python Code: import matplotlib import matplotlib.pyplot as plt import numpy as np from NuPyCEE import omega from NuPyCEE import sygma Explanation: Fast chem_evol Created by Benoit Côté This notebook presents and tests the pre_calculate_SSPs implementation in chem_evol.py. When many timesteps are required in OMEGA, the...
177
Given the following text description, write Python code to implement the functionality described below step by step Description: The Flint, MI water crisis - part II Student names Type the names of everybody in your group here! Learning Goals (why are we asking you to do this?) As discussed in last class, there are tw...
Python Code: # THIS CELL READS IN THE FLINT DATASET - DO NOT CHANGE ANYTHING! # Make plots inline %matplotlib inline # Make inline plots vector graphics instead of raster graphics from IPython.display import set_matplotlib_formats set_matplotlib_formats('pdf', 'svg') # import modules for plotting and data analysis impo...
178
Given the following text description, write Python code to implement the functionality described below step by step Description: Encoder-Decoder Analysis Model Architecture Step1: Perplexity on Each Dataset Step2: Loss vs. Epoch Step3: Perplexity vs. Epoch Step4: Generations Step5: BLEU Analysis Step6: N-pairs B...
Python Code: report_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing15_bow_200_512_04drb/encdec_noing15_bow_200_512_04drb.json' log_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing15_bow_200_512_04drb/encdec_noing15_bow_200_512_04drb_logs.json' import ...
179
Given the following text description, write Python code to implement the functionality described below step by step Description: Classify Data Create a classifier for different kinds of plankton using supervised machine learning Executing this Notebook requires a personal STOQS database. Follow the steps to build you...
Python Code: from contrib.analysis.classify import Classifier c = Classifier() Explanation: Classify Data Create a classifier for different kinds of plankton using supervised machine learning Executing this Notebook requires a personal STOQS database. Follow the steps to build your own development system &mdash; this ...
180
Given the following text description, write Python code to implement the functionality described below step by step Description: Least squares fitting of models to data This is a quick introduction to statsmodels for physical scientists (e.g. physicists, astronomers) or engineers. Why is this needed? Because most of s...
Python Code: import numpy as np import pandas as pd import statsmodels.api as sm Explanation: Least squares fitting of models to data This is a quick introduction to statsmodels for physical scientists (e.g. physicists, astronomers) or engineers. Why is this needed? Because most of statsmodels was written by statistici...
181
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Before we get started, a couple of reminders to keep in mind when using iPython notebooks Step2: Fixing Data Types Step4: Note when running the above cells that we are actively chan...
Python Code: import unicodecsv ## Longer version of code (replaced with shorter, equivalent version below) # enrollments = [] # f = open('enrollments.csv', 'rb') # reader = unicodecsv.DictReader(f) # for row in reader: # enrollments.append(row) # f.close() with open('enrollments.csv', 'rb') as f: reader = unico...
182
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Data Step2: Create An Index Using The Column 'pid' As The Unique ID
Python Code: # Ignore %load_ext sql %sql sqlite:// %config SqlMagic.feedback = False Explanation: Title: Create An Index For A Table Slug: create_index_for_a_table Summary: Create An Index For A Table in SQL. Date: 2016-05-01 12:00 Category: SQL Tags: Basics Authors: Chris Albon Note: This tutorial was written u...
183
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.9 查找两字典的相同点 怎样在两字典中寻找相同点(相同的key or 相同的 value) Step1: 为寻找两字典的相同点 可通过简单的在两字典keys() or items() method 中Return 结果 进行set 操作 Step2: 以上操作亦可用于修改or过滤dict element <br> if you want 以现有dict 来构造一个...
Python Code: a = { 'x':1, 'y':2, 'z':3 } b = { 'w':10, 'x':11, 'y':2 } # In a ::: x : 1 ,y : 2 # In b ::: x : 11,y : 2 Explanation: 1.9 查找两字典的相同点 怎样在两字典中寻找相同点(相同的key or 相同的 value) End of explanation # Find keys in common kc = a.keys() & b.keys() print('a 和 b 共有的键',kc) # Find keys in a that are n...
184
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents Step1: Distribution of Passengers Gender - Analysis | Graph <a id="Gender - Analysis | Graph"></a> Distribution of Genders in Passenger Population Step2: Distribution o...
Python Code: # Imports for pandas, and numpy import numpy as np import pandas as pd # imports for seaborn to and matplotlib to allow graphing import matplotlib.pyplot as plt import seaborn as sns sns.set(style="whitegrid") %matplotlib inline # import Titanic CSV - NOTE: adjust file path as neccessary dTitTrain_DF = p...
185
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Clean Up Let's clean this up just a little! Step2: Step 2 Step3: Decomposition ETS decomposition allows us to see the individual parts! Step5: Testing for Stationari...
Python Code: import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv('monthly-milk-production-pounds-p.csv') df.head() df.tail() Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> <center>Copyright...
186
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Introduction This notebook generates the various data representations in lecture 12. It is easy to generalize this to other applications. Step2: Stem and leaf The code below shows ho...
Python Code: from __future__ import division import matplotlib.pyplot as plt import matplotlib as mpl import palettable import numpy as np import math import seaborn as sns from collections import defaultdict %matplotlib inline # Here, we customize the various matplotlib parameters for font sizes and define a color sch...
187
Given the following text description, write Python code to implement the functionality described below step by step Description: Dense Communities in Networks In this problem, we study the problem of finding dense communities in networks. Assume $G$ = ($V,E$) is an undirected graph (e.g., representing a social network...
Python Code: %pylab inline import pylab def initialVertices(numNodes): V = set(); for i in range(numNodes): V.add(i); return V; def initializeDeg(deg, S): for s in S: deg[s] = 0; def computeDegree(S, edgesfile): fedges = open(edgesfile, 'r'); deg = {}; initializeDeg(deg, ...
188
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook was created by Sergey Tomin for Workshop Step1: Change RF parameters for the comparison with ASTRA Step2: Initializing SpaceCharge Step3: Comparison with ASTRA Beam tracking...
Python Code: # the output of plotting commands is displayed inline within frontends, # directly below the code cell that produced it %matplotlib inline from time import time # this python library provides generic shallow (copy) and deep copy (deepcopy) operations from copy import deepcopy # import from Ocelot main m...
189
Given the following text description, write Python code to implement the functionality described below step by step Description: Visual Diagnosis of Text Analysis with Baleen This notebook has been created as part of the Yellowbrick user study. I hope to explore how visual methods might improve the workflow of text cl...
Python Code: %matplotlib inline import os import sys import nltk import pickle # To import yellowbrick sys.path.append("../..") Explanation: Visual Diagnosis of Text Analysis with Baleen This notebook has been created as part of the Yellowbrick user study. I hope to explore how visual methods might improve the work...
190
Given the following text description, write Python code to implement the functionality described below step by step Description: Define the Data Generating Distribution To examine different approximations to the true loss surface of a particular data generating distribution $P(X,Y)$ we must first define it. We will wo...
Python Code: import numpy as np class P(): def __init__(self, m, s): self.m = m # Slope of line self.s = s # Standard deviation of injected noise def sample(self, size): x = np.random.uniform(size=size) y = [] for xi in x: y.app...
191
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Convolutional Generative Adversarial Network (DCGAN) Tutorial This tutorials walks through an implementation of DCGAN as described in Unsupervised Representation Learning with Deep Conv...
Python Code: #Import the libraries we will need. import tensorflow as tf import numpy as np import input_data import matplotlib.pyplot as plt import tensorflow.contrib.slim as slim import os import scipy.misc import scipy Explanation: Deep Convolutional Generative Adversarial Network (DCGAN) Tutorial This tutorials wal...
192
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-3', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: UHH Source ID: SANDBOX-3 Sub-Topics: Radiative Forcings. Properties: 85...
193
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 6 Step1: Step 3 Step2: Run the below cell, and copy the output into the Google Cloud Shell
Python Code: %%bash # Check your project name export PROJECT=$(gcloud config list project --format "value(core.project)") echo "Your current GCP Project Name is: "$PROJECT import os os.environ["BUCKET"] = "your-bucket-id-here" # Recommended: use your project name Explanation: LAB 6: Serving baby weight predictions Lea...
194
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of physical analysis with IPython Step1: Reading simulation data Step2: Looking at data, taking first rows Step3: Plotting some feature Step5: Adding interesting features for eac...
Python Code: %pylab inline import numpy import pandas import root_numpy folder = '/moosefs/notebook/datasets/Manchester_tutorial/' Explanation: Example of physical analysis with IPython End of explanation def load_data(filenames, preselection=None): # not setting treename, it's detected automatically data = roo...
195
Given the following text description, write Python code to implement the functionality described below step by step Description: Python for Probability, Statistics, and Machine Learning Step1: Useful Inequalities In practice, few quantities can be analytically calculated. Some knowledge of bounding inequalities helps...
Python Code: from pprint import pprint import textwrap import sys, re Explanation: Python for Probability, Statistics, and Machine Learning End of explanation import sympy import sympy.stats as ss t=sympy.symbols('t',real=True) x=ss.ChiSquared('x',1) Explanation: Useful Inequalities In practice, few quantities can be a...
196
Given the following text description, write Python code to implement the functionality described below step by step Description: Instalação do Pygame O programa abaixo usa o Pygame e descreve como se pode criar uma janela de titulo "O PyGame é fixe!" Para isso crie um novo ficheiro no menu File do IDLE, seleccionando ...
Python Code: # Importa o modulo com o pygame import pygame_sdl2 as pygame # Inicia o motor de jogo pygame.init() # Indica as dimensões da janela size=[700,500] screen=pygame.display.set_mode(size) # Escreve titulo na Janela pygame.display.set_caption("O PyGame é fixe!") # Usado para controlar a velocidade com que a ja...
197
Given the following text description, write Python code to implement the functionality described below step by step Description: Tuples Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each va...
Python Code: months = ('January','February','March','April','May','June',\ 'July','August','September','October','November',' December') Explanation: Tuples Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the pr...
198
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's get some JSON data from the web - both a point layer and a polygon GeoJson dataset with some population data. Step1: And take a look at what our data looks like Step2: Look how far t...
Python Code: import geopandas states = geopandas.read_file( "https://rawcdn.githack.com/PublicaMundi/MappingAPI/main/data/geojson/us-states.json", driver="GeoJSON", ) cities = geopandas.read_file( "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_populated_places_simple.geojson", driver="...
199
Given the following text description, write Python code to implement the functionality described below step by step Description: Boletins de ocorrência registrados na Grande São Paulo em 2016 Neste passo-a-passo analisaremos um conjunto de dados referente às ocorrências policiais registradas na Grande São Paulo durant...
Python Code: import numpy import pandas from matplotlib import pyplot %matplotlib inline pyplot.style.use('fivethirtyeight') pyplot.rcParams['figure.figsize'] = [11, 8] url = '../dat/boletins_ocorrencia_sp_clean_2016.csv.gz' dat = pandas.read_csv(url, encoding='ISO-8859-1', low_memory=False) dat.describe() dat.head() E...