Unnamed: 0
int64
0
16k
text_prompt
stringlengths
149
45.7k
code_prompt
stringlengths
67
140k
600
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Deep LSTM RNNs Step1: Dataset Step2: Check the data real quick Step3: Preparing the data for training Step4: Long short-term memory (LSTM) RNNs An ...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import mxnet as mx from mxnet import nd, autograd import numpy as np from collections import defaultdict mx.random.seed(1) # ctx = mx.gpu(0) ctx = mx.cpu(0) %matplotlib inline import matplotlib import matplotlib.pyplot as plt import seaborn as sns imp...
601
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Soil Moisture Active Passive (SMAP) Level 4 Data demo In this demo we are downloading data using Planet OS Package-API which let's us use bigger amount...
<ASSISTANT_TASK:> Python Code: import time import os from package_api import download_data import xarray as xr from netCDF4 import Dataset, num2date from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np import matplotlib import datetime import warnings warnings.filterwarnings("igno...
602
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: This is the <a href="https Step1: Magnetic Dipole Applet Purpose The objective is to learn about the magnetic field observed at the ground's surface, ...
<ASSISTANT_TASK:> Python Code: from geoscilabs.mag.MagDipoleApp import MagneticDipoleApp Explanation: This is the <a href="https://jupyter.org/">Jupyter Notebook</a>, an interactive coding and computation environment. For this lab, you do not have to write any code, you will only be running it. To use the notebook: - ...
603
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Integración numérica Montecarlo Referencia Step1: Integración Montecarlo tipo 1 Se basa en la definición de valor promedio de una función y en el valo...
<ASSISTANT_TASK:> Python Code: from IPython.display import YouTubeVideo YouTubeVideo('Ti5zUD08w5s') YouTubeVideo('jmsFC0mNayM') Explanation: Integración numérica Montecarlo Referencia: - https://ocw.mit.edu/courses/mechanical-engineering/2-086-numerical-computation-for-mechanical-engineers-fall-2014/nutshells-guis/MIT2...
604
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Dependencies Step1: Loading Data First, we want to create our word vectors. For simplicity, we're going to be using a pretrained model. As one of the...
<ASSISTANT_TASK:> Python Code: # Tensorflow import tensorflow as tf print('Tested with TensorFLow 1.2.0') print('Your TensorFlow version:', tf.__version__) # Feeding function for enqueue data from tensorflow.python.estimator.inputs.queues import feeding_functions as ff # Rnn common functions from tensorflow.contrib.le...
605
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Two time correlation example notebook Step4: Brute force correlation set num_levs to 1 and num_bufs to the number of images you want to correlate Step...
<ASSISTANT_TASK:> Python Code: import skbeam.core.correlation as corr from skbeam.core.correlation import two_time_corr, two_time_state_to_results import skbeam.core.roi as roi import skbeam.core.utils as utils from xray_vision.mpl_plotting.roi import show_label_array_on_image import numpy as np import time as ttime im...
606
<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 go/flax-air Flax You probably want to keep the Flax documentation ready in another tab Step1: Functional core Step2: Stateless Linen module Step3...
<ASSISTANT_TASK:> Python Code: # from typing import Callable, Sequence # used ? import flax from flax import linen as nn Explanation: See go/flax-air Flax You probably want to keep the Flax documentation ready in another tab: https://flax.readthedocs.io/ End of explanation # Simple module with matmul layer. Note that ...
607
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: DeepLearning Introduction In this notebook, we introduce H2O Deep Learning via fully-connected artificial neural networks. We also show many useful fea...
<ASSISTANT_TASK:> Python Code: import h2o h2o.init(nthreads=-1) import os.path PATH = os.path.expanduser("~/h2o-3/") test_df = h2o.import_file(PATH + "bigdata/laptop/mnist/test.csv.gz") train_df = h2o.import_file(PATH + "bigdata/laptop/mnist/train.csv.gz") Explanation: DeepLearning Introduction In this notebook, we int...
608
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Visualize the MetaLearning pipeline built on top NitroML. We are using NitroML on Kubeflow Step1: Connect to the ML Metadata (MLMD) database First we ...
<ASSISTANT_TASK:> Python Code: # Step 1: Configure your cluster with gcloud # `gcloud container clusters get-credentials <cluster_name> --zone <cluster-zone> --project <project-id> # Step 2: Get the port where the gRPC service is running on the cluster # `kubectl get configmap metadata-grpc-configmap -o jsonpath={.data...
609
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: TensorFlow Dataset API Learning Objectives 1. Learn how use tf.data to read data from memory 1. Learn how to use tf.data in a training loop 1. Learn ho...
<ASSISTANT_TASK:> Python Code: # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.0 || pip install tensorflow==2.0 import json import math import os from pprint import pprint import numpy as np import tensorflow as tf print(tf.version.VERSION) Explanation: TensorFlow Dataset API Lea...
610
<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: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of ...
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own ...
611
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: DATASCI W261 Step1: Part 1 Step2: (1b) Sparse vectors Data points can typically be represented with a small number of non-zero OHE features relative...
<ASSISTANT_TASK:> Python Code: labVersion = 'MIDS_MLS_week12_v_0_9' %cd ~/Documents/W261/hw12/ import os import sys spark_home = os.environ['SPARK_HOME'] = \ '/Users/davidadams/packages/spark-1.5.1-bin-hadoop2.6/' if not spark_home: raise ValueError('SPARK_HOME enviroment variable is not set') sys.path.insert(0,...
612
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Finite-Length Performance on the BEC Channel This code is provided as supplementary material of the lecture Channel Coding 2 - Advanced Methods. This c...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib import matplotlib.pyplot as plt # plotting options font = {'size' : 20} plt.rc('font', **font) plt.rc('text', usetex=matplotlib.checkdep_usetex(True)) matplotlib.rc('figure', figsize=(18, 6) ) Explanation: Finite-Length Performance on the BEC Channe...
613
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Detecção de Outliers nas Cotas Parlamentares Primeiro, vamos investigar manualmente alguns gastos dos deputados em 2015. Em seguida, usaremos uma técni...
<ASSISTANT_TASK:> Python Code: import pandas as pd ceap = pd.read_csv('dados/ceap2015.csv.zip') linhas, colunas = ceap.shape print('Temos {} entradas com {} colunas cada.'.format(linhas, colunas)) print('Primeira entrada:') ceap.iloc[0] Explanation: Detecção de Outliers nas Cotas Parlamentares Primeiro, vamos investiga...
614
<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 align="center">Testing SimpleITK Setup</h1> Check that SimpleITK and auxilliary program(s) are correctly installed in your environment, and that yo...
<ASSISTANT_TASK:> Python Code: import SimpleITK as sitk from downloaddata import fetch_data, fetch_data_all print(sitk.Version()) Explanation: <h1 align="center">Testing SimpleITK Setup</h1> Check that SimpleITK and auxilliary program(s) are correctly installed in your environment, and that you have the SimpleITK versi...
615
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: SVM, Undersampling and Data Cleaning for Imbalanced Data Date created Step1: <h3>II. Preprocessing </h3> We process the missing values first, dropping...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn.preprocessing import Imputer from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split as tts from sklearn.ensemble impo...
616
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Data Creation Accounts Create several gzipped files Each line in each file is a JSON encoded dictionary with the following keys id Step1: Denormalize ...
<ASSISTANT_TASK:> Python Code: from accounts import create_accounts_json num_files = 25 n = 100000 # number of accounts per file k = 500 # number of transactions create_accounts_json(num_files, n, k) Explanation: Data Creation Accounts Create several gzipped files Each line in each file is a JSON encoded dictionary w...
617
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: About This notebook demonstrates several additional tools to optimize classification model provided by Reproducible experiment platform (REP) package S...
<ASSISTANT_TASK:> Python Code: %pylab inline Explanation: About This notebook demonstrates several additional tools to optimize classification model provided by Reproducible experiment platform (REP) package: grid search for the best classifier hyperparameters different optimization algorithms different scoring models...
618
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Power spectrum example This tutorial shows how to make and manipulate a power spectrum of two light curves using Stingray. Step1: 1. Create a light cu...
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 import numpy as np from stingray import Lightcurve, Powerspectrum, AveragedPowerspectrum import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager %matplotlib inline font_prop = font_manager.FontProperties(size=16) Explanation: Power...
619
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Find Natural Neighbors Verification Finding natural neighbors in a triangulation A triangle is a natural neighbor of a point if that point is within a ...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np from scipy.spatial import Delaunay from metpy.gridding.triangles import find_natural_neighbors # Create test observations, test points, and plot the triangulation and points. gx, gy = np.meshgrid(np.arange(0, 20, 4), np.arange(0, 20, 4)) ...
620
<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 would like to predict the probability from Logistic Regression model with cross-validation. I know you can get the cross-validation scores, ...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import StratifiedKFold X, y = load_data() assert type(X) == np.ndarray assert type(y) == np.ndarray cv = StratifiedKFold(5).split(X, y) logreg = LogisticRegression() fro...
621
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Polynomial Regression What if your data doesn't look linear at all? Let's look at some more realistic-looking page speed / purchase data Step1: numpy ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from pylab import * np.random.seed(2) pageSpeeds = np.random.normal(3.0, 1.0, 1000) purchaseAmount = np.random.normal(50.0, 10.0, 1000) / pageSpeeds scatter(pageSpeeds, purchaseAmount) Explanation: Polynomial Regression What if your data doesn't look linear at all? Let'...
622
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Data Wrangling with OpenStreetMap <br/> Final Project Author Step1: Number of nodes Step2: Number of ways Step3: Top 10 types of amenities Step4: T...
<ASSISTANT_TASK:> Python Code: bayarea.find().count() Explanation: Data Wrangling with OpenStreetMap <br/> Final Project Author: William Truong Map Area: San Francisco Bay Area, CA, United States Sources: Mapzen Metro Extract Link Audit and Shaping into JSON IPython Notebook Audit and Shaping into JSON IPython Note...
623
<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: \title{Logic Gate Primitives in myHDL} \author{Steven K Armour} \maketitle <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="t...
<ASSISTANT_TASK:> Python Code: #This notebook also uses the `(some) LaTeX environments for Jupyter` #https://github.com/ProfFan/latex_envs wich is part of the #jupyter_contrib_nbextensions package from myhdl import * from myhdlpeek import Peeker import numpy as np import pandas as pd import matplotlib.pyplot as plt %ma...
624
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: 10 Mining Social-Network Graphs how to identify "communities"? communities Step1: Is Fig 10.1 typical of a social network, in the sense that it ...
<ASSISTANT_TASK:> Python Code: plt.imshow(plt.imread('./res/fig10_1.png')) Explanation: 10 Mining Social-Network Graphs how to identify "communities"? communities: strong connections, usually overlap. explore efficient algorithms for discovering other properities of graphs. 10.1 Social Networks as Graphs 10.1.1 W...
625
<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: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and othe...
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if ...
626
<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 Authors. Step1: tf.dataを使って画像をロードする <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href...
<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...
627
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Fast Proportional Selection [RETWEET] Proportional selection -- or, roulette wheel selection -- comes up frequently when developing agent-based models....
<ASSISTANT_TASK:> Python Code: import random from bisect import bisect_left import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns %matplotlib inline Explanation: Fast Proportional Selection [RETWEET] Proportional selection -- or, roulette wheel selection -- comes up frequently whe...
628
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> 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 im...
<ASSISTANT_TASK:> Python Code: import time import numpy as np import tensorflow as tf 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 about embedding words for u...
629
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: .. _tut_stats_cluster_methods Step1: Set parameters Step2: Construct simulated data Make the connectivity matrix just next-neighbor spatially Step...
<ASSISTANT_TASK:> Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import numpy as np from scipy import stats from functools import partial import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa; this changes hidden mpl vars from mne.stats import (spatio_t...
630
<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 - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributor...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-lr', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: EC-EARTH...
631
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Region of interest This notebook detects signals, or regions of interest, in a spectrogram generated from a recording of the natural acoustic environme...
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy.ndimage import label, find_objects from scipy.ndimage.morphology import generate_binary_structure import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from nacoustik import Wave from nacoustik.spectrum import psd from nacoustik.noise impor...
632
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the d...
<ASSISTANT_TASK:> Python Code: import pandas as pd %matplotlib inline import numpy as np from sklearn.linear_model import LogisticRegression Explanation: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and ...
633
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Example on How to Use Net Yields Prepared by Christian Ritter Step1: Default setup - total yields Step2: Setup with total yields as input but net yie...
<ASSISTANT_TASK:> Python Code: %matplotlib nbagg import matplotlib.pyplot as plt import sys import matplotlib import numpy as np from NuPyCEE import sygma as s from NuPyCEE import omega as o from NuPyCEE import stellab from NuPyCEE import read_yields as ry table='yield_tables/agb_and_massive_stars_nugrid_MESAonly_fryer...
634
<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 - Distributed training in a notebook! Using Accelerate to launch a training script from your notebook Step1: Overview In this tutorial we wil...
<ASSISTANT_TASK:> Python Code: #|all_multicuda Explanation: Tutorial - Distributed training in a notebook! Using Accelerate to launch a training script from your notebook End of explanation #hide from fastai.vision.all import * from fastai.distributed import * from fastai.vision.models.xresnet import * from accelerate ...
635
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: <h3>Current School Panda</h3> Working with directory school data Creative Commons in all schools This script uses a csv file from Creative Commons New ...
<ASSISTANT_TASK:> Python Code: crcom = pd.read_csv('/home/wcmckee/Downloads/List of CC schools - Sheet1.csv', skiprows=5, index_col=0, usecols=[0,1,2]) Explanation: <h3>Current School Panda</h3> Working with directory school data Creative Commons in all schools This script uses a csv file from Creative Commons New Zeal...
636
<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 3c Step1: Lab Task #1 Step2: Get training information and evaluate Let's first look at our training statistics. Step3: Now let's evaluate our tr...
<ASSISTANT_TASK:> Python Code: %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_train LIMIT 0 %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_eval LIMIT 0 Explanat...
637
<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: Human Pose Classification with MoveNet and TensorFlow Lite This notebook teaches you how to train a pose...
<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...
638
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Exploratory work on the ABPI Disclosure data This notebook sets out our initial exploratory analysis of the new ABPI Disclosure data on payments from ...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np pd.set_option('display.float_format', lambda x: '%.2f' % x) dtype = { 'Title': str, 'First Name': str, 'Last Name': str, 'Speciality': str, 'Institution Name': str } df = pd.read_csv('./data/payments.csv', dtype=dtype) Explanation...
639
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Q001 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is...
<ASSISTANT_TASK:> Python Code: solution = 0 N = 0 while N < 1000: if (N % 3 == 0) or (N % 5 == 0): solution = solution + N N+=1 print solution Explanation: Q001 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples...
640
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: 阅读笔记 作者:方跃文 Email Step1: 基础知识 语言语义 python语言的设计特点是重视可读性、简洁性和明确性。 缩进,而不是大括号 python是通过空白符(制表符或者空格)来阻止代码的,不像R、C++等用的是大括号。该书原作者建议使用4空格作为缩进量。 万物皆对象 pytho...
<ASSISTANT_TASK:> Python Code: %run appendix-A/simple01.py Explanation: 阅读笔记 作者:方跃文 Email: fyuewen@gmail.com 时间:始于2017年9月12日, 结束写作于 附录 A 附录A在原书最后,不过我自己为了复习python的一些命令,所以特意将这一部分提前到此。 python 解释器 python解释器通过“一次执行一条语句”的方式运行程序。多加利用Ipython。 通过使用 %run 命令,IPython 会在同个进程中执行指定文件中的代码。例如我在当年目录的下级目录appendix-A中创建了一个simple01.py...
641
<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 Network Tour of Data Science Michaël Defferrard, PhD student, Pierre Vandergheynst, Full Professor, EPFL LTS2. Exercise 5 Step1: 1 Graph Goal Step2:...
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy.spatial import matplotlib.pyplot as plt %matplotlib inline Explanation: A Network Tour of Data Science Michaël Defferrard, PhD student, Pierre Vandergheynst, Full Professor, EPFL LTS2. Exercise 5: Graph Signals and Fourier Transform The goal of this exercis...
642
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Ants in Space! An introduction to the code in beam_paco__gtoc5 Luís F. Simões 2017-04 <h1 id="tocheading">Table of Contents</h1> <div id="toc"></div> S...
<ASSISTANT_TASK:> Python Code: # https://esa.github.io/pykep/ # https://github.com/esa/pykep # https://pypi.python.org/pypi/pykep/ import PyKEP as pk import numpy as np from tqdm import tqdm, trange import matplotlib.pylab as plt %matplotlib inline import seaborn as sns plt.rcParams['figure.figsize'] = 10, 8 from gtoc5...
643
<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 - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributo...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'dwd', 'sandbox-1', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: DWD Source ID: SANDBOX-1 Topic: Landice Sub-Topics: Glac...
644
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Módulo 3 Step1: Operações com Arquivos Criando os Arquivos Criando Estrutura de Pastas Step5: Dataset orders.csv Step9: Dataset stores.csv Step13: ...
<ASSISTANT_TASK:> Python Code: import os import pandas as pd Explanation: Módulo 3: Leitura e Escrita em Arquivos + Combinando Tabelas Tutorial Imports para a Aula End of explanation try: os.makedirs(os.path.join("data", "tutorial")) print("Pasta criada.") except OSError: print("Pasta já existe!") Explanati...
645
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Prevalence of Personal Attacks In this notebook, we do some basic investigation into the frequency of personal attacks on Wikipedia. We will attempt to...
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import warnings warnings.filterwarnings('ignore') import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd from load_utils import * from analysis_utils import compare_groups d = load_diffs() df_event...
646
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Import Libraries Step1: Read image and Check inspect values of image at different locations Step2: RGB pixel intensity 0-255 Step3: RGB line intensi...
<ASSISTANT_TASK:> Python Code: import cv2 import matplotlib.pyplot as plt %matplotlib inline Explanation: Import Libraries End of explanation img_RGB = cv2.imread('demo1.jpg') plt.imshow(cv2.cvtColor(img_RGB, cv2.COLOR_BGR2RGB)) print('Shape_RGB:', img_RGB.shape) print('Type_RGB:', img_RGB.dtype) Explanation: Read imag...
647
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: WARNING It is a non-public API. It may change with no previous notice We are going to show how to work with the CARTO custom visualizations (aka Kuviz)...
<ASSISTANT_TASK:> Python Code: USERNAME = "" BASE_URL = "https://{u}.carto.com".format(u=USERNAME) API_KEY = "" from carto.auth import APIKeyAuthClient auth_client = APIKeyAuthClient(api_key=API_KEY, base_url=BASE_URL) Explanation: WARNING It is a non-public API. It may change with no previous notice We are going to sh...
648
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: There are 50 observations and 5 columns. 4 columns - R&D Spend, Administration and Marketing Spend, and Profile are numeric and one is categorical - St...
<ASSISTANT_TASK:> Python Code: df_null_idx = df[df.isnull().sum(axis = 1) > 0].index df.iloc[df_null_idx] median_values = df.groupby("State")[["R&D Spend", "Marketing Spend"]].median() median_values df["R&D Spend"] = df.apply(lambda row: median_values.loc[row["State"], "R&D Spend"] if np.isnan(row["R&D Spend"]) else r...
649
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: RichStr consist of pieces of strings and RichStrs Step1: __repr__esentation of a rich string shows a "flat" representation of a RichStr - a sequence o...
<ASSISTANT_TASK:> Python Code: n=RichStr("I am ", "normal") Explanation: RichStr consist of pieces of strings and RichStrs End of explanation n Explanation: __repr__esentation of a rich string shows a "flat" representation of a RichStr - a sequence of styles and strings where style applies to everything after it. This ...
650
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: You can download water chemistry of an entire HUC. It downloads wells and springs and major ions by default, unless specified otherwise. Step1: Stand...
<ASSISTANT_TASK:> Python Code: chem = wa.WQP(16020301,'huc') Explanation: You can download water chemistry of an entire HUC. It downloads wells and springs and major ions by default, unless specified otherwise. End of explanation Results = chem.massage_results() Stations = chem.massage_stations() Piv = chem.piv_chem()...
651
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Analyse hsa-miR-124a-3p transfection time-course In order to do this analysis you have to be in the tests directory of GEOparse. In the paper Systemati...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import GEOparse import pandas as pd import pylab as pl import seaborn as sns pl.rcParams['figure.figsize'] = (14, 10) pl.rcParams['ytick.labelsize'] = 12 pl.rcParams['xtick.labelsize'] = 11 pl.rcParams['axes.labelsize'] = 23 pl.rcParams['legend.fontsize'] = 20 sns.set_s...
652
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: The EDEX modelsounding plugin creates 64-level vertical profiles from GFS and ETA (NAM) BUFR products distirubted over NOAAport. Paramters which are re...
<ASSISTANT_TASK:> Python Code: from awips.dataaccess import DataAccessLayer import matplotlib.tri as mtri import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes from math import exp, log import numpy as np from metpy.calc import get_wind_components, lcl, dry_lapse, parcel_profile, ...
653
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: DataFrame object Create SparkContext and SparkSession Step1: Create a DataFrame object Creat DataFrame by reading a file Step2: Create DataFrame with...
<ASSISTANT_TASK:> Python Code: from pyspark import SparkContext sc = SparkContext(master = 'local') from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("Python Spark SQL basic example") \ .config("spark.some.config.option", "some-value") \ .getOrCreate() Explanatio...
654
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Plotting whitened data This tutorial demonstrates how to plot Step1: Raw data with whitening <div class="alert alert-info"><h4>Note</h4><p>In the St...
<ASSISTANT_TASK:> Python Code: import mne from mne.datasets import sample Explanation: Plotting whitened data This tutorial demonstrates how to plot :term:whitened &lt;whitening&gt; evoked data. Data are whitened for many processes, including dipole fitting, source localization and some decoding algorithms. Viewing whi...
655
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Rotations" data-toc-modified-id="Rotations-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import xgboost as xgb from sklearn.metrics import roc_curve, auc from sklearn.metrics import precision_recall_curve df = pd.read_csv("iris.csv") Explanation: Table of Contents <p><div class="lev1 ...
656
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: This notebook presents the techniques of displaying the precision of the Radio Telemetry Tracker system. Step1: Model Estimation To determine the loca...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt; plt.ion() from scipy.optimize import least_squares from scipy import stats as st Explanation: This notebook presents the techniques of displaying the precision of the Radio Telemetry Tracker system. End of explanation def receivePowerMod...
657
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Locating TFBS I will be using Biopython's Bio.motifs package. I cannot get the python 3 kernel working with the biopython package. This needs to be f...
<ASSISTANT_TASK:> Python Code: from Bio import motifs from Bio import SeqIO from Bio.Seq import Seq from Bio.Alphabet import IUPAC, generic_dna, generic_protein import pandas as pd import os, sys Explanation: Locating TFBS I will be using Biopython's Bio.motifs package. I cannot get the python 3 kernel working with t...
658
<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 - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-lmec', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: NCC Source ID: NORESM2-LMEC Topic: Atmos Sub-Topics: Dyna...
659
<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 - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'uhh', 'sandbox-1', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: UHH Source ID: SANDBOX-1 Topic: Atmos Sub-Topics: Dynamical ...
660
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Visualizing Evoked data This tutorial shows the different visualization methods for ~mne.Evoked objects. As usual we'll start by importing the modules ...
<ASSISTANT_TASK:> Python Code: import os import numpy as np import mne Explanation: Visualizing Evoked data This tutorial shows the different visualization methods for ~mne.Evoked objects. As usual we'll start by importing the modules we need: End of explanation sample_data_folder = mne.datasets.sample.data_path() samp...
661
<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 time-series A holding several values. I need to obtain a series B that is defined algebraically as follows:
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd A = pd.Series(np.random.randn(10,)) a = 2 b = 3 B = np.empty(len(A)) for k in range(0, len(B)): if k == 0: B[k] = a*A[k] else: B[k] = a*A[k] + b*B[k-1] <END_TASK>
662
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Methane Step1: Any Compound can contain other Compounds which can be added using its add() method. Compounds at the bottom of such a hierarchy are ref...
<ASSISTANT_TASK:> Python Code: import mbuild as mb class Methane(mb.Compound): def __init__(self): super(Methane, self).__init__() Explanation: Methane: Compounds and bonds Note: mBuild expects all distance units to be in nanometers. The primary building block in mBuild is a Compound. Anything you construct...
663
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Visualizando datos de entrada Step1: Algoritmo de Regresion Lineal en TensorFlow Step2: Regresion Lineal en Polinomios de grado N Step3: Regularizac...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt # Regresa 101 numeros igualmmente espaciados en el intervalo[-1,1] x_train = np.linspace(-1, 1, 101) # Genera numeros pseudo-aleatorios multiplicando la matriz x_train * 2 y # sumando a cada elemento un ruido (una matriz del mismo tamani...
664
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Midterm Review CSCI 1360E Step1: Answering this is not simply taking what's in the autograder and copy-pasting it into your solution Step2: The whole...
<ASSISTANT_TASK:> Python Code: number = 3.14159265359 Explanation: Midterm Review CSCI 1360E: Foundations for Informatics and Analytics Material Anything in Lectures 1 through 10 are fair game! Anything in assignments 1 through 4 are fair game! Topics Data Science - Definition - Intrinsic interdisciplinarity - "Grea...
665
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: So my the code for my solution can be found in Step1: The above bit of boiler-plate code is useful in a number of situations. Indeed, this is a patter...
<ASSISTANT_TASK:> Python Code: ## Assume that this code exists in a file named example.py def main(): print(1 + 1) if __name__ == "__main__": main() Explanation: So my the code for my solution can be found in: ../misc/minesweeper.py In this lecture I shall be going through some bits of code and explaining parts...
666
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Analyzing Data using Python and SQLite3 SQLite basics Create a connection conn = sqlite3.connect('database_file') cur = conn.curser() Execute SQL comma...
<ASSISTANT_TASK:> Python Code: import sqlite3 conn = sqlite3.connect('election_tweets.sqlite') cur = conn.cursor() Explanation: Analyzing Data using Python and SQLite3 SQLite basics Create a connection conn = sqlite3.connect('database_file') cur = conn.curser() Execute SQL commands execute: cur.execute('SQL COMMANDS') ...
667
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Model16 Step1: Right, now, you can use those module. GMM Classifying questions features Step3: B. Modeling Select model Step4: n_iter=10
<ASSISTANT_TASK:> Python Code: from utils import load_buzz, select, write_result from features import featurize, get_pos from containers import Questions, Users, Categories Explanation: Model16: Extract common functions Now, we know what kind of common functions we need. So, I have make some functions which we used as ...
668
<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-scan from a metal cylinder (2D) This example is the GPR modelling equivalent of 'Hello World'! It demonstrates how to simulate a single trace (A-scan...
<ASSISTANT_TASK:> Python Code: %%writefile ../../user_models/cylinder_Ascan_2D.in #title: A-scan from a metal cylinder buried in a dielectric half-space #domain: 0.240 0.210 0.002 #dx_dy_dz: 0.002 0.002 0.002 #time_window: 3e-9 #material: 6 0 1 0 half_space #waveform: ricker 1 1.5e9 my_ricker #hertzian_dipole: z 0.100 ...
669
<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 1 Step1: Load house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is located. Step2:...
<ASSISTANT_TASK:> Python Code: import graphlab Explanation: Regression Week 1: Simple Linear Regression In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will: * Use graphlab SArray and SFrame functions to compute important summary st...
670
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Healthy Communities Data and Indicators Project (HCI) Healthy Communities Data and Indicators Project (HCI) Step2: First, create a set of views to lim...
<ASSISTANT_TASK:> Python Code: from ambry import get_library l = get_library() b = l.bundle('cdph.ca.gov-hci-0.0.2') Explanation: Healthy Communities Data and Indicators Project (HCI) Healthy Communities Data and Indicators Project (HCI) End of explanation w = b.warehouse('hci_counties') w.clean() print w.dsn w.query( ...
671
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: MIDS - w261 Machine Learning At Scale Course Lead Step1: <a name="HW10.1.1"><h2 style="color Step2: <a name="HW10.2"> <h2 style="color Step3: <a nam...
<ASSISTANT_TASK:> Python Code: ## Code goes here ## Drivers & Runners ## Run Scripts, S3 Sync Explanation: MIDS - w261 Machine Learning At Scale Course Lead: Dr James G. Shanahan (email Jimi via James.Shanahan AT gmail.com) Assignment - HW10 Name: Your Name Goes Here Class: MIDS w261 (Section Your Section Goes Here,...
672
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: benchmarking for the basic document and efficient document Step1: Plot the Basic and Efficient data first Basic Step2: do a linear regression for the...
<ASSISTANT_TASK:> Python Code: data = pd.read_csv('../benchMarkingResult.txt', header=None, sep='\t', names=('iteration', 'basic_result', 'efficient_result')) Explanation: benchmarking for the basic document and...
673
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: SCat Algorithm I have pushed multiple iterations of a simple sequence labeling algorithm called SCat. This iteration is the first version that will be ...
<ASSISTANT_TASK:> Python Code: # Find the city in a weather related query train_x = [ "What is the weather like in Paris ?", "What kind of weather will it do in London ?", "Give me the weather forecast in Berlin please .", "Tell me the forecast in New York !", "Give me the weather in San Francisco ....
674
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Writing Low-Level TensorFlow Code Learning Objectives Practice defining and performing basic operations on constant Tensors Use Tensorflow's automatic ...
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.1 || pip install tensorflow==2.1 import numpy as np import tensorflow as tf from matplotlib import pyplot as plt print(tf.__version__)...
675
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Loads the mechanical Turk data Run this script to load the data. Your job after loading the data is to make a 20 questions style game (see www.20q.net ...
<ASSISTANT_TASK:> Python Code: # Read in the list of 250 movies, making sure to remove commas from their names # (actually, if it has commas, it will be read in as different fields) import csv movies = [] with open('movies.csv','r') as csvfile: myreader = csv.reader(csvfile) for index, row in enumerate(myreader...
676
<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 TensorFlow with GPU Step1: Multiply 2 matrices Step2: Sessions must be closed to release resources. We may use the 'with' syntax to close sess...
<ASSISTANT_TASK:> Python Code: !nvidia-smi import tensorflow as tf sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) logdir = '/root/pipeline/logs/tensorflow' import numpy as np import matplotlib.pyplot as plt import datetime from tensorflow.python.framework import ops from tensorflow.python.platform ...
677
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Example Step2: The first thing we shall need is holdings data. For this example, we assume that holdings data is provided in a CSV format, and insert ...
<ASSISTANT_TASK:> Python Code: import loman comp = loman.Computation() Explanation: Example: Using Loman to Value a Portfolio In this example, we'll look at valuing a simple portfolio composed of equities and futures. In additional, we'll calculate an intraday P&L, and some simple exposure measures. The main challenge ...
678
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Exact solution used in MES runs We would like to MES the operation $$ \nabla \cdot \mathbf{f}_\perp $$ Using cylindrical geometry. Step1: Initialize S...
<ASSISTANT_TASK:> Python Code: %matplotlib notebook from sympy import init_printing from sympy import S from sympy import sin, cos, tanh, exp, pi, sqrt from boutdata.mms import x, y, z, t from boutdata.mms import Delp2, DDX, DDY, DDZ import os, sys # If we add to sys.path, then it must be an absolute path common_dir = ...
679
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Resolviendo un Laberinto El problema es muy sencillo Step1: Pintemos el laberinto! Step2: Queda chulo, ¿verdad? Creando un camino a partir de un geno...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import laberinto.algen as ag import laberinto.laberinto as lab import numpy as np import matplotlib.pyplot as plt mapa1 = lab.Map() Explanation: Resolviendo un Laberinto El problema es muy sencillo: tenemos un laberinto, y deseamos que nuestro algoritmo genético encuent...
680
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Facies classification using Machine Learning aaML Submission By Step1: Loading the data training data without Shankle well Step2: Loading the SHANKLE...
<ASSISTANT_TASK:> Python Code: from libtools import * Explanation: Facies classification using Machine Learning aaML Submission By: Alexsandro G. Cerqueira, Alã de C. Damasceno There are tow main notebooks: Data Analysis and edition Submission End of explanation training = pd.read_csv('data-test.csv') training.head()...
681
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: First Taste of Plotly Step1: Try Plotting a Dirichlet Distribution Step4: Make an Interactive 3D Plot with Parameter Selection
<ASSISTANT_TASK:> Python Code: trace0 = go.Scatter( x=[1, 2, 3, 4], y=[10, 15, 13, 17] ) trace1 = go.Scatter( x=[1, 2, 3, 4], y=[16, 5, 11, 9] ) data = go.Data([trace0, trace1]) py.iplot(data, filename = 'basic-line') Explanation: First Taste of Plotly End of explanation alpha = np.array([5, 5, 5]) rv =...
682
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Distribution Test Tables This example demonstrates how to create some conditional probability tables and a bayesian network. Step1: First let's define...
<ASSISTANT_TASK:> Python Code: from pomegranate import * import math Explanation: Distribution Test Tables This example demonstrates how to create some conditional probability tables and a bayesian network. End of explanation c_table = [[0, 0, 0, 0.6], [0, 0, 1, 0.4], [0, 1, 0, 0.7], [0...
683
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Objective Build a Sentiment Classifier Step1: Load Data Load Training Data Split into Train and Validation Step2: Vectorize Vectorize using Scikit-Le...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function # Python 2/3 compatibility import numpy as np import pandas as pd from IPython.display import Image Explanation: Objective Build a Sentiment Classifier End of explanation ## Your Turn Explanation: Load Data Load Training Data Split into Train and Val...
684
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Simulating with FBA Simulations using flux balance analysis can be solved using Model.optimize(). This will maximize or minimize (maximizing is the def...
<ASSISTANT_TASK:> Python Code: from cobra.io import load_model model = load_model("textbook") Explanation: Simulating with FBA Simulations using flux balance analysis can be solved using Model.optimize(). This will maximize or minimize (maximizing is the default) flux through the objective reactions. End of explanation...
685
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Mixed Precision Training Introduction Traditionally, for training a neural network, we used to use FP32 for weights and activations; however computatio...
<ASSISTANT_TASK:> Python Code: ctx = get_extension_context("cudnn", type_config="half") Explanation: Mixed Precision Training Introduction Traditionally, for training a neural network, we used to use FP32 for weights and activations; however computation costs for training a neural network rapidly increase over years as...
686
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Rich Output In Python, objects can declare their textual representation using the __repr__ method. IPython expands on this idea and allows objects to ...
<ASSISTANT_TASK:> Python Code: from IPython.display import display Explanation: Rich Output In Python, objects can declare their textual representation using the __repr__ method. IPython expands on this idea and allows objects to declare other, rich representations including: HTML JSON PNG JPEG SVG LaTeX A single obje...
687
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Map election results to regions. Assumes you have huffpostdata/election-2012-results cloned at ../../election-2012-results. Does 2000 regions by defaul...
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function %matplotlib inline import numpy as np import pandas as pd import re import six from IPython.display import display import sys sys.path.append('..') from pummeler.data import geocode_data county_to_region = geocode_data('county_region_10').re...
688
<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 - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-1', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-1 Topic: Ocean Sub-Topics...
689
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Assign NERC labels to plants using 860 data and RandomForest Instructions Make sure the file_date parameter below is set to whatever value you would li...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import os from os.path import join import pandas as pd from sklearn import neighbors, metrics from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split, GridSearchCV from collections import Counte...
690
<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. Кластеризация Выбор оптимального количества кластеров Кластерный анализ (Data clustering) — это задача разбиения заданной выборки объектов (ситуаци...
<ASSISTANT_TASK:> Python Code: #импортируем библиотеки import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import make_blobs from sklearn.cluster import DBSCAN plt.figure(figsize=(12, 12)) n_samples = 2300 random_state = 220 X, y = make_blobs(n_samples=n_samples, ...
691
<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 12 – Distributed TensorFlow This notebook contains all the sample code and solutions to the exercises in chapter 12. Setup First, let's make su...
<ASSISTANT_TASK:> Python Code: # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os # to make this notebook's output stable across runs def reset_graph(seed=42): tf.reset_default_graph() tf.set_random_seed(seed) ...
692
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Update domain in Research Sometimes one needs to change the domain of parameters during Research execution. update_domain mathod helps to do that. We s...
<ASSISTANT_TASK:> Python Code: import sys import os import shutil import numpy as np import matplotlib %matplotlib inline os.environ["CUDA_VISIBLE_DEVICES"] = "6" sys.path.append('../../..') from batchflow import Pipeline, B, C, V, D, L from batchflow.opensets import CIFAR10 from batchflow.models.torch import VGG7, VGG...
693
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: The FrameAgentType is an alternative way to specify a model. The library contains a demonstration of this form of model, ConsPortfolioFrameModel, which...
<ASSISTANT_TASK:> Python Code: pct = cpm.PortfolioConsumerType(T_sim=5000, AgentCount=200) pct.cycles = 0 # Solve the model under the given parameters pct.solve() pct.track_vars += [ "mNrm", "cNrm", "Share", "aNrm", "Risky", "Adjust", "PermShk", "TranShk", "bNrm", "who_dies" ] pc...
694
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Projecting terrestrial biodiversity using PREDICTS and LUH2 This notebook shows how to use rasterset to project a PREDICTS model using the LUH2 land-us...
<ASSISTANT_TASK:> Python Code: import click %matplotlib inline import matplotlib.pyplot as plt import numpy as np import numpy.ma as ma import rasterio from rasterio.plot import show, show_hist Explanation: Projecting terrestrial biodiversity using PREDICTS and LUH2 This notebook shows how to use rasterset to project a...
695
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: SVM Learning Load Dataset Step1: Train-Test Split Before we construct out model pipeline, we divide the dataset into separate a separate training data...
<ASSISTANT_TASK:> Python Code: from coherence import load_coherence_dataset coherence_ds = load_coherence_dataset() X = coherence_ds.data y = coherence_ds.target Explanation: SVM Learning Load Dataset End of explanation from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_...
696
<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 - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contribut...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'miroc', 'sandbox-3', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: MIROC Source ID: SANDBOX-3 Sub-Topics: Radiative For...
697
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Basic Principles of Machine Learning Her...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn') Explanation: <small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small> Basic Principles of Machine Learning Here we'll dive into the basic pr...
698
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: << nazaj Step1: 3. naloga Step2: Polje za diskusijo Naslednje kode ni treba poganjati, saj je namenjena le temu, da se na koncu zvezka prikaže polje ...
<ASSISTANT_TASK:> Python Code: 1+1 Explanation: << nazaj: Predgovor Uvod Preden se lotimo trenja matematičnih orehov s kladivom imenovanim Python, si moramo pripraviti primerno okolje. Dokumenti so napisani v obliki Jupyter notebook, ki je interaktivno okolje za Python, v katerem lahko združujemo programsko kodo in be...
699
<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="https Step1: Environment Preparation Install bigdl-chronos You can install the latest pre-release version with chronos support using pip inst...
<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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...