Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
11,600
Given the following text description, write Python code to implement the functionality described below step by step Description: Step5: Factor Network Functions Messenger Class Performs transformations on data. eg. f(x) -> y Decoupled from the other factor network code, and can be swapped with other implementations...
Python Code: class Messenger: def __init__(self, config='cdr', size=2000): :param url: str Fully qualified url to an elasticsearch instance :param size: int| Size limit to set on elasticsearch query self.conn = connections.get_connection(config) ...
11,601
Given the following text description, write Python code to implement the functionality described below step by step Description: 练习 1:写函数,求n个随机整数均值的平方根,整数范围在m与k之间。 Step1: 练习 2:写函数,共n个随机整数,整数范围在m与k之间,求西格玛log(随机整数)及西格玛1/log(随机整数) Step2: 练习 3:写函数,求s=a+aa+aaa+aaaa+aa...a的值,其中a是[1,9]之间的随机整数。例如2+22+222+2222+22222(此时共有5个数相...
Python Code: import random,math def Square(): m=int(input('plz input the min ')) k=int(input('plz input the max ')) n=int(input('plz input n : ')) i=0 total=0 while i<n: i+=1 temp=random.randint(m,k) total+=temp print (math.sqrt(total/n)) Square() Explanation: 练习...
11,602
Given the following text description, write Python code to implement the functionality described below step by step Description: Decision Trees in Practice In this assignment we will explore various techniques for preventing overfitting in decision trees. We will extend the implementation of the binary decision trees ...
Python Code: import numpy as np import pandas as pd import json Explanation: Decision Trees in Practice In this assignment we will explore various techniques for preventing overfitting in decision trees. We will extend the implementation of the binary decision trees that we implemented in the previous assignment. You w...
11,603
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression with Grid Search (scikit-learn) <a href="https Step1: This example features Step2: Imports Step3: Log Workflow This section demonstrates logging model metadata and tra...
Python Code: # restart your notebook if prompted on Colab try: import verta except ImportError: !pip install verta Explanation: Logistic Regression with Grid Search (scikit-learn) <a href="https://colab.research.google.com/github/VertaAI/modeldb/blob/master/client/workflows/demos/census-end-to-end.ipynb" target...
11,604
Given the following text description, write Python code to implement the functionality described below step by step Description: Test suite for Jupyter-notebook Sample example of use of PyCOMPSs from Jupyter First step Import ipycompss library Step1: Second step Initialize COMPSs runtime Parameters indicates if the e...
Python Code: import pycompss.interactive as ipycompss Explanation: Test suite for Jupyter-notebook Sample example of use of PyCOMPSs from Jupyter First step Import ipycompss library End of explanation ipycompss.start(graph=True, trace=True, debug=True, project_xml='../project.xml', resources_xml='../resources.xml', com...
11,605
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting house prices using k-nearest neighbors regression In this notebook, we will implement k-nearest neighbors regression. You will Step1: Unzipping files with house sales data For th...
Python Code: import os import zipfile import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') %matplotlib inline Explanation: Predicting house prices using k-nearest neighbors regression In this notebook, we will implement k-nearest...
11,606
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparaison $T_{ext}$ mesurée et celle de la météo Step1: Comparaison avec une autre position GPS Step2: Data from ROMMA http Step3: laquelle est correcte ?? à priori Romma
Python Code: coords_grenoble = (45.1973288, 5.7139923) #(45.1973288, 5.7103223) startday, lastday = pd.to_datetime('22/06/2017', format='%d/%m/%Y'), pd.to_datetime('now') # download the data: data = wf.buildmultidayDF(startday, lastday, coords_grenoble ) import emoncmsfeed as getfeeds dataframefreq = '10min' feeds = {...
11,607
Given the following text description, write Python code to implement the functionality described below step by step Description: PyGSLIB PPplot Step1: Getting the data ready for work If the data is in GSLIB format you can use the function pygslib.gslib.read_gslib_file(filename) to import the data into a Pandas DataFr...
Python Code: #general imports import pygslib Explanation: PyGSLIB PPplot End of explanation #get the data in gslib format into a pandas Dataframe mydata= pygslib.gslib.read_gslib_file('../datasets/cluster.dat') true= pygslib.gslib.read_gslib_file('../datasets/true.dat') true['Declustering Weight'] = 1 Explanation: G...
11,608
Given the following text description, write Python code to implement the functionality described below step by step Description: ARC2 download example In this demo we show how to download ARC2 data Step1: <font color='red'>Please put your datahub API key into a file called APIKEY and place it to the notebook folder o...
Python Code: %matplotlib notebook import dh_py_access.lib.datahub as datahub import dh_py_access.package_api as package_api Explanation: ARC2 download example In this demo we show how to download ARC2 data End of explanation server = 'api.planetos.com' API_key = open('APIKEY').readlines()[0].strip() #'<YOUR API KEY HER...
11,609
Given the following text description, write Python code to implement the functionality described below step by step Description: Classify handwritten digits with Keras Data from Step1: <a id="01">1. Download the MNIST dataset from Internet </a> I've made the dataset into a zipped tar file. You'll have to download it ...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns sns.set() import pandas as pd import sklearn import os import requests from tqdm._tqdm_notebook import tqdm_notebook import tarfile Explanation: Classify handwritten digits with Keras Data from: the MNIST dataset Do...
11,610
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducing CivisML 2.0 Note Step1: Downloading data Before we build any models, we need a dataset to play with. We're going to use the most recent College Scorecard data from the Departmen...
Python Code: # first, let's import the packages we need import requests from io import StringIO import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import model_selection # import the Civis Python API client import civis # ModelPipeline is the class used to build Ci...
11,611
Given the following text description, write Python code to implement the functionality described below step by step Description: Class 03 - Supplemental Using Categorical data in machine learning Now that we've created some categorical data or other created features, we would like to use them as inputs for our machine...
Python Code: import pandas as pd import numpy as np sampledata = pd.read_csv('Class03_supplemental_data.csv') print(sampledata.dtypes) sampledata.head() Explanation: Class 03 - Supplemental Using Categorical data in machine learning Now that we've created some categorical data or other created features, we would like t...
11,612
Given the following text description, write Python code to implement the functionality described below step by step Description: El "problema" Es posible que al usar funciones con parámetros por defecto se encuentren con cierto comportamiento inesperado o poco intuitivo de Python. Por estas cosas siempre hay que revis...
Python Code: def funcion(lista=[]): lista.append(1) print("La lista vale: {}".format(lista)) Explanation: El "problema" Es posible que al usar funciones con parámetros por defecto se encuentren con cierto comportamiento inesperado o poco intuitivo de Python. Por estas cosas siempre hay que revisar el código, co...
11,613
Given the following text description, write Python code to implement the functionality described below step by step Description: 数据应用学院 Data Scientist Program Hw2 <h1 id="tocheading">Table of Contents</h1> <div id="toc"></div> Step1: 1. Gnerate x = a sequence of points, y = sin(x)+a where a is a small random error. S...
Python Code: %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') # import the necessary package at the very beginning import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import sklearn Explanation: 数据应用学院 Data Scientist Program H...
11,614
Given the following text description, write Python code to implement the functionality described below step by step Description: < 04 - Time and Chronology | Home | 06 - Stable Roommates, Marriages, and Gender > Cliques and Communities Step1: Communities are just as important in the social structure of novels as th...
Python Code: from bookworm import * %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (12,9) import pandas as pd import numpy as np import networkx as nx Explanation: < 04 - Time and Chronology | Home | 06 - Stable Roommates, Marriages, and Gender > Cliques and Communities End of exp...
11,615
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I use linear SVM from scikit learn (LinearSVC) for binary classification problem. I understand that LinearSVC can give me the predicted labels, and the decision scores but I wanted ...
Problem: import numpy as np import pandas as pd import sklearn.svm as suppmach X, y, x_test = load_data() assert type(X) == np.ndarray assert type(y) == np.ndarray assert type(x_test) == np.ndarray # Fit model: svmmodel=suppmach.LinearSVC() from sklearn.calibration import CalibratedClassifierCV calibrated_svc = Calibra...
11,616
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Recurrent Neural Networks (RNN) with Keras <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: ...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
11,617
Given the following text description, write Python code to implement the functionality described below step by step Description: KNN Motivation The principle behind nearest neighbor methods is to find a predefined number of training samples closest in distance to the new point, and predict the label from these. The nu...
Python Code: import pandas import numpy import csv #from scipy.stats import mode from sklearn import neighbors from sklearn.neighbors import DistanceMetric from pprint import pprint MY_TITANIC_TRAIN = 'train.csv' MY_TITANIC_TEST = 'test.csv' titanic_dataframe = pandas.read_csv(MY_TITANIC_TRAIN, header=0) print('length...
11,618
Given the following text description, write Python code to implement the functionality described below step by step Description: Here is an example of simulated sea surface height from the NEMO model run at 1/4°, that is represented by an xarray.DataArray object. Note that dask array can be used by precising chunks. S...
Python Code: signal_xyt = xr.open_dataset(sigdir + test_file, decode_times=False)['sossheig'].chunk(chunks={'time_counter': 50}) print signal_xyt signal_xyt.isel(time_counter=0).plot(vmin=-0.07, vmax=0.07, cmap='seismic') Explanation: Here is an example of simulated sea surface height from the NEMO model run at 1/4°, t...
11,619
Given the following text description, write Python code to implement the functionality described below step by step Description: Denavit Hartenberg Notation Kevin Walchko Created Step1: Rise of the Robots Robot arms and legs are hard to control (lots of math), but are required for most robotic applications. <img src...
Python Code: %matplotlib inline from __future__ import print_function from __future__ import division import numpy as np from math import cos, sin, pi from IPython.display import HTML # need this for embedding a movie in an iframe Explanation: Denavit Hartenberg Notation Kevin Walchko Created: 10 July 2017 Denavit Hart...
11,620
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Preprocessing for Machine Learning Learning Objectives * Understand the different approaches for data preprocessing in developing ML models * Use Dataflow to perform data preprocessing ...
Python Code: #Ensure that we have the correct version of Apache Beam installed !pip freeze | grep apache-beam || sudo pip install apache-beam[gcp]==2.12.0 import tensorflow as tf import apache_beam as beam import shutil import os print(tf.__version__) Explanation: Data Preprocessing for Machine Learning Learning Object...
11,621
Given the following text description, write Python code to implement the functionality described below step by step Description: Collaborative filtering on the MovieLense Dataset Learning objectives 1. Explore the data using BigQuery. 2. Use the model to make recommendations for a user. 3. Use the model to recommend a...
Python Code: import os import tensorflow as tf PROJECT = "your-project-here" # REPLACE WITH YOUR PROJECT ID # Do not change these os.environ["PROJECT"] = PROJECT os.environ["TFVERSION"] = '2.6' %%bash mkdir bqml_data cd bqml_data curl -O 'http://files.grouplens.org/datasets/movielens/ml-20m.zip' unzip ml-20m.zip yes | ...
11,622
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize the model https Step1: Show convolutional filters Step2: Show activations with quiver Install quiver
Python Code: from keras.models import load_model,Model import dogs_vs_cats as dvc import numpy as np modelname = "cnn_model_trained.h5" cnn_model = load_model(modelname) # Load some data from keras.applications.imagenet_utils import preprocess_input all_files = dvc.image_files() all_files = np.array(all_files) files_te...
11,623
Given the following text description, write Python code to implement the functionality described below step by step Description: Lesson 17 Step1: Dictionaries are equivalent. Step2: A Dictionary cannot lookup a value that is not available. Step3: You can check if a variable is in a dictionary. Step4: You can use m...
Python Code: eggs = { 'name': 'Zophie', 'species': 'cat', 'age': 8 } ham = { 'species': 'cat', 'name': 'Zophie', 'age': 8 } print(eggs) print(ham) Explanation: Lesson 17: The Dictionary Data Type Switched to the Jupyter Notebook for REPL convenience. Dictionaries use key pairs to store ...
11,624
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...
11,625
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have two csr_matrix, c1, c2.
Problem: from scipy import sparse c1 = sparse.csr_matrix([[0, 0, 1, 0], [2, 0, 0, 0], [0, 0, 0, 0]]) c2 = sparse.csr_matrix([[0, 3, 4, 0], [0, 0, 0, 5], [6, 7, 0, 8]]) Feature = sparse.hstack((c1, c2)).tocsr()
11,626
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimating Current Cases by Category This notebook explores a methodology to estimate current mild, severe and critical patients. Both mild and critical categories appear to be correlated to...
Python Code: # Since reported numbers are approximate, they are rounded for the sake of simplicity severe_ratio = .15 critical_ratio = .05 mild_ratio = 1 - severe_ratio - critical_ratio Explanation: Estimating Current Cases by Category This notebook explores a methodology to estimate current mild, severe and critical p...
11,627
Given the following text description, write Python code to implement the functionality described below step by step Description: Gradient Checking Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. You are part of a team working to make mobile paym...
Python Code: # Packages import numpy as np from testCases import * from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector Explanation: Gradient Checking Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. ...
11,628
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyzing Thanksgiving Dinner This notebook analyzes Thanksgiving dinner in the US. The dataset contains 1058 responses to an online survey about what Americans eat for Thanksgiving dinner, ...
Python Code: import pandas as pd data = pd.read_csv("thanksgiving.csv", encoding = 'Latin-1') data.head() data.columns data['Do you celebrate Thanksgiving?'].value_counts() Explanation: Analyzing Thanksgiving Dinner This notebook analyzes Thanksgiving dinner in the US. The dataset contains 1058 responses to an online s...
11,629
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook will perform analysis of functional connectivity on simulated data. Step1: Now let's add on an activation signal to both voxels Step2: How can we address this problem? A gene...
Python Code: import os,sys import numpy %matplotlib inline import matplotlib.pyplot as plt sys.path.insert(0,'../utils') from mkdesign import create_design_singlecondition from nipy.modalities.fmri.hemodynamic_models import spm_hrf,compute_regressor from make_data import make_continuous_data data=make_continuous_data(N...
11,630
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Crash Course Exercises This is an optional exercise to test your understanding of Python Basics. If you find this extremely challenging, then you probably are not ready for the rest o...
Python Code: 7**4 Explanation: Python Crash Course Exercises This is an optional exercise to test your understanding of Python Basics. If you find this extremely challenging, then you probably are not ready for the rest of this course yet and don't have enough programming experience to continue. I would suggest you tak...
11,631
Given the following text description, write Python code to implement the functionality described below step by step Description: Sending Secret Messages with Python This notebook will teach you how to send secret messages to your friends using a computer language called "Python." Python is used by thousands of program...
Python Code: print ("Hello my name is Levi.") Explanation: Sending Secret Messages with Python This notebook will teach you how to send secret messages to your friends using a computer language called "Python." Python is used by thousands of programmers around the world to create websites and video games, to do science...
11,632
Given the following text description, write Python code to implement the functionality described below step by step Description: EuroPython program grid Step1: Load the data Step2: Clean up the data Here I pick from talk_sessions only the talks with the type that I need for scheduling. I also remove from all these t...
Python Code: %%javascript IPython.OutputArea.auto_scroll_threshold = 99999; //increase max size of output area import json import datetime as dt from random import choice, randrange, shuffle from copy import deepcopy from collections import OrderedDict, defaultdict from itertools import product from functools import pa...
11,633
Given the following text description, write Python code to implement the functionality described below step by step Description: Gate Zoo <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step1: Cirq comes with many gates that are standard across quantum computing. This noteb...
Python Code: try: import cirq except ImportError: print("installing cirq...") !pip install --quiet --pre cirq print("installed cirq.") import IPython.display as ipd import cirq import inspect def display_gates(*gates): for gate_name in gates: ipd.display(ipd.Markdown("---")) gat...
11,634
Given the following text description, write Python code to implement the functionality described below step by step Description: quant-econ Solutions Step1: Setup To recall, we consider the following problem Step2: Here we want to solve a finite state version of the continuous state model above. We discretize the st...
Python Code: %matplotlib inline from __future__ import division, print_function import numpy as np import scipy.sparse as sparse import matplotlib.pyplot as plt from quantecon import compute_fixed_point from quantecon.markov import DiscreteDP Explanation: quant-econ Solutions: Discrete Dynamic Programming Solutions for...
11,635
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 4 Step1: Part 1a. Simple Line Fitting Step2: Try a range of slopes and intercepts, and calculate $\chi^2$ values for each set. Step3: What is chi2? What happens if you print it? Wh...
Python Code: import numpy as np from matplotlib import pyplot as plt %matplotlib inline Explanation: Lab 4: Curve Fitting Jacob Skinner End of explanation x=np.array([1.1,2.2,3.1,4.0,5.0,5.8,6.9]) y=np.array([2.0,3.0,4.0,5.0,6.0,7.0,8.0]) dely=np.array([0.1,0.1,0.1,0.1,0.1,0.1,0.1]) plt.plot(x,y,'ro') plt.show() Expla...
11,636
Given the following text description, write Python code to implement the functionality described below step by step Description: Using isomorphism doesn't help Step1: Since the Property map doesn't map exactly to the node id in the main graph, I have to use the induced subgraphs.
Python Code: re = isomorphism(re.get_graph(), m3_5.gt_motif, isomap=True) re[1][2] re = m3_5_r[2][0][0] graph_draw(re.get_graph(), output_size=(100,100)) re.get_graph().get_edges() re[0] re[1] re[2] g.get_out_edges(216) re.get_graph().get_edges() re[0], re[1], re[2] for i in _: print(g.get_out_edges(i)) Explanation...
11,637
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal Retrieve the discretization attributes available in PredicSis.ai GUI using the Python SDK Prerequisites PredicSis.ai Python SDK (pip install predicsis; documentation) A predictive model...
Python Code: # Load PredicSis.ai SDK from predicsis import PredicSis import predicsis.config as config, os, sys os.environ['PREDICSIS_URL'] = 'your_instance' if sys.version_info[0] >= 3: from importlib import reload reload(config) Explanation: Goal Retrieve the discretization attributes available in PredicSis.ai GU...
11,638
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification with a Multi-layer Perceptron (MLP) Author Step1: A few notes on Pytorch syntax (Many thanks to Vanessa Bohm!!) Pytorch datatype summary Step2: Problem 2b Make a histogram s...
Python Code: # this module contains our dataset !pip install astronn #this is pytorch, which we will use to build our nn import torch #Standards for plotting, math import matplotlib.pyplot as plt import numpy as np #for our objective function from sklearn.metrics import accuracy_score, confusion_matrix, ConfusionMatrix...
11,639
Given the following text description, write Python code to implement the functionality described below step by step Description: 主题模型 王成军 wangchengjun@nju.edu.cn 计算传播网 http Step1: Download data http Step2: Build the topic model Step3: We can see the list of topics a document refers to by using the model[doc] syntax...
Python Code: %matplotlib inline from __future__ import print_function from wordcloud import WordCloud from gensim import corpora, models, similarities, matutils import matplotlib.pyplot as plt import numpy as np Explanation: 主题模型 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-communication.com 2014年高考前夕,百度“基于海...
11,640
Given the following text description, write Python code to implement the functionality described below step by step Description: Límite de Shockley–Queisser Bandas de conduccion y Bandgap Primero librerias Step1: Graficas chidas! Step2: 1 A graficar el Hermoso Espectro Solar Primero constantes numericas Utilizaremo...
Python Code: import numpy as np # modulo de computo numerico import matplotlib.pyplot as plt # modulo de graficas import pandas as pd # modulo de datos import seaborn as sns import scipy as sp import scipy.interpolate, scipy.integrate # para interpolar e integrar import wget, tarfile # para bajar datos y descompirmir ...
11,641
Given the following text description, write Python code to implement the functionality described below step by step Description: Clase 7 Step1: 2. Modelo normal para los rendimientos Step2: 3. Simulación usando el histograma de los rendimientos
Python Code: #importar los paquetes que se van a usar import pandas as pd import pandas_datareader.data as web import numpy as np from sklearn.neighbors import KernelDensity import datetime from datetime import datetime, timedelta import scipy.stats as stats import scipy as sp import scipy.optimize as optimize import s...
11,642
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom Generator objects This example should guide you to build your own simple generator. Step1: Basic knowledge We assume that you have completed at least some of the previous examples an...
Python Code: from adaptivemd import ( Project, Task, File, PythonTask ) project = Project('tutorial') engine = project.generators['openmm'] modeller = project.generators['pyemma'] pdb_file = project.files['initial_pdb'] Explanation: Custom Generator objects This example should guide you to build your own simple gen...
11,643
Given the following text description, write Python code to implement the functionality described below step by step Description: Example Assignment <a href="#Problem-1">Problem 1</a> <a href="#Problem-2">Problem 2</a> <a href="#Part-A">Part A</a> <a href="#Part-B">Part B</a> <a href="#Part-C">Part C</a> Before you tur...
Python Code: NAME = "" COLLABORATORS = "" Explanation: Example Assignment <a href="#Problem-1">Problem 1</a> <a href="#Problem-2">Problem 2</a> <a href="#Part-A">Part A</a> <a href="#Part-B">Part B</a> <a href="#Part-C">Part C</a> Before you turn this problem in, make sure everything runs as expected. First, restart th...
11,644
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Text Data Step2: Tokenize Words Step3: Tokenize Sentences
Python Code: # Load library from nltk.tokenize import word_tokenize, sent_tokenize Explanation: Title: Tokenize Text Slug: tokenize_text Summary: How to tokenize text from unstructured text data for machine learning in Python. Date: 2016-09-08 12:00 Category: Machine Learning Tags: Preprocessing Text Authors: Chris Al...
11,645
Given the following text description, write Python code to implement the functionality described below step by step Description: Kalman filter for altitude estimation from accelerometer and sonar I) TRAJECTORY We assume sinusoidal trajectory Step1: II) MEASUREMENTS Sonar Step2: Baro Step3: GPS Step4: GPS velocity...
Python Code: m = 10000 # timesteps dt = 1/ 250.0 # update loop at 250Hz t = np.arange(m) * dt freq = 0.1 # Hz amplitude = 0.5 # meter alt_true = 405 + amplitude * np.cos(2 * np.pi * freq * t) height_true = 5 + amplitude * np.cos(2 * np.pi * freq * t) vel_true = - amplitude * (2 * np.pi * freq) * np.sin(2 *...
11,646
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading CTD data with PySeabird Author Step1: Let's first download an example file with some CTD data Step2: The profile dPIRX003.cnv.OK was loaded with the default rule cnv.yaml Step3: W...
Python Code: %matplotlib inline from seabird.cnv import fCNV from gsw import z_from_p Explanation: Reading CTD data with PySeabird Author: Guilherme Castelão pySeabird is a package to parse/load CTD data files. It should be an easy task but the problem is that the format have been changing along the time. Work with mul...
11,647
Given the following text description, write Python code to implement the functionality described below step by step Description: In general your solutions are more elegant. Great use of available libraries Like your solutions for day3 (spiral memory), day11 (hex grid) Day 1 Smart, clean and elegant. Step1: Day 3 Well...
Python Code: digits = '91212129' L = len(digits) sum([int(digits[i]) for i in range(L) if digits[i] == digits[(i+1) % L]]) def solve(captcha): captcha = list(map(int, captcha)) prev_val = captcha[-1] repeated = 0 for v in captcha: if v == prev_val: repeated += v prev_val = v ...
11,648
Given the following text description, write Python code to implement the functionality described below step by step Description: Titanic kaggle competition with SVM - Advanced Step1: Let's load the processed data and feature scale Age and Fare Step2: Select the features from data, and convert to numpy arrays Step3: ...
Python Code: #import all the needed package import numpy as np import scipy as sp import re import pandas as pd import sklearn from sklearn.cross_validation import train_test_split,cross_val_score from sklearn import metrics import matplotlib from matplotlib import pyplot as plt %matplotlib inline from sklearn.svm imp...
11,649
Given the following text description, write Python code to implement the functionality described below step by step Description: Training Logistic Regression via Stochastic Gradient Ascent The goal of this notebook is to implement a logistic regression classifier using stochastic gradient ascent. You will Step1: Load...
Python Code: from __future__ import division import graphlab Explanation: Training Logistic Regression via Stochastic Gradient Ascent The goal of this notebook is to implement a logistic regression classifier using stochastic gradient ascent. You will: Extract features from Amazon product reviews. Convert an SFrame int...
11,650
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Exercise 1 Step2: b. Graphing Using the techniques laid out in lecture, plot a histogram of the returns Step3: c. Cumulative distribution Plot the cumulative distribution...
Python Code: # Useful Functions import numpy as np import matplotlib.pyplot as plt Explanation: Exercises: Plotting By Christopher van Hoecke, Max Margenot, and Delaney Mackenzie Lecture Link: https://www.quantopian.com/lectures/plotting-data IMPORTANT NOTE: This lecture corresponds to the Plotting Data lecture, which ...
11,651
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification We have seen how you can evaluate a supervised learner with a loss function. Classification is the learning task where one tried to predict a binary response variable, this c...
Python Code: import pandas as pd import numpy as np import matplotlib as mpl import plotnine as p9 import matplotlib.pyplot as plt import itertools import warnings warnings.simplefilter("ignore") from matplotlib.pyplot import rcParams rcParams['figure.figsize'] = 6,6 Explanation: Classification We have seen how you can...
11,652
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Import Python Packages To install the kernel used by NERSC-metatlas users, copy the following text to $HOME/.ipython/kernels/mass_spec_cori/kernel.json { "argv" Step1: 2. Set atlas, pro...
Python Code: from IPython.core.display import Markdown, display, clear_output, HTML display(HTML("<style>.container { width:100% !important; }</style>")) %matplotlib notebook %matplotlib inline %env HDF5_USE_FILE_LOCKING=FALSE import sys, os #### add a path to your private code if not using production code #### #print ...
11,653
Given the following text description, write Python code to implement the functionality described below step by step Description: Generation of tables and figures of MRIQC paper This notebook is associated to the paper Step1: Read some data (from mriqc package) Step2: Figure 1 Step3: Figure 2 Step4: Figure 3 Step5:...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import os.path as op import numpy as np import pandas as pd from pkg_resources import resource_filename as pkgrf from mriqc.viz import misc as mviz from mriqc.classifier.data import read_dataset, combine_datasets # Where the outputs should be saved outp...
11,654
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of indiv...
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 import math %matplotlib inline #reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image...
11,655
Given the following text description, write Python code to implement the functionality described below step by step Description: Characteristic times in real networks Step1: Model Chassagnole2002 Create a new network object and load the informations from the model Chassagnole2002. In the original model, the concentra...
Python Code: from imp import reload import re import numpy as np from scipy.integrate import ode import NetworkComponents Explanation: Characteristic times in real networks End of explanation chassagnole = NetworkComponents.Network("chassagnole2002") chassagnole.readSBML("./published_models/Chassagnole2002.xml") chassa...
11,656
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem Set 8 Review & Transfer Learning with word2vec Import various modules that we need for this notebook (now using Keras 1.0.0) Step1: I. Problem Set 8, Part 1 Let's work through a sol...
Python Code: %pylab inline import copy import numpy as np import pandas as pd import sys import os import re from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.optimizers import SGD, RMSprop from keras.layers.normalization import BatchNormalization from keras.layers....
11,657
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
11,658
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook describes setting up a model inspired by the Maxout Network (Goodfellow et al.) which they ran out the CIFAR-10 dataset. The yaml file was modified as little as possible, subst...
Python Code: !obj:pylearn2.train.Train { dataset: &train !obj:neukrill_net.dense_dataset.DensePNGDataset { settings_path: %(settings_path)s, run_settings: %(run_settings_path)s, training_set_mode: "train" }, model: !obj:pylearn2.models.mlp.MLP { batch_size: &batch...
11,659
Given the following text description, write Python code to implement the functionality described below step by step Description: DV360 Report Emailed To BigQuery Pulls a DV360 Report from a gMail email into BigQuery. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: DV360 Report Emailed To BigQuery Pulls a DV360 Report from a gMail email into BigQuery. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with ...
11,660
Given the following text description, write Python code to implement the functionality described below step by step Description: NATURAL LANGUAGE PROCESSING This notebook covers chapters 22 and 23 from the book Artificial Intelligence Step1: CONTENTS Overview Languages HITS Question Answering CYK Parse Chart Parsing ...
Python Code: import nlp from nlp import Page, HITS from nlp import Lexicon, Rules, Grammar, ProbLexicon, ProbRules, ProbGrammar from nlp import CYK_parse, Chart from notebook import psource Explanation: NATURAL LANGUAGE PROCESSING This notebook covers chapters 22 and 23 from the book Artificial Intelligence: A Modern A...
11,661
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Pandas</h1> Step1: <h2>Imports</h2> Step2: <h2>The structure of a dataframe</h2> Step3: <h3>Accessing columns and rows</h3> Step4: <h3>Getting column data</h3> Step5: <h3>Getting ro...
Python Code: #installing pandas libraries !pip install pandas-datareader !pip install --upgrade html5lib==1.0b8 #There is a bug in the latest version of html5lib so install an earlier version #Restart kernel after installing html5lib Explanation: <h1>Pandas</h1> End of explanation import pandas as pd #pandas library fr...
11,662
Given the following text description, write Python code to implement the functionality described below step by step Description: NNabla Python API Demonstration Tutorial Let us import nnabla first, and some additional useful tools. Step1: NdArray NdArray is a data container of a multi-dimensional array. NdArray is de...
Python Code: !pip install nnabla-ext-cuda100 !git clone https://github.com/sony/nnabla.git %cd nnabla/tutorial import nnabla as nn # Abbreviate as nn for convenience. import numpy as np %matplotlib inline import matplotlib.pyplot as plt Explanation: NNabla Python API Demonstration Tutorial Let us import nnabla first, ...
11,663
Given the following text description, write Python code to implement the functionality described below step by step Description: Note For this to work, you will need the lsst.sims stack to be installed. - opsimsummary uses healpy which is installed with the sims stack, but also available from pip/conda - snsims use...
Python Code: import opsimsummary as oss from opsimsummary import Tiling, HealpixTiles # import snsims import healpy as hp %matplotlib inline import matplotlib.pyplot as plt Explanation: Note For this to work, you will need the lsst.sims stack to be installed. - opsimsummary uses healpy which is installed with the sim...
11,664
Given the following text description, write Python code to implement the functionality described below step by step Description: More fun with pandas Let's use pandas to dive into some more complicated data. The data We're going to be working with FDA import refusal data from 2014 to September 2017. From the source St...
Python Code: # to avoid errors with the FDA files, we're going to specify the encoding # as latin_1, which is common with gov't data # so it's a decent educated guess to start with # main dataframe # country code lookup dataframe # refusal code lookup dataframe # specify that the 'ASC_ID' column comes in as a string # ...
11,665
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In this exercise, you'll apply target encoding to features in the Ames dataset. Run this cell to set everything up! Step1: First you'll need to choose which features you want t...
Python Code: # Setup feedback system from learntools.core import binder binder.bind(globals()) from learntools.feature_engineering_new.ex6 import * import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import warnings from category_encoders import MEstimateEncoder from sklearn.mod...
11,666
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab Session Step1: 1. Introduction In this notebook we explore an application of clustering algorithms to shape segmentation from binary images. We will carry out some exploratory work with...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy.misc import imread Explanation: Lab Session: Clustering algorithms for Image Segmentation Author: Jesús Cid Sueiro Jan. 2017 End of explanation name = "birds.jpg" name = "Seeds.jpg" birds = imread("Images/" + name) birdsG = np...
11,667
Given the following text description, write Python code to implement the functionality described below step by step Description: 로지스틱 회귀 분석 로지스틱 회귀(Logistic Regression) 분석은 회귀 분석이라는 명칭을 가지고 있지만 분류(classsification) 방법의 일종이다. 로지스틱 회귀 모형에서는 베르누이 확률 변수(Bernoilli random variable)의 모수(parameter) $\theta$가 독립 변수 $x$에 의존한다고 가...
Python Code: xx = np.linspace(-10, 10, 1000) plt.plot(xx, (1/(1+np.exp(-xx)))*2-1, label="logistic (scaled)") plt.plot(xx, sp.special.erf(0.5*np.sqrt(np.pi)*xx), label="erf (scaled)") plt.plot(xx, np.tanh(xx), label="tanh") plt.ylim([-1.1, 1.1]) plt.legend(loc=2) plt.show() Explanation: 로지스틱 회귀 분석 로지스틱 회귀(Logistic Regr...
11,668
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Bipartite graphs are graphs that have two (bi-) partitions (-partite) of nodes. Nodes within each partition are not allowed to be connected to one another; rather, they can only...
Python Code: G = cf.load_crime_network() G.edges(data=True)[0:5] G.nodes(data=True)[0:10] Explanation: Introduction Bipartite graphs are graphs that have two (bi-) partitions (-partite) of nodes. Nodes within each partition are not allowed to be connected to one another; rather, they can only be connected to nodes in t...
11,669
Given the following text description, write Python code to implement the functionality described below step by step Description: Bubble Sort Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and sw...
Python Code: def bubble_sort(unsorted_list): x = ipytracer.List1DTracer(unsorted_list) display(x) length = len(x)-1 for i in range(length): for j in range(length-i): if x[j] > x[j+1]: x[j], x[j+1] = x[j+1], x[j] return x.data Explanation: Bubble Sort Bubble sort, ...
11,670
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear Algebra in NumPy Unit 9, Lecture 2 Numerical Methods and Statistics Prof. Andrew White, March 30, 2020 Step1: Working with Matrices in Numpy We saw earlier in the class how to create...
Python Code: import random import numpy as np import matplotlib.pyplot as plt from math import sqrt, pi, erf import scipy.stats import numpy.linalg Explanation: Linear Algebra in NumPy Unit 9, Lecture 2 Numerical Methods and Statistics Prof. Andrew White, March 30, 2020 End of explanation matrix = [ [4,3], [6, 2] ] pri...
11,671
Given the following text description, write Python code to implement the functionality described below step by step Description: New to Plotly? Plotly's Python library is free and open source! Get started by downloading the client and reading the primer. <br>You can set up Plotly to work in online or offline mode, or ...
Python Code: import plotly plotly.__version__ Explanation: New to Plotly? Plotly's Python library is free and open source! Get started by downloading the client and reading the primer. <br>You can set up Plotly to work in online or offline mode, or in jupyter notebooks. <br>We also have a quick-reference cheatsheet (ne...
11,672
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. This is a Jupyter notebook! <p>A <em>Jupyter notebook</em> is a document that contains text cells (what you're reading right now) and code cells. What is special with a notebook is that i...
Python Code: # I'm a code cell, click me, then run me! 256 * 60 * 24 # Children × minutes × hours Explanation: 1. This is a Jupyter notebook! <p>A <em>Jupyter notebook</em> is a document that contains text cells (what you're reading right now) and code cells. What is special with a notebook is that it's <em>interactive...
11,673
Given the following text description, write Python code to implement the functionality described below step by step Description: Dealing with spectrum data This tutorial demonstrates how to use Spectrum class to do various arithmetic operations of Spectrum. This demo uses the Jsc calculation as an example, namely \beg...
Python Code: %matplotlib inline import numpy as np import scipy.constants as sc import matplotlib.pyplot as plt from pypvcell.spectrum import Spectrum from pypvcell.illumination import Illumination from pypvcell.photocurrent import gen_step_qe_array Explanation: Dealing with spectrum data This tutorial demonstrates how...
11,674
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 1 The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later. This notebook ...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from scipy import ndimage from...
11,675
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducing the Keras Sequential API Learning Objectives 1. Build a DNN model using the Keras Sequential API 1. Learn how to use feature columns in a Keras model 1. Learn how to train ...
Python Code: import datetime import os import shutil import numpy as np import pandas as pd import tensorflow as tf from google.cloud import aiplatform from matplotlib import pyplot as plt from tensorflow import keras from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers import Dense, DenseFea...
11,676
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with relational data using Pandas Testing the waters with sample relational data Based on well defined theory and availability of highly mature, scalable and accessible relational da...
Python Code: import pandas as pd # Some basic data users = [ { 'name': 'John', 'age': 29, 'id': 1 }, { 'name': 'Doe', 'age': 19, 'id': 2 }, { 'name': 'Alex', 'age': 32, 'id': 3 }, { 'name': 'Rahul', 'age': 27, 'id': 4 }, { 'name': 'Ellen', 'age': 23, 'id': 5}, { 'name': 'Shristy', 'age': 30, 'id...
11,677
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> 2. Creating a sampled dataset </h1> In this notebook, you will implement Step1: <h2> Create ML dataset by sampling using BigQuery </h2> <p> Sample the BigQuery table publicdata.samples...
Python Code: # TODO: change these to reflect your environment BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb...
11,678
Given the following text description, write Python code to implement the functionality described below step by step Description: Empircally observed SaaS churn A subscribtion-as-a-service company has a typical customer churn pattern. During periods of no billing, the churn is relatively low compared to periods of bill...
Python Code: kmf = KaplanMeierFitter().fit(df['T'], df['E']) kmf.plot(figsize=(11,6)); Explanation: Empircally observed SaaS churn A subscribtion-as-a-service company has a typical customer churn pattern. During periods of no billing, the churn is relatively low compared to periods of billing (typically every 30 or 365...
11,679
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Test Cases Case 1.1 - Biomedical Device for Parkinson's Disease Progression Monitoring The dataset used in this test case is the Oxford Parkinson's Disease Telemonitoring Da...
Python Code: import numpy as np import pandas as pd import os from pandas import DataFrame from pandas import read_csv from numpy import mean from numpy import std import matplotlib.pyplot as plt import matplotlib %matplotlib inline matplotlib.style.use('ggplot') import seaborn as sns results = read_csv('parkinsons_upd...
11,680
Given the following text description, write Python code to implement the functionality described below step by step Description: The csv module can be used to work with data exported from spreadsheets and databases into text files formatted with fields and records, commonly referred to as comma-separated value (CSV) f...
Python Code: import csv import sys unicode_chars = 'å∫ç' with open('data.csv', 'wt') as f: writer = csv.writer(f) writer.writerow(('Title 1', 'Title 2', 'Title 3', 'Title 4')) for i in range(3): row = ( i + 1, chr(ord('a') + i), '08/{:02d}/07'.format(i + 1), ...
11,681
Given the following text description, write Python code to implement the functionality described below step by step Description: Previous 1.18 映射名称到序列元素 问题 你有一段通过下标访问列表或者元组中元素的代码,但是这样有时候会使得你的代码难以阅读, 于是你想通过名称来访问元素。 解决方案 collections.namedtuple() 函数通过使用一个普通的元组对象来帮你解决这个问题。 这个函数实际上是一个返回 Python 中标准元组类型子类的一个工厂方法。 你需要传递一个类型名和...
Python Code: from collections import namedtuple Subscriber = namedtuple("Subscriber", ["addr", "joined"]) sub = Subscriber("jonesy@example.com", "2012-10-19") sub sub.addr sub.joined Explanation: Previous 1.18 映射名称到序列元素 问题 你有一段通过下标访问列表或者元组中元素的代码,但是这样有时候会使得你的代码难以阅读, 于是你想通过名称来访问元素。 解决方案 collections.namedtuple() 函数通过使用一个普...
11,682
Given the following text description, write Python code to implement the functionality described below step by step Description: Compile and deploy the TFX pipeline to Kubeflow Pipelines This notebook is the second of two notebooks that guide you through automating the Real-time Item-to-item Recommendation with BigQue...
Python Code: %load_ext autoreload %autoreload 2 !pip install -q -U kfp Explanation: Compile and deploy the TFX pipeline to Kubeflow Pipelines This notebook is the second of two notebooks that guide you through automating the Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorization and ScaNN solution ...
11,683
Given the following text description, write Python code to implement the functionality described below step by step Description: This quickstart guide explains how to join two tables A and B using edit distance measure. First, you need to import the required packages as follows (if you have installed py_stringsimjoin ...
Python Code: # Import libraries import py_stringsimjoin as ssj import py_stringmatching as sm import pandas as pd import os, sys print('python version: ' + sys.version) print('py_stringsimjoin version: ' + ssj.__version__) print('py_stringmatching version: ' + sm.__version__) print('pandas version: ' + pd.__version__) ...
11,684
Given the following text description, write Python code to implement the functionality described. Description: Count of numbers whose difference with Fibonacci count upto them is atleast K Python 3 program to find the count of numbers whose difference with Fibonacci count upto them is atleast K ; fibUpto [ i ] denotes ...
Python Code: MAX = 1000005 fibUpto =[0 ] *(MAX + 1 ) def compute(sz ) : isFib =[False ] *(sz + 1 ) prev = 0 curr = 1 isFib[prev ] = True isFib[curr ] = True while(curr <= sz ) : temp = curr + prev if(temp <= sz ) : isFib[temp ] = True  prev = curr curr = temp  fibUpto[0 ] = 1 for i in...
11,685
Given the following text description, write Python code to implement the functionality described below step by step Description: Differential Equations An ordinary differential equation or ODE is a mathematical equation containing a function or functions of one independent variable and its derivatives. The term ordina...
Python Code: def rungekutta(fn, y0, ti=0, tf=10, h=0.01): h = np.float(h) x = np.arange(ti, tf, h) Y = np.zeros((len(x), len(y0))) Y[0] = y0 for i in range(0, len(x)-1): yi = Y[i] xi = x[i] k1 = h * fn(xi, yi) k2 = h * fn(xi + 0.5 * h, yi +...
11,686
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Import the necessary packages to read in the data, plot, and create a linear regression model Step1: 2. Read in the hanford.csv file Step2: 3. Calculate the basic descriptive statistics...
Python Code: import pandas as pd import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') %matplotlib inline import statsmodels.formula.api as smf Explanation: 1. Import the necessary packages to read in the data, plot, and create a linear regression model End of explanation df = pd.read_csv('hanford.csv') Expl...
11,687
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting Models Learning Objectives Step1: Introduction In Data Science it is common to start with data and develop a model of that data. Such models can help to explain the data and make pr...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy import optimize as opt from IPython.html.widgets import interact Explanation: Fitting Models Learning Objectives: learn to fit models to data using linear and non-linear regression. This material is licensed under the MIT lice...
11,688
Given the following text description, write Python code to implement the functionality described below step by step Description: CI/CD for a Kubeflow pipeline on Vertex AI Learning Objectives Step1: Let us make sure that the artifact store exists Step2: Creating the KFP CLI builder for Vertex AI Review the Dockerfil...
Python Code: PROJECT_ID = !(gcloud config get-value project) PROJECT_ID = PROJECT_ID[0] REGION = "us-central1" ARTIFACT_STORE = f"gs://{PROJECT_ID}-kfp-artifact-store" Explanation: CI/CD for a Kubeflow pipeline on Vertex AI Learning Objectives: 1. Learn how to create a custom Cloud Build builder to pilote Vertex AI Pip...
11,689
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting the H.E.S.S. Crab spectrum with iminuit and emcee As an example of a chi^2 fit, we use the flux points from the Crab nebula as measured by H.E.S.S. in 2006 Step1: The data We start ...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.style.use('ggplot') Explanation: Fitting the H.E.S.S. Crab spectrum with iminuit and emcee As an example of a chi^2 fit, we use the flux points from the Crab nebula as measured by H.E.S.S. in 2006: http://adsabs....
11,690
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Tabular-Output" data-toc-modified-id="Tabular-Output-1"><span class="...
Python Code: from myhdl import * from myhdlpeek import Peeker # Import the myhdlpeeker module. def mux(z, a, b, sel): A simple multiplexer. @always_comb def mux_logic(): if sel == 1: z.next = a # Signal a sent to mux output when sel is high. else: z.next = b # Sign...
11,691
Given the following text description, write Python code to implement the functionality described below step by step Description: LSTM text generation from Nietzsche's writings The original script is here. It has the following message regarding speed Step1: Get the data Step2: Build the neural network Step3: Train t...
Python Code: # Imports from __future__ import print_function from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.layers import LSTM from keras.utils.data_utils import get_file import numpy as np import random import sys Explanation: LSTM text generation from Nietzsche's wr...
11,692
Given the following text description, write Python code to implement the functionality described below step by step Description: Formulas Step1: Import convention You can import explicitly from statsmodels.formula.api Step2: Alternatively, you can just use the formula namespace of the main statsmodels.api. Step3: O...
Python Code: import numpy as np # noqa:F401 needed in namespace for patsy import statsmodels.api as sm Explanation: Formulas: Fitting models using R-style formulas Since version 0.5.0, statsmodels allows users to fit statistical models using R-style formulas. Internally, statsmodels uses the patsy package to convert ...
11,693
Given the following text description, write Python code to implement the functionality described below step by step Description: Read Loans csv and Create test/train csv files Step1: Read and process train and test dataframes Step2: Model Tuning with skopt Step3: GBM best results - sorted Step4: XGB best results -...
Python Code: %%time print('Reading: loan_stat542.csv into loans dataframe...') loans = pd.read_csv('loan_stat542.csv') print('Loans dataframe:', loans.shape) test_ids = pd.read_csv('Project3_test_id.csv', dtype={'test1':int,'test2':int, 'test3':int,}) print('ids dataframe:', test_ids.shape) trains = [] tests = [] label...
11,694
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook explores the speed of searching for values in sets and lists. After reading this notebook, watch Brandon Rhodes' videos All Your Ducks In A Row Step1: Notice that the differen...
Python Code: def make_list(n): if True: return list(range(n)) else: return list(str(i) for i in range(n)) n = int(25e6) # n = 5 m = (0, n // 2, n-1, n) a_list = make_list(n) a_set = set(a_list) n, m # Finding something that is in a set is fast. # The key one is looking for has little effect on t...
11,695
Given the following text description, write Python code to implement the functionality described below step by step Description: Spark Cluster Overview Spark applications run as independent sets of processes on a cluster, coordinated by the SparkContext object in your main program (called the driver program). Step1: ...
Python Code: import socket Explanation: Spark Cluster Overview Spark applications run as independent sets of processes on a cluster, coordinated by the SparkContext object in your main program (called the driver program). End of explanation print( "Hello World from " + socket.gethostname() ) Explanation: This code runs...
11,696
Given the following text description, write Python code to implement the functionality described below step by step Description: Fruitful Functions Return Values Some of the built-in functions we have used, such as the math functions, produce results. Calling the function generates a value, which we usually assign to ...
Python Code: import math e = math.exp(1.0) e Explanation: Fruitful Functions Return Values Some of the built-in functions we have used, such as the math functions, produce results. Calling the function generates a value, which we usually assign to a variable or use as part of an expression. End of explanation # Functio...
11,697
Given the following text description, write Python code to implement the functionality described below step by step Description: Process U-Wind Step1: 2. Read u-wind data and pick variables 2.1 Use print to check variable information Actually, you can also use numdump infile.nc -h to check the same inforamtion Step2:...
Python Code: % matplotlib inline from pylab import * import numpy as np from scipy.interpolate import interp2d from netCDF4 import Dataset as netcdf # netcdf4-python module import matplotlib.pyplot as plt from matplotlib.pylab import rcParams rcParams['figure.figsize'] = 12, 6 Explanation: Process U-Wind: Zonal Mean an...
11,698
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with data files Reading and writing data files is a common task, and Python offers native support for working with many kinds of data files. Today, we're going to be working mainly w...
Python Code: # open the MLB data file `as` mlb # create a reader object # loop over the rows in the file # assign variables to each element in the row (shortcut!) # print the row, which is a list Explanation: Working with data files Reading and writing data files is a...
11,699
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ...
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's wor...