Unnamed: 0
int64
0
16k
text_prompt
stringlengths
149
45.7k
code_prompt
stringlengths
67
140k
400
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Histograma da imagem Uma imagem normalmente é composta de um grande número de pixels; hoje em dia, celulares tiram fotografias com a resolução espacial...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.image as mpimg f = mpimg.imread('../data/cameraman.tif') print(f.min(), f.max()) %matplotlib inline import matplotlib.pyplot as plt plt.imshow(f, cmap = 'gray') plt.colorbar() nbins = 20 h, bin_edges = np.histogram(f, nbins,(0,255)) print('h=\n',h)...
401
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: 透過二元分類訓練 IMDB 評論資料 二元分類或稱兩類分類可能是在機器學習中應用最廣泛問題。只要處理的問題只有兩個結果,就可以適用。在這個例子中,我們將根據 IMDB 評論的文本內容將電影評論分為「正面」評論和「負面」評論。 關於 IMDB Dataset 資料集 IMDB Dataset 是來自 I...
<ASSISTANT_TASK:> Python Code: from keras.datasets import imdb (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000) Explanation: 透過二元分類訓練 IMDB 評論資料 二元分類或稱兩類分類可能是在機器學習中應用最廣泛問題。只要處理的問題只有兩個結果,就可以適用。在這個例子中,我們將根據 IMDB 評論的文本內容將電影評論分為「正面」評論和「負面」評論。 關於 IMDB Dataset 資料集 IMDB Dataset 是來自 Interne...
402
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Limb Darkening Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for ...
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.2,<2.3" Explanation: Limb Darkening Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matp...
403
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: LAB 1a Step2: The source dataset Our dataset is hosted in BigQuery. The CDC's Natality data has details on US births from 1969 to 2008 and is a public...
<ASSISTANT_TASK:> Python Code: from google.cloud import bigquery Explanation: LAB 1a: Exploring natality dataset. Learning Objectives Use BigQuery to explore natality dataset Use Vertex AI Notebooks to plot data explorations Introduction In this notebook, we will explore the natality dataset before we begin model deve...
404
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Threading 2018-01-07 <br> Basics A thread is the smallest unit that computer can schedule to run. One process can contain multiple threads. These threa...
<ASSISTANT_TASK:> Python Code: import threading from _thread import start_new_thread, allocate_lock import logging import time import numpy as np Explanation: Threading 2018-01-07 <br> Basics A thread is the smallest unit that computer can schedule to run. One process can contain multiple threads. These threads share t...
405
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Convolutional Cubic Splines $C^2$-continuous cubic splines through evenly spaced data points can be created by convolving the data points with a $C^2$-...
<ASSISTANT_TASK:> Python Code: import math #given an array of Y values at consecutive integral x abscissas, #return array of corresponding derivatives to make a natural cubic spline def naturalSpline(ys): vs = [0.0] * len(ys) if (len(ys) < 2): return vs DECAY = math.sqrt(3)-2; endi = len(ys...
406
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Processes Introduction In simulation and modelling we encounter a wide range of stochastic processes. But most fall into a few common categories Step1:...
<ASSISTANT_TASK:> Python Code: %matplotlib inline Explanation: Processes Introduction In simulation and modelling we encounter a wide range of stochastic processes. But most fall into a few common categories: Ito processes, martingales, Markov processes, Gaussian processes, etc. We attempt to take this into account in ...
407
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Predicting Average Marks Based on Facebook Likes Introduction It is common for students to have a Facebook group on which they post course relevant dis...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = 12, 10 plt.rcParams.update({'font.size': 15}) data = pd.read_csv('../data/train.csv') data.describe() Explanation: Predicting Average Marks Based on Facebook Likes In...
408
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Given a 2D set of points spanned by axes $x$ and $y$ axes, we will try to fit a line that best approximates the data. The equation of the line, in slop...
<ASSISTANT_TASK:> Python Code: def generate_random_points_along_a_line (slope, intercept, num_points, abs_value, abs_noise): # randomly select x x = np.random.uniform(-abs_value, abs_value, num_points) # y = mx + b + noise y = slope*x + intercept + np.random.uniform(-abs_noise, abs_noise, num_points) ...
409
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Copyright 2019 Google LLC. Licensed under the Apache License, Version 2.0 (the "License") Step1: On Variational Bounds of Mutual Information Ben Poole...
<ASSISTANT_TASK:> 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, sof...
410
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Variables Step1: That seems to indicate this identity Step2: Hmm... now that is a very interesting structure. I'm even more convinced that there's ...
<ASSISTANT_TASK:> Python Code: from scipy.special import legendre q = 20 n_steps = 100000 t = np.linspace(0, 1, n_steps) P = np.asarray([legendre(i)(2*t - 1) for i in range(q)]).T total = np.zeros((q,q)) for Pt in P: Ct = np.outer(Pt, Pt) total += Ct / n_steps plt.figure(figsize=(12,6)) plt.subplot(1, 2, 1...
411
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Copyright 2019 The TensorFlow Authors. Step1: Load NumPy data <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="ht...
<ASSISTANT_TASK:> 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 writin...
412
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Clase 10 Step1: 2. Uso de Pandas para descargar datos de precios de cierre Bajar datos en forma de función Step2: Una vez cargados los paquetes, es n...
<ASSISTANT_TASK:> Python Code: #importar los paquetes que se van a usar import pandas as pd import pandas_datareader.data as web import numpy as np import datetime from datetime import datetime import scipy.stats as stats import scipy as sp import scipy.optimize as scopt import matplotlib.pyplot as plt import seaborn a...
413
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: ANLP 2015 Text Classification Assignment Emily Scharff and Juan Shishido Write Up Introduction This notebook contains the code and documentation that w...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import re import numpy as np import pandas as pd import matplotlib.pyplot as plt import nltk from nltk.corpus import stopwords from nltk.tokenize import regexp_tokenize from nltk.stem.porter import PorterStemmer from sklearn import cross_validation from sklearn.feature_...
414
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Create a Dask cluster using Coiled First, we'll create a Dask cluster with Coiled Step1: Let's point the distributed client to the Dask cluster on Coi...
<ASSISTANT_TASK:> Python Code: import coiled cluster = coiled.Cluster(n_workers=10) Explanation: Create a Dask cluster using Coiled First, we'll create a Dask cluster with Coiled: End of explanation from dask.distributed import Client client = Client(cluster) print('Dashboard:', client.dashboard_link) Explanation: Let'...
415
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: See http Step1: not tested... writer = pd.ExcelWriter('nd_out.xlsx') nd.to_excel(writer,'Sheet1') writer.save()
<ASSISTANT_TASK:> Python Code: from pandas.tools.plotting import scatter_matrix p = scatter_matrix(nd.loc[:, use_col[:3]], alpha=0.2, figsize=(18, 12), diagonal='kde') %%script bash --bg --out script_out bokeh-server nd.dtypes[:5] use_col = [True if dtype in ['int64', 'float64'] else False for dtype in nd.dtypes] from ...
416
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Vector space tutorial The goal of this tutorial is to show how word co-occurrence statistics can be used to build their vectors, such that words that a...
<ASSISTANT_TASK:> Python Code: # This is a code cell. It can be executed by pressing CTRL+Enter print('Hello') Explanation: Vector space tutorial The goal of this tutorial is to show how word co-occurrence statistics can be used to build their vectors, such that words that are similar in meaning are also close in a vec...
417
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Compare the read depth and number of strains This data is the average read depth of each metagenome. The table in read_depth.strains.tsv has the SRA ID...
<ASSISTANT_TASK:> Python Code: #instantiate our environment import os import sys %matplotlib inline import pandas as pd import statsmodels.api as sm # read the data into a pandas dataframe df = pd.read_csv("read_depth.strains.tsv", header=0, delimiter="\t") print("Shape: {}".format(df.shape)) df.head() Explanation: Com...
418
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Chicago taxi fare training experience This experiment using Scikit-learn Random Forest to train a ML model on Chicago taxi dataset to estimate t...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from pandas_profiling import ProfileReport from scipy import stats from sklearn.ensemble import RandomForestRegressor from sklearn.compose import ColumnTransformer from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV fr...
419
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contribu...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'sandbox-2', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: NOAA-GFDL Source ID: SANDBOX-2 Topic: Atmosche...
420
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Resolving Specifiers Specifier grammars allow you to specify complex inputs for Batfish questions. This category of questions reveals how specifier inp...
<ASSISTANT_TASK:> Python Code: bf.set_network('generate_questions') bf.set_snapshot('generate_questions') Explanation: Resolving Specifiers Specifier grammars allow you to specify complex inputs for Batfish questions. This category of questions reveals how specifier inputs are resolved by Batfish. Resolve Location Spec...
421
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: 内容概要 如何使用K折交叉验证来搜索最优调节参数 如何让搜索参数的流程更加高效 如何一次性的搜索多个调节参数 在进行真正的预测之前,如何对调节参数进行处理 如何削减该过程的计算代价 1. K折交叉验证回顾 交叉验证的过程 - 选择K的值(一般是10),将数据集分成K等份 - 使用其中的K-1份数据作为...
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt %matplotlib inline from sklearn.grid_search import GridSearchCV # read in the iris data iris = load_iris() # create X (features) and y (response) X = iris.data y = iri...
422
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Source of the materials Step1: The SeqRecord Object The SeqRecord (Sequence Record) class is defined in the Bio.SeqRecord module. This class allows hi...
<ASSISTANT_TASK:> Python Code: from Bio.SeqRecord import SeqRecord Explanation: Source of the materials: Biopython Tutorial and Cookbook (adapted) Sequence annotation objects The previous notebook introduced the sequence classes. Immediately ``above'' the Seq class is the Sequence Record or SeqRecord class, defined in...
423
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described. <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: def closest_integer(value): ''' Create a function that takes a value (string) representing a number and returns the closest integer to it. If the number is equidistant from two integers, round it away from zero. Examples >>> closest_integer("10") 10 >>> clo...
424
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: <center><h1>Probabilistic Programming in Quantitative Finance</h1><br> <h3>Thomas Wiecki</h3> <br> <h3>@twiecki</h3> <br> <img width=40% src="ht...
<ASSISTANT_TASK:> Python Code: %pyplot inline figsize(12, 12) import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np import itertools import scipy as sp import pymc3 as pm import theano.tensor as T from scipy import stats import scipy data_0 = pd.read_csv('data0.csv', index_col=0, ...
425
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Python graphics Step1: Comment. When you run the code cell above, its output appears below it. Exercise. Enter pd.read_csv? in the empty cell below...
<ASSISTANT_TASK:> Python Code: # make plots show up in notebook %matplotlib inline import pandas as pd # data package import matplotlib.pyplot as plt # pyplot module Explanation: Python graphics: Matplotlib fundamentals We illustrate three approaches to graphing data with...
426
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Sensors Hi ha quatre sensors diferents montats i connectats al robot Step1: Sensor de tacte És un polsador, que segons estiga polsat o no, donarà un v...
<ASSISTANT_TASK:> Python Code: from functions import connect, touch, light, sound, ultrasonic, disconnect, next_notebook connect() Explanation: Sensors Hi ha quatre sensors diferents montats i connectats al robot: <img src="img/sensors.jpg" width=400> Els de la figura corresponen al model NXT, però els de l'EV3 són equ...
427
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Adding Custom Operator Steps in Integration Schemes In addition to forces that modify particle accelerations every timestep, we can use REBOUNDx to add...
<ASSISTANT_TASK:> Python Code: import rebound import reboundx import numpy as np import matplotlib.pyplot as plt %matplotlib inline def makesim(): sim = rebound.Simulation() sim.G = 4*np.pi**2 sim.add(m=1.) sim.add(m=1.e-4, a=1.) sim.add(m=1.e-4, a=1.5) sim.move_to_com() return sim Explanati...
428
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: k-Nearest Neighbor (kNN) exercise Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet...
<ASSISTANT_TASK:> 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 n...
429
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Self-Driving Car Engineer Nanodegree Project Step1: Read in an Image Step9: Ideas for Lane Detection Pipeline Some OpenCV functions (beyond those int...
<ASSISTANT_TASK:> Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline Explanation: Self-Driving Car Engineer Nanodegree Project: Finding Lane Lines on the Road In this project, you will use the tools you learned a...
430
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Basic Metrics When we think about summarizing data, what are the metrics that we look at? In this notebook, we will look at the car dataset To read how...
<ASSISTANT_TASK:> Python Code: #Import the required libraries import numpy as np import pandas as pd from datetime import datetime as dt from scipy import stats Explanation: Basic Metrics When we think about summarizing data, what are the metrics that we look at? In this notebook, we will look at the car dataset To rea...
431
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: In this notebook the datsets for the predictor will be generated. Step1: Let's first define the list of parameters to use in each dataset. Step2: Now...
<ASSISTANT_TASK:> Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error %matplotlib inline %pylab inline pylab.rcParams[...
432
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Chapter 7 - Sets This chapter will introduce a different kind of container Step1: Curly brackets surround sets, and commas separate the elements in th...
<ASSISTANT_TASK:> Python Code: a_set = {1, 2, 3} a_set empty_set = set() # you have to use set() to create an empty set! (we will see why later) print(empty_set) Explanation: Chapter 7 - Sets This chapter will introduce a different kind of container: sets. Sets are unordered lists with no duplicate entries. You might w...
433
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Image features exercise Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with you...
<ASSISTANT_TASK:> Python Code: import random import numpy as np from skynet.utils.data_utils import load_CIFAR10 import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray'...
434
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Files File is a named location on disk to store related information. Python uses the file objects to interact with external files on the computer. Thes...
<ASSISTANT_TASK:> Python Code: %%writefile test.txt This is a test file Explanation: Files File is a named location on disk to store related information. Python uses the file objects to interact with external files on the computer. These files could be of any format like text, binary, excel, audio, video files. Please ...
435
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Análise de um oscilador com N graus de liberdade sujeito a uma excitação dinâmica aplicada nalguns graus de liberdade Formulação do problema Equação de...
<ASSISTANT_TASK:> Python Code: import sys import math import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline print('System: {}'.format(sys.version)) for package in (np, mpl): print('Package: {} {}'.format(package.__name__, package.__version__)) Explanation: Análise de um osci...
436
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Creating Ukulele Chord Diagrams in SVG with Python With the Python modul uchord you can create ukulele chord diagrams in SVG format. Step1: <img src="...
<ASSISTANT_TASK:> Python Code: import uchord uchord.write_chord('c.svg','C','0003') Explanation: Creating Ukulele Chord Diagrams in SVG with Python With the Python modul uchord you can create ukulele chord diagrams in SVG format. End of explanation pip install uchord Explanation: <img src="pic/c.svg" align="left"><br><...
437
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Components Step1: IPython Console IPython started as a terminal based interactive console with tab completion, integrated help, plotting support, etc....
<ASSISTANT_TASK:> Python Code: from IPython.display import display, Image, HTML from talktools import website, nbviewer Explanation: Components End of explanation Image('images/ipython_console.png') Explanation: IPython Console IPython started as a terminal based interactive console with tab completion, integrated help...
438
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Community Node Layout / Bundled Edges Step1: Alternatively, the best partition into communities can be inferred, for example using the Louvain algorit...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import networkx as nx from netgraph import Graph # create a modular graph partition_sizes = [10, 20, 30, 40] g = nx.random_partition_graph(partition_sizes, 0.5, 0.1) # create a dictionary that maps nodes to the community they belong to node_to_community = d...
439
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Antenna Position Measurement Author Step1: Locating the third reference point The distances from reference point 2 to the other two reference points (...
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy.optimize import minimize x0 = [0,0] x1 = [0, 2209] Explanation: Antenna Position Measurement Author: Tim Molteno. tim@elec.ac.nz. The antennas are laid out on tiles, and these tiles are placed on site. Once this is done, a survey is needed to refine the posi...
440
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Copyright 2019 Google LLC Step1: scikit-learn Training on AI Platform This notebook uses the Census Income Data Set to demonstrate how to train a mode...
<ASSISTANT_TASK:> 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, sof...
441
<SYSTEM_TASK:> Given the following text problem statement, write Python code to implement the functionality described below in problem statement <END_TASK> <USER_TASK:> Problem: I have a pandas DataFrame data
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from sklearn import preprocessing data = load_data() df_out = pd.DataFrame(preprocessing.scale(data), index=data.index, columns=data.columns) <END_TASK>
442
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Plot train and valid set NLL Step1: Plot ratio of update norms to parameter norms across epochs for different layers
<ASSISTANT_TASK:> 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.plot(model_no_mom.moni...
443
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Plot 1 Step1: Description Step2: Load data and take a peak at it. Step3: Separate data into training, validation, and test sets. (This division is n...
<ASSISTANT_TASK:> Python Code: from IPython.display import display, HTML display(HTML('''<img src="image1.png",width=800,height=500">''')) Explanation: Plot 1: The predictive potential of rank difference End of explanation import numpy as np # numerical libraries import pandas as pd # for data analysis import matplotli...
444
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Загрузка данных Step1: Выходная переменная Step2: Посмотрим самые частые и самые редкие категории. Step3: 7 = сигареты 6 = продукты питания 32 = поз...
<ASSISTANT_TASK:> Python Code: train_data = pd.read_csv('./data/evo_train.csv', sep=',', header=0) test_data = pd.read_csv('./data/evo_test.csv', sep=',', header=0) print train_data.shape print test_data.shape train_data.head() Explanation: Загрузка данных End of explanation train_data.GROUP_ID.value_counts() Explanati...
445
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: DataLoaders The DataLoader class Step1: DataLoader helpers fastai includes a replacement for Pytorch's DataLoader which is largely API-compatible, and...
<ASSISTANT_TASK:> Python Code: #|export from __future__ import annotations from fastai.torch_basics import * from torch.utils.data.dataloader import _MultiProcessingDataLoaderIter,_SingleProcessDataLoaderIter,_DatasetKind _loaders = (_MultiProcessingDataLoaderIter,_SingleProcessDataLoaderIter) #|hide from nbdev.showdoc...
446
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Introduzione a Pandas Pandas è una libreria, costruita sulla base della libreria numpy, che ha lo scopo di manipolare data frames. Oggetto di tipo Data...
<ASSISTANT_TASK:> Python Code: import pandas as pd Explanation: Introduzione a Pandas Pandas è una libreria, costruita sulla base della libreria numpy, che ha lo scopo di manipolare data frames. Oggetto di tipo DataFrame = tabella organizzata in righe (records) e colonne intestate. Pandas offre tre funzionalità princip...
447
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Test suite for Jupyter-notebook Sample example of use of PyCOMPSs from Jupyter First step Import ipycompss library Step1: Second step Initialize COMPS...
<ASSISTANT_TASK:> 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='../r...
448
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Lecture 3 Step1: We'll train a logistic regression model of the form $$ p(y = 1 ~|~ {\bf x}; {\bf w}) = \frac{1}{1 + \textrm{exp}[-(w_0 + w_1x_1 + w_...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt %matplotlib inline from sklearn import datasets iris = datasets.load_iris() X_train = iris.data[iris.target != 2, :2] # first two features and y_train = iris.target[iris.target != 2] # first two labels only fig = plt.figure(figsize=(8,8)) mycolors = {"b...
449
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Index Weak-field approximation for Stokes V Strong-field approximation for Stokes V Longitudinal magnetograph Center-of-gravity Unresolved fields - inc...
<ASSISTANT_TASK:> Python Code: lambda0 = 6301.5 JUp = 1.0 JLow = 1.0 gUp = 2.5 gLow = 0.0 lambdaStart = 6300.8 lambdaStep = 0.01 nLambda = 150 wavelength = lambdaStart + np.arange(nLambda) * lambdaStep lineInfo = np.asarray([lambda0, JUp, JLow, gUp, gLow, lambdaStart, lambdaStep]) s = pymilne.milne(nLambda, lineInfo) B...
450
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: How to set priors on stellar parameters. gully https Step1: We want a a continuous prior Step2: The normalization doesn't matter, but it's nice to kn...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns % config InlineBackend.figure_format = 'retina' Explanation: How to set priors on stellar parameters. gully https://github.com/iancze/Starfish/issues/32 The strategy here is to define a lnprior and...
451
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: network(), radar() and site() objects This notebook introduces the high-level python interface with the radar.dat and hdw.dat content. For more in-de...
<ASSISTANT_TASK:> Python Code: # Import radar module %pylab inline from davitpy.pydarn.radar import * Explanation: network(), radar() and site() objects This notebook introduces the high-level python interface with the radar.dat and hdw.dat content. For more in-depth access (i.e., your own hdw.dat), look at the radIn...
452
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Statistics The executed version of this tutorial is at https Step1: The function requires four parameters Step2: The nice thing about Quantities is t...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from quantities import ms, s, Hz from elephant.spike_train_generation import homogeneous_poisson_process, homogeneous_gamma_process help(homogeneous_poisson_process) Explanation: Statistics The executed version of this ...
453
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: <a id="Top"></a> ___ ___ ___ _____ /\__\ ...
<ASSISTANT_TASK:> Python Code: # Standard library import datetime import time # Third party libraries import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Digitre code import digitre_preprocessing as prep import digitre_model import digitre_classifier # Reload digitre code in the same session (during...
454
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: 12-752 Step1: Short Introduction to Python and Jupyter Jupyter notebooks consist of cells. This cell is a Markdown cell. Try double-clicking this cell...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import sys print('Python version:') print(sys.version) print('Numpy version:') print(np.__version__) import sklearn print('Sklearn version:') print(sklearn.__version__) Explanation: 12-752: Data-Driven Building Energy ...
455
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: (NVM)= 1.3 Normas vectoriales y matriciales ```{admonition} Notas para contenedor de docker Step1: Norma $2$ Step2: Norma $1$ Step3: Norma $\infty$ ...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt Explanation: (NVM)= 1.3 Normas vectoriales y matriciales ```{admonition} Notas para contenedor de docker: Comando de docker para ejecución de la nota de forma local: nota: cambiar &lt;ruta a mi directorio&gt; por la ruta de directorio que...
456
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: syncID Step1: Define functions Next, we'll define a few functions that we will use throughout the code. Step2: This next piece of code just helps ide...
<ASSISTANT_TASK:> Python Code: import sys sys.version import gdal import h5py import numpy as np from math import floor import os import matplotlib.pyplot as plt Explanation: syncID: a6db1047adb34f41b9d17d6ed41f5fd5 title: "Exploring Uncertainty in LiDAR Data using Python" description: "Learn to analyze the difference ...
457
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Smooth Tree Single decision trees generally overfit, leading to poor predictive performance. Tree ensembles (RF, GBM) perform well, but are black-box m...
<ASSISTANT_TASK:> Python Code: from arboretum.datasets import load_diabetes xtr, ytr, xte, yte = load_diabetes() xtr.shape, xte.shape Explanation: Smooth Tree Single decision trees generally overfit, leading to poor predictive performance. Tree ensembles (RF, GBM) perform well, but are black-box models. In this noteboo...
458
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: <h1> Preprocessing using Cloud Dataflow </h1> <h2>Learning Objectives</h2> <ol> <li>Create ML dataset using <a href="https Step1: After installing...
<ASSISTANT_TASK:> Python Code: # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.1 %pip install apache-beam[gcp]==2.13.0 Explanation: <h1> Preprocessing using Cloud Dataflow </h1> <h2>Learning Objectives</h2> <ol> <li>Create ML dataset using <a href="https://cloud.google.com/da...
459
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: TPOT tutorial on the Titanic dataset The Titanic machine learning competition on Kaggle is one of the most popular beginner's competitions on the platf...
<ASSISTANT_TASK:> Python Code: # Import required libraries from tpot import TPOTClassifier from sklearn.model_selection import train_test_split import pandas as pd import numpy as np # Load the data titanic = pd.read_csv('data/titanic_train.csv') titanic.head(5) Explanation: TPOT tutorial on the Titanic dataset The Ti...
460
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Session 2 Step1: import The Python import statement makes other packages available to your current session. There are a few forms of import, two of wh...
<ASSISTANT_TASK:> Python Code: import veneer import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline Explanation: Session 2: Quick tour of Veneer Main features of Veneer (and veneer-py) Starting a new notebook Querying models Running models and Retrieving results Manipulating model set...
461
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: TF-IDF based Recommender System Recommender System based on tf-idf as vector representation of documents TF-IDF Based Recommender Represent articles in...
<ASSISTANT_TASK:> Python Code: PATH_NEWS_ARTICLES="/home/phoenix/Documents/HandsOn/Final/news_articles.csv" ARTICLES_READ=[2,7] NUM_RECOMMENDED_ARTICLES=5 try: import numpy import pandas as pd import pickle as pk from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwi...
462
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Python Basics (2016-09-09) Content Comments Data Types Simple Arithmetics Strings Comments Comments provide important documentation for your cod...
<ASSISTANT_TASK:> Python Code: # this is a single line comment this is a multi line comment Explanation: Python Basics (2016-09-09) Content Comments Data Types Simple Arithmetics Strings Comments Comments provide important documentation for your code. End of explanation a = 5.1 print 'a', type(a) b = 3 print 'b', type...
463
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: DMDU 2019 Training Day - Introduction to SALib Will Usher Assistant Professor, Division of Energy Systems Analysis, KTH Royal Institute of Technology H...
<ASSISTANT_TASK:> Python Code: from ipywidgets import widgets, interact from IPython.display import display import seaborn as sbn import matplotlib.pyplot as plt %matplotlib inline import numpy as np from IPython.core.pylabtools import figsize sbn.set_context("talk", font_scale=.8) figsize(10, 8) # The model used for t...
464
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: DoWhy example on Twins dataset Here we study the twins dataset as studied by <a href="https Step1: <font size="4">Load the Data</font> The data loadin...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import dowhy from dowhy import CausalModel from dowhy import causal_estimators # Config dict to set the logging level import logging.config DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { '': { ...
465
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Continuing Graphs of Specimens Over Time - Continents and GBIF This notebook continues the work done in 01_iDigBio_Specimens_Collected_Over_Time.ipynb,...
<ASSISTANT_TASK:> Python Code: # col() selects columns from a data frame, year() works on dates, and udf() creates user # defined functions from pyspark.sql.functions import col, year, udf # Plotting library and configuration to show graphs in the notebook import matplotlib.pyplot as plt %matplotlib inline Explanation:...
466
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: <a href='http Step1: <font color=green>In the above sentence, running, run and ran all point to the same lemma run (...11841) to avoid duplication.</f...
<ASSISTANT_TASK:> Python Code: # Perform standard imports: import spacy nlp = spacy.load('en_core_web_sm') doc1 = nlp(u"I am a runner running in a race because I love to run since I ran today") for token in doc1: print(token.text, '\t', token.pos_, '\t', token.lemma, '\t', token.lemma_) Explanation: <a href='http:/...
467
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Copyright 2020 DeepMind Technologies Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compli...
<ASSISTANT_TASK:> Python Code: !pip install tensorflow==1.15 dm-sonnet==1.36 tensor2tensor==1.14 import time import numpy as np import tensorflow.compat.v1 as tf tf.logging.set_verbosity(tf.logging.ERROR) # Hide TF deprecation messages import matplotlib.pyplot as plt %cd /tmp %rm -rf /tmp/deepmind_research !git clone ...
468
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Test of POPIII star input Test of SSP with POPIII yields. Focus are basic GCE features. You can find the documentation <a href="doc/sygma.html">here</a...
<ASSISTANT_TASK:> Python Code: %pylab nbagg import sygma as s reload(s) s.__file__ #from imp import * #s=load_source('sygma','/home/nugrid/nugrid/SYGMA/SYGMA_online/SYGMA_dev/sygma.py') from scipy.integrate import quad from scipy.interpolate import UnivariateSpline import matplotlib.pyplot as plt import numpy as np Exp...
469
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Natural language image search with a Dual Encoder Author Step1: Prepare the data We will use the MS-COCO dataset to train our dual encoder model. MS-C...
<ASSISTANT_TASK:> Python Code: import os import collections import json import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import tensorflow_hub as hub import tensorflow_text as text import tensorflow_addons as tfa import matplotlib.pyplot as plt import matplotli...
470
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: 1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. Step1: 2. Get Cloud P...
<ASSISTANT_TASK:> Python Code: !pip install git+https://github.com/google/starthinker Explanation: 1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. End of explanation CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" ...
471
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Copyright 2021 The TensorFlow Authors. Step1: TensorFlow Lite Model Analyzer <table class="tfo-notebook-buttons" align="left"> <td> <a target="_...
<ASSISTANT_TASK:> 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 writin...
472
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Executed Step1: Notebook arguments measurement_id (int) Step2: Selecting a data file Step3: Data load and Burst search Load and process the data Ste...
<ASSISTANT_TASK:> Python Code: measurement_id = 0 windows = (60, 180) # Cell inserted during automated execution. windows = (30, 180) measurement_id = 1 Explanation: Executed: Tue Mar 28 00:43:40 2017 Duration: 41 seconds. End of explanation import time from pathlib import Path import pandas as pd from scipy.stats impo...
473
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 2) Step1: Eulerian Cycles Before we look at different network types, let us r...
<ASSISTANT_TASK:> Python Code: from networkit import * %matplotlib inline cd ~/workspace/NetworKit G = readGraph("input/PGPgiantcompo.graph", Format.METIS) Explanation: Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 2) End of explanation # 2-2) and 2-3) Decide whether graph is Eulerian or not ...
474
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Configuring MNE python This tutorial gives a short introduction to MNE configurations. Step1: MNE-python stores configurations to a folder called .mne...
<ASSISTANT_TASK:> Python Code: import os.path as op import mne from mne.datasets.sample import data_path fname = op.join(data_path(), 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(fname).crop(0, 10) original_level = mne.get_config('MNE_LOGGING_LEVEL', 'INFO') Explanation: Configuring MNE python Th...
475
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Chapter 3 Examples and Exercises from Think Stats, 2nd Edition http Step1: Again, I'll load the NSFG pregnancy file and select live births Step2: Her...
<ASSISTANT_TASK:> Python Code: from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import urlretrieve local, _ = urlretrieve(url, filename) print("Downloaded " + local) download("https://github.com/AllenDowney/Thin...
476
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Ferrofluid - Part 2 Table of Contents Applying an external magnetic field Magnetization curve Remark Step1: and set up the simulation parameters where...
<ASSISTANT_TASK:> Python Code: import espressomd import espressomd.magnetostatics import espressomd.magnetostatic_extensions espressomd.assert_features('DIPOLES', 'LENNARD_JONES') import numpy as np Explanation: Ferrofluid - Part 2 Table of Contents Applying an external magnetic field Magnetization curve Remark: The eq...
477
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: CSAL4243 Step1: Feature Scaling and Mean Normalization Step2: Initialize Hyper Parameters Step3: Model/Hypothesis Function Step5: Cost Function Ste...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np from sklearn import linear_model import matplotlib.pyplot as plt import matplotlib as mpl # read data in pandas frame dataframe = pd.read_csv('datasets/house_dataset2.csv', encoding='utf-8') # check data by printing first few rows ...
478
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Short introduction to working with DEMs in Python GDAL Greg Tucker, CU Boulder, Feb 2016 Install GDAL library You'll need to install the GDAL library. ...
<ASSISTANT_TASK:> Python Code: from osgeo import gdal import numpy as np Explanation: Short introduction to working with DEMs in Python GDAL Greg Tucker, CU Boulder, Feb 2016 Install GDAL library You'll need to install the GDAL library. If you have Anaconda installed, you can do this from the command line by: conda ins...
479
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Configuring the model, running g-tools and output files and infos This tutorial shows how to configure the model and how to run Fermipy-LAT g-tools wit...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import numpy as np from fermipy.gtanalysis import GTAnalysis from fermipy.plotting import ROIPlotter, SEDPlotter import matplotlib.pyplot as plt import matplotlib from IPython.display import Image Explanation: Configuring the model, running g-tools and output ...
480
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 1) Welcome to the hands-on session of our tutorial! This tutorial is based on ...
<ASSISTANT_TASK:> Python Code: from networkit import * %matplotlib inline Explanation: Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 1) Welcome to the hands-on session of our tutorial! This tutorial is based on the user guide of NetworKit, our network analysis software. You will learn in this...
481
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: GLM Step1: The Adult Data Set is commonly used to benchmark machine learning algorithms. The goal is to use demographic features, or variables, to pre...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import pymc3 as pm import matplotlib.pyplot as plt import seaborn import warnings warnings.filterwarnings('ignore') from collections import OrderedDict from time import time import numpy as np import pandas as pd import matplotlib....
482
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: BOW model and Naive Bayes Step1: Table of Contents BOW model and Naive Bayes Rotten Tomatoes data set Explore The Vector space model and a search engi...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt import pandas as pd pd.set_option('display.width', 500) pd.set_option('display.max_columns', 100) pd.set_option('display.notebook_repr_html', True) ...
483
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Logarithmic Parameters This notebook explores Bayesian optimisation of a function who's parameter is best thought of logarithmically (the order of magn...
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 from IPython.core.debugger import Tracer # debugging from IPython.display import clear_output, display import time %matplotlib inline #%config InlineBackend.figure_format = 'svg' import matplotlib.pyplot as plt import seaborn as sns; sns.set() # prettify...
484
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Python for Webscraping SOC 590 Step1: open US News Rankings for Sociology webpage view page source to see html Step3: create a function to extract pa...
<ASSISTANT_TASK:> Python Code: import os import urllib import webbrowser import pandas as pd from bs4 import BeautifulSoup Explanation: Python for Webscraping SOC 590: Big Data and Population Processes 17th October 2016 Tutorial 2: Webscraping with a function Outline Import modules Examine html structure of a webpage U...
485
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: How to locally run parallel code with mpi4py in an IPython notebook Step1: Now, to make the code run on all of our engines (and not just on one), the ...
<ASSISTANT_TASK:> Python Code: from ipyparallel import Client import os c = Client() view = c[:] print(c.ids) %%px def find(name, path): for root, dirs, files in os.walk(path): if name in files: return root path = find('02_LocalParallelization.ipynb', '/home/') print(path) os.chdir(path) Explana...
486
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Pyflex Pyflex is a Python port of the FLEXWIN algorithm for automatically selecting windows for seismic tomography. For the most part it mimicks the ca...
<ASSISTANT_TASK:> Python Code: %pylab inline import obspy import pyflex Explanation: Pyflex Pyflex is a Python port of the FLEXWIN algorithm for automatically selecting windows for seismic tomography. For the most part it mimicks the calculations of the original FLEXWIN package; minor differences and their reasoning ar...
487
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Regression Week 2 Step1: Load in house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Ste...
<ASSISTANT_TASK:> Python Code: import graphlab Explanation: Regression Week 2: Multiple Regression (gradient descent) In the first notebook we explored multiple regression using graphlab create. Now we will use graphlab along with numpy to solve for the regression weights with gradient descent. In this notebook we will...
488
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Protein - Structure Mapping, Alignments, and Visualization This notebook gives an example of how to map a single protein sequence to its structure, alo...
<ASSISTANT_TASK:> Python Code: import sys import logging # Import the Protein class from ssbio.core.protein import Protein # Printing multiple outputs per cell from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" Explanation: Protein - Structure Mapping, Alignments,...
489
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Using OPSPiggybacker to stub in test data for analysis One of the main uses of OPSPiggybacker is to make data from one source readable for OPS analysis...
<ASSISTANT_TASK:> Python Code: from openpathsampling.tests.test_helpers import make_1d_traj left_state_edge = 0.0 right_state_edge = 10.0 def make_traj(suffix, stride=1): frame = left_state_edge -1.0 + suffix coords = [frame] while frame < right_state_edge: frame += 1.0*stride coords.append(...
490
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Much of the world isn't mapped. This seems odd at first, but it basically comes down to a question of cash, and a large chunk of the world doesn't have...
<ASSISTANT_TASK:> Python Code: from mapswipe_analysis import * all_projects_solution = Solution( ground_truth_solutions_file_to_map('../experiment_1/all_projects_dataset/test/solutions.csv'), predictions_file_to_map('../experiment_1/inception_v3_all_layers.results') ) all_projects_solution.accuracy Explanation:...
491
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Introduction Run this cell to set everything up! Step1: Examine the following seasonal plot Step2: And also the periodogram Step3: 1) Determine seas...
<ASSISTANT_TASK:> Python Code: # Setup feedback system from learntools.core import binder binder.bind(globals()) from learntools.time_series.ex3 import * # Setup notebook from pathlib import Path from learntools.time_series.style import * # plot style settings from learntools.time_series.utils import plot_periodogram,...
492
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: <h1> Create Keras Wide-and-Deep model </h1> <h2>Learning Objectives</h2> <ol> <li>Use the tf.data API to create our ML datasets</li> <li>Use the Keras ...
<ASSISTANT_TASK:> Python Code: # change these to try this notebook out 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 ...
493
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: How to build a simple text classifie...
<ASSISTANT_TASK:> Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
494
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: DSFP Object Oriented Programming Notebook Incorporating classes, objects, and functions into your code will improve its efficiency, readability, and ma...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import random import numpy as np %matplotlib inline Explanation: DSFP Object Oriented Programming Notebook Incorporating classes, objects, and functions into your code will improve its efficiency, readability, and make it easier to extend to other programs ...
495
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: How to import the data 1. Define search filters. This is needed if some data has to be filtered out. 2. Import data from ase databases. 3. Store refere...
<ASSISTANT_TASK:> Python Code: # Import and instantiate energy_landscape object. from catmap.api.ase_data import EnergyLandscape energy_landscape = EnergyLandscape() # Import all gas phase species from db. search_filter_gas = [] energy_landscape.get_molecules('molecules.db', selection=search_filter_gas) # Import all ad...
496
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Pandas pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt Explanation: Pandas pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims t...
497
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Agile and Test-Driven Development TDD Worked Example Robert Haines, University of Manchester, UK Adapted from "Test-Driven Development By Example", Ken...
<ASSISTANT_TASK:> Python Code: import unittest def run_tests(): suite = unittest.TestLoader().loadTestsFromTestCase(TestFibonacci) unittest.TextTestRunner().run(suite) Explanation: Agile and Test-Driven Development TDD Worked Example Robert Haines, University of Manchester, UK Adapted from "Test-Driven Developm...
498
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Character Sequence to Sequence In this notebook, we'll build a model that takes in a sequence of letters, and outputs a sorted version of that sequence...
<ASSISTANT_TASK:> Python Code: import numpy as np import time import helper source_path = 'data/letters_source.txt' target_path = 'data/letters_target.txt' source_sentences = helper.load_data(source_path) target_sentences = helper.load_data(target_path) Explanation: Character Sequence to Sequence In this notebook, we'l...
499
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Compute a sparse inverse solution using the Gamma-Map empirical Bayesian method See [1]_ for details. References .. [1] D. Wipf, S. Nagarajan "A uni...
<ASSISTANT_TASK:> Python Code: # Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de> # # License: BSD (3-clause) import numpy as np import mne from mne.datasets import sample from mne.inverse_sparse import gamma_map, make_stc_from_dipoles from mne.viz import...