Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
800
Given the following text description, write Python code to implement the functionality described below step by step Description: Imports Step1: Algorithm Pseudocode Step2: Actual Code Step3: Algorithm Conditions We believe nonMaxSupression will perform well if and only if the histogram of the data is capable of pro...
Python Code: import sys import scipy.io as sio import glob import numpy as np import matplotlib.pyplot as plt from skimage.filters import threshold_otsu sys.path.append('../code/functions') import qaLib as qLib sys.path.append('../../pipeline_1/code/functions') import connectLib as cLib from IPython.display import Imag...
801
Given the following text description, write Python code to implement the functionality described below step by step Description: Performing scripts with python-fmrest This is a short example on how to perform scripts with python-fmrest. Import the module Step1: Create the server instance Step2: Login The login metho...
Python Code: import fmrest Explanation: Performing scripts with python-fmrest This is a short example on how to perform scripts with python-fmrest. Import the module End of explanation fms = fmrest.Server('https://10.211.55.15', user='admin', password='admin', ...
802
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploratory data analysis Whenever you collect a new dataset, a good first step is to explore it. This means different things for different kinds of datasets, but if it's a timeseries then t...
Python Code: import numpy as np from scipy import io as si from matplotlib import pyplot as plt import h5py %matplotlib inline Explanation: Exploratory data analysis Whenever you collect a new dataset, a good first step is to explore it. This means different things for different kinds of datasets, but if it's a timeser...
803
Given the following text description, write Python code to implement the functionality described below step by step Description: <figure> <IMG SRC="https Step1: Simultaneously plot three graphs This shows a way to read data from the current directory and then plot these in a single figure. The data file need to be ...
Python Code: import numpy as np import matplotlib.pyplot as plt aList = ['a', 'quark', 'flies', 'in', 'this', 'room', 'at', 3, 'oclock'] # print("{} {} {} {} {} {} {} {} {}".format(1,2,'three',4,5,6,6, 7, 8, 9)) # (aList)) print("{} {} {} {} {} {} {} {} {}".format(*aList)) plt.legend? import numpy as np ...
804
Given the following text description, write Python code to implement the functionality described below step by step Description: Training DeepMind's Atari DQN with Chimp Load Chimp modules Step1: Load Python packages Step2: Set training parameters Step3: You may want to set a smaller number of iterations (like 1000...
Python Code: from chimp.memories import ReplayMemoryHDF5 from chimp.learners.dqn_learner import DQNLearner from chimp.learners.chainer_backend import ChainerBackend from chimp.simulators.atari import AtariSimulator from chimp.agents import DQNAgent Explanation: Training DeepMind's Atari DQN with Chimp Load Chimp module...
805
Given the following text description, write Python code to implement the functionality described below step by step Description: Image Recognition on MNIST using PyTorch Lightning Demonstrating the elements of machine learning Step1: Pytorch Lightning Module PyTorch Lightning Module has a PyTorch ResNet18 Model. It i...
Python Code: %pip install pytorch-lightning --upgrade %pip install torchmetrics --upgrade import torch import torchvision import wandb from argparse import ArgumentParser from pytorch_lightning import LightningModule, Trainer, Callback from pytorch_lightning.loggers import WandbLogger from torchmetrics.functional impor...
806
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bnu', 'sandbox-2', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: BNU Source ID: SANDBOX-2 Topic: Aerosol Sub-Topics: Transport, Emissions, ...
807
Given the following text description, write Python code to implement the functionality described below step by step Description: Stock analysis Step1: The volatility calculation is made using the return for each day, given the close price of any stock. As we are interested in the annual volatility, this needs to be s...
Python Code: import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=(12,12)) Explanation: Stock analysis: returns and volatility This notebook aims to explore the Markowitz theory on modern portfolios with a little of code and a little of maths...
808
Given the following text description, write Python code to implement the functionality described below step by step Description: Answering Descriptive and Exploratory Questions About my Project Step1: Descriptive <br /> - What is N<sub>i</sub> for all i? Step2: What is |V|? Step3: Do the graphs G<sub>n<sub>i</sub><...
Python Code: # Import packages import igraph as ig import numpy as np import math import os from subprocess import Popen, PIPE # Initializing dataset names dnames = list(['../data/desikan/MRN114', '../data/desikan/KKI2009', '../data/desikan/SWU4']) print "Datasets: " + ", ".join(dnames) print "D = " + str(len(dnames)) ...
809
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'messy-consortium', 'sandbox-1', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MESSY-CONSORTIUM Source ID: SANDBOX-1 Topic: Aerosol Sub-Topi...
810
Given the following text description, write Python code to implement the functionality described below step by step Description: 机器学习工程师纳米学位 入门 项目 0 Step1: 从泰坦尼克号的数据样本中,我们可以看到船上每位旅客的特征 Survived:是否存活(0代表否,1代表是) Pclass:社会阶级(1代表上层阶级,2代表中层阶级,3代表底层阶级) Name:船上乘客的名字 Sex:船上乘客的性别 Age Step3: 这个例子展示了如何将泰坦尼克号的 Survived 数据从 Data...
Python Code: import numpy as np import pandas as pd # RMS Titanic data visualization code # 数据可视化代码 from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset # 加载数据集 in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few en...
811
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of DOV search methods for soil data (bodemgegevens) Use cases explained below Introduction to the bodem-objects Get bodemsites in a bounding box Get bodemlocaties with specific prope...
Python Code: %matplotlib inline import inspect, sys import warnings; warnings.simplefilter('ignore') # check pydov path import pydov Explanation: Example of DOV search methods for soil data (bodemgegevens) Use cases explained below Introduction to the bodem-objects Get bodemsites in a bounding box Get bodemlocaties wit...
812
Given the following text description, write Python code to implement the functionality described below step by step Description: For this to work you are going to need a collection of engines to connect to. You can probably create a local collection by just running ipcluster -n 8; for more sophisticated setups read th...
Python Code: c = Client() c.ids Explanation: For this to work you are going to need a collection of engines to connect to. You can probably create a local collection by just running ipcluster -n 8; for more sophisticated setups read the ipyparallel docs. You set up "profiles" and can start and connect to different engi...
813
Given the following text description, write Python code to implement the functionality described below step by step Description: Kaggle San Francisco Crime Classification Berkeley MIDS W207 Final Project Step1: Local, individual load of updated data set (with weather data integrated) into training, development, and t...
Python Code: # Additional Libraries %matplotlib inline import matplotlib.pyplot as plt # Import relevant libraries: import time import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn import preprocessing from sklearn.preprocessing import MinMaxScaler from sklearn.preproce...
814
Given the following text description, write Python code to implement the functionality described below step by step Description: Optymalizacja i propagacja wsteczna (backprop) Zaczniemy od prostego przykładu. Funkcji kwadratowej Step1: Funkcja ta ma swoje minimum w punkcie $x = 0$. Jak widać na powyższym rysunku, gdy...
Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn %matplotlib inline x = np.linspace(-3, 3, 100) plt.plot(x, x**2, label='f(x)') # optymalizowana funkcja plt.plot(x, 2 * x, label='pochodna -- f\'(x)') # pochodna plt.legend() plt.show() Explanation: Optymalizacja i propagacja wsteczna (bac...
815
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Gaussian Mixture Models and Expectation Maximisation in Shogun By Heiko Strathmann - <a href="mailto Step2: Set up the model in Shogun Step3: Sampling from mixture models Sampling i...
Python Code: %pylab inline %matplotlib inline # import all Shogun classes from modshogun import * from matplotlib.patches import Ellipse # a tool for visualisation def get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color="red", linewidth=3): Returns an ellipse artist for nstd times the standard deviation of...
816
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright (c)2015 DiGangi, C. Managing Epidemics Through Mathematical Modeling This lesson will examine the spread of an epidemic over time using Euler's method. The model is a system of non...
Python Code: %matplotlib inline import numpy from matplotlib import pyplot from matplotlib import rcParams rcParams['font.family'] = 'serif' rcParams['font.size'] = 16 Explanation: Copyright (c)2015 DiGangi, C. Managing Epidemics Through Mathematical Modeling This lesson will examine the spread of an epidemic over tim...
817
Given the following text description, write Python code to implement the functionality described below step by step Description: Import data Step1: Analyse Emails Step2: The columns ExtractedBodyText is supposed to be the content of the mail but some of the mail have a ExtractedBodyText = NaN but the Rawtext seems t...
Python Code: folder = 'hillary-clinton-emails/' emails = pd.read_csv(folder + 'Emails.csv', index_col='Id') emails.head(5) Explanation: Import data End of explanation emails.head() Explanation: Analyse Emails End of explanation emails.columns print('Number of emails: ', len(emails)) bodyNaN = emails.ExtractedBodyText.i...
818
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Neural Networks Step2: 2 - Outline of the Assignment You will be implementing the building blocks of a convolutional neural network! Each function you will implement will have...
Python Code: import numpy as np import h5py import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1) Explanation: Con...
819
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Function To Visualize Classification Regions You can ignore the code below. It is used to visualize the the decision regions of the classifier. However it is unimportant...
Python Code: # Import packages to visualize the classifer from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt import warnings # Import packages to do the classifying import numpy as np from sklearn.svm import SVC Explanation: Title: SVC Parameters When Using RBF Kernel Slug: svc_parameters_usin...
820
Given the following text description, write Python code to implement the functionality described below step by step Description: 1 Simple Octave/MATLAB Function As a quick warm up, create a function to return a 5x5 identity matrix. Step1: 2 Linear Regression with One Variable In this part of this exercise, you will i...
Python Code: A = np.eye(5) print(A) Explanation: 1 Simple Octave/MATLAB Function As a quick warm up, create a function to return a 5x5 identity matrix. End of explanation datafile = 'ex1\\ex1data1.txt' df = pd.read_csv(datafile, header=None, names=['Population', 'Profit']) def plot_data(x, y): plt.figure(figsize=(1...
821
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy elegance and curve smoothing I recently came across a blog where smoothing of data was discussed. The following function was used to smooth a data set with a Gaussian kernel. Read the ...
Python Code: def smoothListGaussian(list,degree=5): list =[list[0]]*(degree-1) + list + [list[-1]]*degree window=degree*2-1 weight=np.array([1.0]*window) weightGauss=[] for i in range(window): i=i-degree+1 frac=i/float(window) gauss=1/(np.exp((4*(frac))**2)) ...
822
Given the following text description, write Python code to implement the functionality described below step by step Description: we can check the output of this cell to kind of see how much new structural data we acquire with more properties Step1: so some keras version stuff. 1.0 uses keras.losses to store its loss ...
Python Code: properties = ['density', 'cpt', 'viscosity', 'thermal_conductivity', 'melting_point'] for i in range(len(properties)): props = properties[:i+1] devmodel = salty.aggregate_data(props, merge='Union') devmodel.Data['smiles_string'] = devmodel.Data['smiles-cation'] + "." + devmodel.Da...
823
Given the following text description, write Python code to implement the functionality described below step by step Description: GA4GH 1000 Genome Sequence Annotation Example This example illustrates how to access the sequence annotations for a given set of .... Initialize Client In this step we create a client object...
Python Code: import ga4gh_client.client as client c = client.HttpClient("http://1kgenomes.ga4gh.org") Explanation: GA4GH 1000 Genome Sequence Annotation Example This example illustrates how to access the sequence annotations for a given set of .... Initialize Client In this step we create a client object which will be ...
824
Given the following text description, write Python code to implement the functionality described below step by step Description: The HRT for mixed data types (Python implementation) In my last post I showed how the holdout random test (HRT) could be used to obtain valid p-values for any machine learning model by sampl...
Python Code: # import the necessary modules import pandas as pd import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification import seaborn as sns Explanation: The HRT for mixed data types (Python implementation) In my last post I showed how the holdout random ...
825
Given the following text description, write Python code to implement the functionality described below step by step Description: Stationarity and detrending (ADF/KPSS) Stationarity means that the statistical properties of a time series i.e. mean, variance and covariance do not change over time. Many statistical models...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm Explanation: Stationarity and detrending (ADF/KPSS) Stationarity means that the statistical properties of a time series i.e. mean, variance and covariance do not change over time. Many sta...
826
Given the following text description, write Python code to implement the functionality described below step by step Description: Index - Back Asynchronous Widgets This notebook covers two scenarios where we'd like widget-related code to run without blocking the kernel from acting on other execution requests Step1: We...
Python Code: %gui asyncio Explanation: Index - Back Asynchronous Widgets This notebook covers two scenarios where we'd like widget-related code to run without blocking the kernel from acting on other execution requests: Pausing code to wait for user interaction with a widget in the frontend Updating a widget in the bac...
827
Given the following text description, write Python code to implement the functionality described below step by step Description: Initialize set up Amplifyer is fet -15V and = +85V Calibrate strain gauge to zero with the kinesis software Pull fiber back Set nicard to -3.75 Step1: Move close with fiber
Python Code: cavitylogic._ni.cavity_set_voltage(0.0) cavitylogic._current_filepath = r'C:\BittorrentSyncDrive\Personal - Rasmus\Rasmus notes\Measurements\171001_position15_2' cavitylogic.last_sweep = None cavitylogic.get_nth_full_sweep(sweep_number=1, save=True) Explanation: Initialize set up Amplifyer is fet -15V and ...
828
Given the following text description, write Python code to implement the functionality described below step by step Description: Train tensorflow or keras model on GCP or Kubeflow from Notebooks This notebook introduces you to using Kubeflow Fairing to train the model to Kubeflow on Google Kubernetes Engine (GKE), and...
Python Code: import os import logging import tensorflow as tf import fairing import numpy as np from datetime import datetime from fairing.cloud import gcp # Setting up google container repositories (GCR) for storing output containers # You can use any docker container registry istead of GCR # For local notebook, GCP_P...
829
Given the following text description, write Python code to implement the functionality described below step by step Description: Graphs Step1: Variables Step2: lazy evaluation Step3: This is what happens when we operate on two variables that are from different graphs Step4: Variable initialization all tf.Variables...
Python Code: tf.get_default_graph() graph = tf.Graph() graph tf.get_default_graph() Explanation: Graphs End of explanation x1 = tf.Variable(3.0, name='x') y1 = tf.Variable(4.0) x1, y1 x1.name, y1.name x1.graph is tf.get_default_graph() y1.graph is tf.get_default_graph() with graph.as_default(): x2 = tf.Variable(4.1...
830
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Python Objects Test Advanced Numbers Problem 1 Step1: Problem 2 Step2: Advanced Strings Problem 3 Step3: Problem 4 Step4: Advanced Sets Problem 5 Step5: Problem 6 Step6: Advan...
Python Code: print hex(1024) Explanation: Advanced Python Objects Test Advanced Numbers Problem 1: Convert 1024 to binary and hexadecimal representation: End of explanation print round(5.23222,2) Explanation: Problem 2: Round 5.23222 to two decimal places End of explanation s = 'hello how are you Mary, are you feeling ...
831
Given the following text description, write Python code to implement the functionality described below step by step Description: Данные Зайдите на https Step1: Предобработка <div class="panel panel-warning"> <div class="panel-heading"> <h3 class="panel-title">Обратите внимание</h3> </div> </div> Пред...
Python Code: train_X, train_y = pd.read_csv( # путь к вашему файлу train.csv 'data/WaterTable/train.csv' ), pd.read_csv( # путь к вашему файлу trainLabels.csv 'data/WaterTable/trainLabels.csv' ) df = pd.merge(train_X, train_y, how='left') df_test = pd.read_csv( # путь к вашему файлу test.csv 'data/WaterTabl...
832
Given the following text description, write Python code to implement the functionality described below step by step Description: Python 基本語法與科學計算套件的使用: Python科學計算套件(一) 四堂課程大綱 第一堂-Python 基礎(一):Python 簡介及環境建立、Python程式的編寫及執行、資料型態、基本輸入輸出、流程控制 第二堂-Python 基礎(二):檔案讀寫、例外處理、函數、模組、物件導向 第三堂-Python科學計算套件(一):Numpy、Matplotlib 第四堂-...
Python Code: period = [2.4, 5, 6.3, 4.1] print(60 * period) bh_mass = [4.3, 5.8, 9.5, 7.6] MASS_SUN = 1.99 * 10 ** 30 print(MASS_SUN * bh_mass) time = list(range(1,10, 0.1)) Explanation: Python 基本語法與科學計算套件的使用: Python科學計算套件(一) 四堂課程大綱 第一堂-Python 基礎(一):Python 簡介及環境建立、Python程式的編寫及執行、資料型態、基本輸入輸出、流程控制 第二堂-Python 基礎(二):檔案讀寫、例...
833
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: As always, let's do imports and initialize a logger and a new Bundle. Step2: Passband Options Passband options follow the exact same rules as dataset columns. Sending a sin...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: Advanced: Datasets Datasets tell PHOEBE how and at what times to compute the model. In some cases these will include the actual observational data, and in other cases may only include the times at which you want to compute a synthetic model. If you're not a...
834
Given the following text description, write Python code to implement the functionality described below step by step Description: Understanding Tree SHAP for Simple Models The SHAP value for a feature is the average change in model output by conditioning on that feature when introducing features one at a time over all ...
Python Code: import sklearn import shap import numpy as np import graphviz Explanation: Understanding Tree SHAP for Simple Models The SHAP value for a feature is the average change in model output by conditioning on that feature when introducing features one at a time over all feature orderings. While this is easy to s...
835
Given the following text description, write Python code to implement the functionality described below step by step Description: Jupyter Notebooks (libros de notas o cuadernos Jupyter) Puedes ejecutar un Cell (celda) pulsando [shift] + [Enter] o presionando el botón Play en la barra de herramientas. Puedes obtener ayu...
Python Code: import numpy as np # Semilla de números aleatorios (para reproducibilidad) rnd = np.random.RandomState(seed=123) # Generar una matriz aleatoria X = rnd.uniform(low=0.0, high=1.0, size=(3, 5)) # dimensiones 3x5 print(X) Explanation: Jupyter Notebooks (libros de notas o cuadernos Jupyter) Puedes ejecutar un...
836
Given the following text description, write Python code to implement the functionality described below step by step Description: k-Nearest Neighbor (kNN) exercise Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ...
Python Code: # Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt from __future__ import print_function # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplo...
837
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'sandbox-2', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: CNRM-CERFACS Source ID: SANDBOX-2 Topic: Landice Sub-Topics: Glac...
838
Given the following text description, write Python code to implement the functionality described below step by step Description: solarposition.py tutorial This tutorial needs your help to make it better! Table of contents Step1: SPA output Step2: Speed tests Step3: This numba test will only work properly if you hav...
Python Code: import datetime # scientific python add-ons import numpy as np import pandas as pd # plotting stuff # first line makes the plots appear in the notebook %matplotlib inline import matplotlib.pyplot as plt # finally, we import the pvlib library import pvlib import pvlib from pvlib.location import Location Ex...
839
Given the following text description, write Python code to implement the functionality described below step by step Description: Step 0 - hyperparams Step1: Step 1 - collect data Step2: (689, 682, 7) (689, 682, 6) (689,) (689, 682) Step3: Step 2 - Build model Step4: targets Tensor("data/strided_slice Step5: Step ...
Python Code: factors(689) max_seq_len = 682 data_path = '../../../../Dropbox/data' phae_path = data_path + '/price_hist_autoencoder' npz_dates = phae_path + '/price_history_full_seqs_dates.npz' assert path.isfile(npz_dates) npz_train = phae_path + '/price_history_seqs_dates_normed_train.npz' assert path.isfile(npz_trai...
840
Given the following text description, write Python code to implement the functionality described below step by step Description: Probability calibration of classifiers When performing classification you often want to predict not only the class label, but also the associated probability. This probability gives you some...
Python Code: print(__doc__) # Author: Mathieu Blondel <mathieu@mblondel.org> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Balazs Kegl <balazs.kegl@gmail.com> # Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # License: BSD Style. import numpy as np import matplotlib.pyplot ...
841
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Tensorflow Lite Gesture Classification Example Conversion Script This guide shows how you can go about converting the model trained with Tensor...
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...
842
Given the following text description, write Python code to implement the functionality described below step by step Description: Loopless FBA The goal of this procedure is identification of a thermodynamically consistent flux state without loops, as implied by the name. Usually, the model has the following constraints...
Python Code: from matplotlib.pylab import * %matplotlib inline import cobra.test from cobra import Reaction, Metabolite, Model from cobra.flux_analysis.loopless import construct_loopless_model from cobra.solvers import get_solver_name Explanation: Loopless FBA The goal of this procedure is identification of a thermodyn...
843
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: Classification might be the most well-known application of Bayesian methods, made famous in the 1990...
Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py from os.path import basename, exists def download(url): filename = basename(url) if not exists(...
844
Given the following text description, write Python code to implement the functionality described below step by step Description: <b>Acknowledgements Step1: Parsing HTML with BeautifulSoup Now that we've downloaded the HTML of the page, we next need to parse it. Let's say we want to extract all of the names, ages, and...
Python Code: pet_pages = ["https://www.boulderhumane.org/animals/adoption/dogs", "https://www.boulderhumane.org/animals/adoption/cats", "https://www.boulderhumane.org/animals/adoption/adopt_other"] r = requests.get(pet_pages[0]) html = r.text print(html[:500]) # Print the first 500 character...
845
Given the following text description, write Python code to implement the functionality described below step by step Description: Step7: Notebook to calculate the water permeation into packaging. Step8: Define the simulation parameters Step9: Loop through user events Calculate the water flux between two points in tim...
Python Code: import numpy as np import pandas as pd import argparse as ap def mass_density_sat(T): Mass of water in one cubic meter of air at one bar at temperature T parameters: T: float - Temperature (K) returns float - mass of water in one cubic meter saturated air (kg/m^3) r...
846
Given the following text description, write Python code to implement the functionality described below step by step Description: An introduction to solving biological problems with Python Session 2.3 Step1: open takes an optional second argument specifying the mode in which the file is opened, either for reading, wri...
Python Code: path = "data/datafile.txt" fileObj = open( path ) Explanation: An introduction to solving biological problems with Python Session 2.3: Files Using files Reading from files Exercises 2.3.1 Writing to files Exercises 2.3.2 Data input and output (I/O) So far, all that data we have been working with has been w...
847
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Statistical Analysis of Data Statistics are numbers that can be used to describe or summarize variable data points. For example, the expected value of a distribution a...
Python Code: # 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 # distribute...
848
Given the following text description, write Python code to implement the functionality described below step by step Description: Graphical analysis of stresses Step2: Mohr circle for 2D stresses Step4: Mohr circle for 3D stresses
Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.linalg import eigvalsh from ipywidgets import interact from IPython.display import display from matplotlib import rcParams %matplotlib notebook rcParams['font.family'] = 'serif' rcParams['font.size'] = 16 Explanation: Graphical analysis of stres...
849
Given the following text description, write Python code to implement the functionality described below step by step Description: 人生苦短,我用python python第三课 推荐一个python数据结构可视化工具:http Step1: json格式 mysql数据库基本操作 命令行操作 Step2: 数据库管理工具 sequelpro 链接:http Step3: mysql数据类型 http Step4: 修改数据 Step5: 删除操作 Step6: 使用python去操作数...
Python Code: import json data_1 = "{'a': 1, 'b': 2, 'c': 3}" data_2 = '{"a": 1, "b": 2, "c": 3}' j_data = json.loads(data_2) type(j_data) with open('/Users/wangyujie/Desktop/data.json', 'r') as f: j_data = json.load(f) print(j_data) Explanation: 人生苦短,我用python python第三课 推荐一个python数据结构可视化工具:http://www.pythontutor...
850
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 08c Step1: Next, let's load the data. Write the path to your ml-100k.csv file in the cell below Step2: Execute the cell below to load the CSV data into a pandas data frame indexed by t...
Python Code: %matplotlib inline import pandas as pd from sklearn.metrics import mean_absolute_error from sklearn.model_selection import GridSearchCV, KFold, cross_val_predict from sklearn.neighbors import KNeighborsRegressor Explanation: Lab 08c: Recommender systems Introduction In this lab, you will build a simple mov...
851
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Custom regression models Like for univariate models, it is possible to create your own custom parametric survival models. Why might you want to do this? Create new / extend AFT model...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' from lifelines.fitters import ParametricRegressionFitter from autograd import numpy as np from lifelines.datasets import load_rossi class ExponentialAFTFitter(ParametricRegressionFitter): # this class property is necessary, and shou...
852
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-2', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: CSIRO-BOM Source ID: SANDBOX-2 Topic: Atmos Sub-Topics: Dynamical Core, ...
853
Given the following text description, write Python code to implement the functionality described below step by step Description: Train and valid set NLL trace Step1: Visualising first layer weights Quite nice features appear to have been learned with some kernels appearing to have been learned at various rotations. S...
Python Code: tr = np.array(model.monitor.channels['valid_y_y_1_nll'].time_record) / 3600. fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(111) ax1.plot(model.monitor.channels['valid_y_y_1_nll'].val_record) ax1.plot(model.monitor.channels['train_y_y_1_nll'].val_record) ax1.set_xlabel('Epochs') ax1.legend(['Valid'...
854
Given the following text description, write Python code to implement the functionality described below step by step Description: The problem Step1: Extract lon, lat variables from vgrid2 and u, v variables from vbaro. The goal is to split the joint variables into individual CF compliant phenomena. Step2: Using iris ...
Python Code: from netCDF4 import Dataset #url = ('http://geoport.whoi.edu/thredds/dodsC/usgs/data2/rsignell/gdrive/' # 'nsf-alpha/Data/MIT_MSEAS/MSEAS_Tides_20160317/mseas_tides_2015071612_2015081612_01h.nc') url = ('/usgs/data2/rsignell/gdrive/' 'nsf-alpha/Data/MIT_MSEAS/MSEAS_Tides_20160317/mseas_tides_2...
855
Given the following text description, write Python code to implement the functionality described below step by step Description: Another language NOTE before starting To change the notebook which is launched by default by the "programming with Jupyter" tab in puppet-master interface Go to My Documents/ Poppy source-c...
Python Code: from pypot.creatures import PoppyErgoJr poppy = PoppyErgoJr(use_http=True, use_snap=True) # If you want to use another robot (humanoid, torso, ...) adapt this code #from pypot.creatures import PoppyTorso #poppy = PoppyTorso(use_http=True, use_snap=True) # If you want to use the robot with the camera unplug...
856
Given the following text description, write Python code to implement the functionality described below step by step Description: 4. PyNGL basics PyNGL is a Python language module for creating 2D high performance visualizations of scientific data. It is based on NCL graphics but still not as extensive as NCL's last ver...
Python Code: import Ngl Explanation: 4. PyNGL basics PyNGL is a Python language module for creating 2D high performance visualizations of scientific data. It is based on NCL graphics but still not as extensive as NCL's last version 6.6.2. The aim of this notebook is to give you an introduction to PyNGL, read your data ...
857
Given the following text description, write Python code to implement the functionality described below step by step Description: <p><font size="6"><b> CASE - air quality data of European monitoring stations (AirBase)</b></font></p> © 2021, Joris Van den Bossche and Stijn Van Hoey (&#106;&#111;&#114;&#105;&#115;&#118;...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt Explanation: <p><font size="6"><b> CASE - air quality data of European monitoring stations (AirBase)</b></font></p> © 2021, Joris Van den Bossche and Stijn Van Hoey (&#106;&#111;&#114;&#105;&#115;&#118;&#97;&#110;&#100;&#101;&#110;&#98...
858
Given the following text description, write Python code to implement the functionality described below step by step Description: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb...
Python Code: import time import numpy as np import tensorflow as tf import random from collections import Counter import utils Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn...
859
Given the following text description, write Python code to implement the functionality described below step by step Description: $$ \def\CC{\bf C} \def\QQ{\bf Q} \def\RR{\bf R} \def\ZZ{\bf Z} \def\NN{\bf N} $$ Exemples (def + while + for + if) Step1: On a vu dans les chapitres précédents comment définir des fonctions...
Python Code: from __future__ import division, print_function # Python 3 Explanation: $$ \def\CC{\bf C} \def\QQ{\bf Q} \def\RR{\bf R} \def\ZZ{\bf Z} \def\NN{\bf N} $$ Exemples (def + while + for + if) End of explanation def syracuse(n): while n != 1: print(n, end=' ') if n % 2 == 0: n =...
860
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Содержание<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Получение-среза" data-toc-modified-id="Получение-среза-1">Получение среза</a></span...
Python Code: lst = [1, 2, 3, 4, 5, 6, 7, 8] print(lst[::]) Explanation: <h1>Содержание<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Получение-среза" data-toc-modified-id="Получение-среза-1">Получение среза</a></span><ul class="toc-item"><li><span><a href="#Без-параметров" ...
861
Given the following text description, write Python code to implement the functionality described below step by step Description: Tweaking the cellpy file format A cellpy file is a hdf5-type file. From v.5 it contains five top-level directories. ```python from cellreader.py raw_dir = prms._cellpyfile_raw step_dir = prm...
Python Code: %load_ext autoreload %autoreload 2 from pathlib import Path from pprint import pprint import pandas as pd import cellpy Explanation: Tweaking the cellpy file format A cellpy file is a hdf5-type file. From v.5 it contains five top-level directories. ```python from cellreader.py raw_dir = prms._cellpyfile_ra...
862
Given the following text description, write Python code to implement the functionality described below step by step Description: Idea Результат (ожидаемый) обучение происходит на своем родном канале на симулированных данных учитываются различия симуляции и данных (см. ниже алгоритм) оценка качества (как и калибровка) ...
Python Code: %pylab inline figsize(8, 6) import sys sys.path.insert(0, "../") Explanation: Idea Результат (ожидаемый) обучение происходит на своем родном канале на симулированных данных учитываются различия симуляции и данных (см. ниже алгоритм) оценка качества (как и калибровка) будут несмещенными качество лучше, чем ...
863
Given the following text description, write Python code to implement the functionality described below step by step Description: 23-10-2017 <center> <h1> Computational Quantum Dynamics </h1> </center> Exercise 1 3. Eigen values of random Hermitian matrices. (a) Write a Python script that generates a complex random ...
Python Code: import numpy as np from numpy import linalg as LA import matplotlib.pyplot as plt from math import factorial from itertools import combinations_with_replacement from scipy.integrate import quad %matplotlib inline def generate_random_hermitian(N): A = np.random.normal(size=(N, N)) H = (np.tril(A) ...
864
Given the following text description, write Python code to implement the functionality described below step by step Description: 阅读笔记 作者:方跃文 Email Step1: 由于这个是逗号隔开的文本,我们可以方便地使用 read_csv 来读入数据 Step2: 上面这个例子中是已经包含了header部分了,但并不是所有数据都自带header,例如 Step3: df1中我没有指明是header=None,所以原始文件中都第一行被错误地用作了header。为了 避免这种错误,需要明确指明...
Python Code: !cat chapter06/ex1.csv Explanation: 阅读笔记 作者:方跃文 Email: fyuewen@gmail.com ** 时间:始于2018年3月6日, 结束写作于 2018年7月27日, 2018年11月复习一次。 第六章 数据加载、存储和文件格式 数据如果不能导入和导出,那么本书中介绍的工具自然也就没有用武之地了。在我们的日常生活和研究中,有许多文件输入和输出的应用场景。 输入和输出通常划分为几个大类:读取文本文件和其他更高效的磁盘存储格式,加载数据库中的数据,利用web api操作网络资源。 读写文本格式的数据 pandas 提供了一些用于将表格型数据读取为 Da...
865
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
866
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Lump Sum vs. Dollar Cost Averaging (DCA) investing View Notebook as HTML View Notebook on GitHub View Notebook on Blog The topic of investing all at once versus spreading it over t...
Python Code: import pandas as pd import pandas_datareader.data as web import datetime pd.set_option('display.width', 200) # Displaying more columns in one row # Data date range, Google provides up to 4000 entries in one call start = datetime.datetime(2000, 2, 10) end = datetime.datetime(2016, 1, 9) spy = web.DataReade...
867
Given the following text description, write Python code to implement the functionality described below step by step Description: Nonlinear elasticity Step1: In this chapter we investigate a nonlinear model of elastic strain in heterogeneous materials. This system is equivalent to the $p$-system of gas dynamics, alth...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'svg' import matplotlib as mpl mpl.rcParams['font.size'] = 8 figsize =(8,4) mpl.rcParams['figure.figsize'] = figsize import numpy as np from scipy.optimize import fsolve import matplotlib.pyplot as plt from utils import riemann_tools from ipywidgets ...
868
Given the following text description, write Python code to implement the functionality described below step by step Description: according to the histogram, the ratios are mainly under 0.2. Step1: Improved app Step2: improved pattern Step3: woren pattern
Python Code: index = ratio>0.05#get the index of ratio larger than 0.05 appfilter = app.loc[index]#filter the apps which number of current rating over number of overall rating larger than 0.1 #use histogram to show the range of current_rating-overall_rating plt.hist(appfilter['current_rating']-appfilter['overall_rating...
869
Given the following text description, write Python code to implement the functionality described below step by step Description: k-近邻算法 优点: 精度高、对异常值不敏感、无数据输入假定 缺点: 计算复杂度高、空间复杂度高、无法给出数据的内在含义 适用数据范围: 数值型和标称型 k-近邻算法更适用于数据集很大很全的情况? 算法思想及过程 对要分类的样本,在已有样本中寻找最近邻的 K 个样本,以这 K 个样本的分类标签中出现次数最多的标签作为待分类样本的分类标签。 寻找最近邻时,通过距离(欧几里得距离)...
Python Code: from numpy import * import operator def createDataSet(): group = array([[1.0, 1.1],[1.0, 1.0],[0, 0],[0, 0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labels Explanation: k-近邻算法 优点: 精度高、对异常值不敏感、无数据输入假定 缺点: 计算复杂度高、空间复杂度高、无法给出数据的内在含义 适用数据范围: 数值型和标称型 k-近邻算法更适用于数据集很大很全的情况? 算法思想及过程 对要分类的样本,在已有样本中寻找最近邻的 ...
870
Given the following text description, write Python code to implement the functionality described below step by step Description: Inefficient photon detection Step1: Direct photo-detection Here we follow an example from Wiseman and Milburn, Quantum measurement and control, section. 4.8.1. Consider cavity that leaks ph...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from qutip import * from qutip.expect import expect_rho_vec from matplotlib import rcParams rcParams['font.family'] = 'STIXGeneral' rcParams['mathtext.fontset'] = 'stix' rcParams['font.size'] = '14' Explanation: Inefficient photon detect...
871
Given the following text description, write Python code to implement the functionality described below step by step Description: Sum of amounts in the TN bucket of the test dataset. Step1: Sum of amounts in the FN bucket of the test dataset.
Python Code: df.Amount.values[training_size:][(y_test == 0) & (y_test_predict == 0)].sum() Explanation: Sum of amounts in the TN bucket of the test dataset. End of explanation df.Amount.values[training_size:][(y_test == 1) & (y_test_predict == 0)].sum() 100 * 8336.05/7224977.58 Explanation: Sum of amounts in the FN buc...
872
Given the following text description, write Python code to implement the functionality described below step by step Description: rotate_error_ellipse 誤差楕円の回転がなぜ、共分散行列の両側から回転行列をかけているのかよくわからない。 なので実際に回してみるコードを書いてみた。 Step1: 共分散行列を回転させる部分を以下に抜き出してみた。 Step2: 試しに左側だけ掛けてみる。 虚数解が出たらしい。傾き22.5度の直線を軸に90度回転しているっぽい。 前後にも飛び出している状...
Python Code: %matplotlib inline import numpy as np import math import matplotlib.pyplot as plt from matplotlib.patches import Ellipse class Error_ellipse: def __init__(self, sigma_x = 1.0, sigma_y = 1.0, cov_xy = 0.0, mu_x = 0.0, mu_y = 0.0): self.cov = np.array([[sigma_x, cov_xy], [cov_xy, sigma_y]]) # ...
873
Given the following text description, write Python code to implement the functionality described below step by step Description: Usable Data Map (UDM2) Cloud Detection In this guide, you'll learn about Planet's automatic detection of pixels which are cloudy or otherwise obscured, so that you can make more intelligent ...
Python Code: from planet import api import time import os import rasterio from rasterio.plot import show client = api.ClientV1() # build a filter for the AOI filter = api.filters.range_filter("clear_percent", gte=90) # show the structure of the filter print(filter) # we are requesting PlanetScope 4 Band imagery item_ty...
874
Given the following text description, write Python code to implement the functionality described below step by step Description: Inspired by R P Herrold's challenge. Some ways of splitting data in Python follow. Step1: Tuple unpacking is nice and in this case enables DRY (aka Single Source of Truth) code. Compare ...
Python Code: MONTH_NDAYS = ''' 0:31 1:29 2:31 3:30 4:31 5:30 6:31 7:31 8:30 9:31 10:30 11:31 '''.split() MONTH_NDAYS for month_n_days in MONTH_NDAYS: month, n_days = map(int, month_n_days.split(':')) print(f'{month} has {n_days}') Explanation: Inspired by R P Her...
875
Given the following text description, write Python code to implement the functionality described below step by step Description: 数据抓取 抓取历届政府工作报告 王成军 wangchengjun@nju.edu.cn 计算传播网 http Step1: Inspect <td width="274" class="bl">·&nbsp;<a href="./d12qgrdzfbg/201603/t20160318_369509.html" target="_blank" title="2016年政府工...
Python Code: import requests from bs4 import BeautifulSoup from IPython.display import display_html, HTML HTML('<iframe src=http://www.hprc.org.cn/wxzl/wxysl/lczf/ width=1000 height=500></iframe>') # the webpage we would like to crawl Explanation: 数据抓取 抓取历届政府工作报告 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-...
876
Given the following text description, write Python code to implement the functionality described below step by step Description: 이 노트북은 Hell, Tensorflow! 의 내용을 참고로 하여 노트북으로 재 정돈한 것입니다. Step1: 텐서플로우의 디폴트 그래프는 직접 접근을 할 수 없고 get_default_graph 메소드를 이용합니다. Step2: 초기에는 디폴트 그래프에 아무런 연산도 들어 있지 않고 비어 있습니다. Step3: 실수 1.0 값을 ...
Python Code: %load_ext watermark %watermark -vm -p tensorflow,numpy,scikit-learn import tensorflow as tf Explanation: 이 노트북은 Hell, Tensorflow! 의 내용을 참고로 하여 노트북으로 재 정돈한 것입니다. End of explanation graph = tf.get_default_graph() Explanation: 텐서플로우의 디폴트 그래프는 직접 접근을 할 수 없고 get_default_graph 메소드를 이용합니다. End of explanation grap...
877
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting Models Exercise 1 Imports Step1: Fitting a quadratic curve For this problem we are going to work with the following model Step2: First, generate a dataset using this model using th...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt Explanation: Fitting Models Exercise 1 Imports End of explanation a_true = 0.5 b_true = 2.0 c_true = -4.0 Explanation: Fitting a quadratic curve For this problem we are going to work with the following model:...
878
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 2 Imports Step1: Factorial Write a function that computes the factorial of small numbers using np.arange and np.cumprod. Step2: Write a function that computes the factorial ...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: Numpy Exercise 2 Imports End of explanation def np_fact(n): # if n == 0: # return 1 # elif n == 1: # return 1 # elif n == 10: # return 3628800 if n==0: r...
879
Given the following text description, write Python code to implement the functionality described below step by step Description: NLP Workshop Author Step1: Load A Text Dataset Collection of TED talk transcripts from the ted.com website Step2: Storage and File types for text Common text file types for text include .j...
Python Code: %pwd # make sure we're running our script from the right place; # imports like "filename" are relative to where we're running ipython Explanation: NLP Workshop Author: Clare Corthell, Luminant Data Conference: Talking Machines, Manila Date: 18 February 2016 Description: Much of human knowledge is “locked...
880
Given the following text description, write Python code to implement the functionality described below step by step Description: 这个分析笔记由Jake Vanderplas编辑汇总。 源代码和license文件在GitHub。 中文翻译由派兰数据在派兰大数据分析平台上完成。 源代码在GitHub上。 深度探索监督学习:支持向量机 之前我们已经介绍了监督学习。监督学习中有很多算法,在这里我们深入探索其中一种最强大的也最有趣的算法之一:支持向量机(Support Vector Machines,SVMs)....
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats # 使用seaborn的一些默认配置 import seaborn as sns; sns.set() Explanation: 这个分析笔记由Jake Vanderplas编辑汇总。 源代码和license文件在GitHub。 中文翻译由派兰数据在派兰大数据分析平台上完成。 源代码在GitHub上。 深度探索监督学习:支持向量机 之前我们已经介绍了监督学习。监督学习中有很多算法,在这里我们深入探索其中一种最强大的也最有趣...
881
Given the following text description, write Python code to implement the functionality described below step by step Description: Downloading public data Something you may want to do in the future is compare your results to papers that came before you. Today we'll go through how to find these data and how to analyze th...
Python Code: # Alphabetical order is standard # We're doing "import superlongname as abbrev" for our laziness - this way we don't have to type out the whole thing each time. # Python plotting library import matplotlib.pyplot as plt # Numerical python library (pronounced "num-pie") import numpy as np # Dataframes in Pyt...
882
Given the following text description, write Python code to implement the functionality described below step by step Description: Evaluation, Cross-Validation, and Model Selection By Heiko Strathmann - heiko.strathmann@gmail.com - http Step1: Types of splitting strategies As said earlier Cross-validation is based upon...
Python Code: %pylab inline %matplotlib inline # include all Shogun classes import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from shogun import * import shogun as sg # generate some ultra easy training data gray() n=20 title('Toy data for binary classification') X=hstack((randn(2,n), randn(2,n)+1)...
883
Given the following text description, write Python code to implement the functionality described below step by step Description: 01 - Example - Eliminating Outliers This notebook presents how to eliminate the diagnosed outliers (in the previous Learning Unit). By Step1: Load the dataset that will be used Step2: Let ...
Python Code: import pandas as pd import numpy as np % matplotlib inline from matplotlib import pyplot as plt Explanation: 01 - Example - Eliminating Outliers This notebook presents how to eliminate the diagnosed outliers (in the previous Learning Unit). By: Hugo Lopes Learning Unit 08 Some inital imports: End of expla...
884
Given the following text description, write Python code to implement the functionality described below step by step Description: Size encodings tutorial See the examples below for common ways to map data to node size in Graphistry. Size refers to point radius. This tutorial covers two kinds of size controls Step1: De...
Python Code: # ! pip install --user graphistry import graphistry # To specify Graphistry account & server, use: # graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com') # For more options, see https://github.com/graphistry/pygraphistry#configure graphistry.__version__ ...
885
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Import packages Importing the necessary packages, including the standard TFX component classes Step2: Pima Indians Diabetes example pipeline Download Example Data We ...
Python Code: !pip install -U tfx # getting the code directly from the repo x = !pwd if 'feature_selection' not in str(x): !git clone -b main https://github.com/deutranium/tfx-addons.git %cd tfx-addons/tfx_addons/feature_selection Explanation: <a href="https://colab.research.google.com/github/deutranium/tfx-addons/...
886
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducing PyTorch written by Gene Kogan, updated by Sebastian Quinard In the next cell, we introduce PyTorch, which is an open-source framework which impelments machine learning methodolog...
Python Code: import numpy as np from sklearn.datasets import load_iris iris = load_iris() data, labels = iris.data[:,0:3], iris.data[:,3] Explanation: Introducing PyTorch written by Gene Kogan, updated by Sebastian Quinard In the next cell, we introduce PyTorch, which is an open-source framework which impelments machin...
887
Given the following text description, write Python code to implement the functionality described below step by step Description: What do I want? Previously in ../catalog_only_classifier/classifier_comparison.ipynb I got a Random Forest-predicted probability of each galaxy being a low-z dwarf. Now I want to select a su...
Python Code: # give access to importing dwarfz import os, sys dwarfz_package_dir = os.getcwd().split("dwarfz")[0] if dwarfz_package_dir not in sys.path: sys.path.insert(0, dwarfz_package_dir) import dwarfz # back to regular import statements %matplotlib inline from matplotlib import pyplot as plt import seabor...
888
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-mh', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NCC Source ID: NORESM2-MH Topic: Landice Sub-Topics: Glaciers, Ice. Prop...
889
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas convert JSON into a DataFrame This is a notebook for the medium article How to convert JSON into a Pandas DataFrame? Please check out article for instructions License Step1: 1. Readi...
Python Code: import pandas as pd Explanation: Pandas convert JSON into a DataFrame This is a notebook for the medium article How to convert JSON into a Pandas DataFrame? Please check out article for instructions License: BSD 2-Clause End of explanation df = pd.read_json('data/simple.json') df df.info() Explanation: 1. ...
890
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mri', 'mri-esm2-0', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MRI Source ID: MRI-ESM2-0 Topic: Aerosol Sub-Topics: Transport, Emissions...
891
Given the following text description, write Python code to implement the functionality described below step by step Description: There is an outlier Step1: Expenses Data Distribution Step2: We can see that there are three employees spend considerably more than others. Step3: Salary Data Distribution Step4: There a...
Python Code: del data_dict['TOTAL'] df = pandas.DataFrame.from_dict(data_dict, orient='index') df.head() print "Dataset size: %d rows x %d columns"%df.shape df.dtypes print "Feature | Missing values" print "---|---" for column in df.columns: if column != 'poi': print "%s | %d"%(column,(df[column] == 'NaN')....
892
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading Annotations from a GO Association File (GAF) Download a GAF file Load the GAF file into the GafReader Get Annotations Bonus Step1: 2) Load the GAF file into the GafReader Step2: 3)...
Python Code: import os if not os.path.exists('goa_human.gaf.gz'): !wget http://current.geneontology.org/annotations/goa_human.gaf.gz !gunzip goa_human.gaf.gz Explanation: Reading Annotations from a GO Association File (GAF) Download a GAF file Load the GAF file into the GafReader Get Annotations Bonus: Each lin...
893
Given the following text description, write Python code to implement the functionality described below step by step Description: Stage 1 Step1: Stage 2 Step2: Stage 3 Step3: Stage 4
Python Code: import pytextrank import sys path_stage0 = "dat/mih.json" path_stage1 = "o1.json" with open(path_stage1, 'w') as f: for graf in pytextrank.parse_doc(pytextrank.json_iter(path_stage0)): f.write("%s\n" % pytextrank.pretty_print(graf._asdict())) # to view output in this notebook pr...
894
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
895
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to NLTK We have seen how to do some basic text processing in Python, now we introduce an open source framework for natural language processing that can further help to work with...
Python Code: sampleText1 = "The Elephant's 4 legs: THE Pub! You can't believe it or can you, the believer?" sampleText2 = "Pierre Vinken, 61 years old, will join the board as a nonexecutive director Nov. 29." Explanation: Introduction to NLTK We have seen how to do some basic text processing in Python, now we introduce...
896
Given the following text description, write Python code to implement the functionality described below step by step Description: Bungee Dunk Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: Suppose you want to set the world record for the highest "bungee dunk", as shown in this video. Sin...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
897
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading, saving and exporting data Pymrio includes several functions for data reading and storing. This section presents the methods to use for saving and loading data already in a pymrio co...
Python Code: import pymrio import os io = pymrio.load_test().calc_all() Explanation: Loading, saving and exporting data Pymrio includes several functions for data reading and storing. This section presents the methods to use for saving and loading data already in a pymrio compatible format. For parsing raw MRIO data se...
898
Given the following text description, write Python code to implement the functionality described below step by step Description: Word Embeddings Learning Objectives You will learn Step1: This notebook uses TF2.x. Please check your tensorflow version using the cell below. Step2: Download the IMDb Dataset You will use...
Python Code: # Use the chown command to change the ownership of repository to user. !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst import io import os import re import shutil import string import tensorflow as tf from datetime import datetime from tensorflow.keras import Model, Sequential from tenso...
899
Given the following text description, write Python code to implement the functionality described below step by step Description: Optically pumped magnetometer (OPM) data In this dataset, electrical median nerve stimulation was delivered to the left wrist of the subject. Somatosensory evoked fields were measured using ...
Python Code: import os.path as op import numpy as np import mne data_path = mne.datasets.opm.data_path() subject = 'OPM_sample' subjects_dir = op.join(data_path, 'subjects') raw_fname = op.join(data_path, 'MEG', 'OPM', 'OPM_SEF_raw.fif') bem_fname = op.join(subjects_dir, subject, 'bem', subject + '-...