Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
9,000
Given the following text description, write Python code to implement the functionality described below step by step Description: Initial investigation of drug-gene networks Brin Rosenthal (sbrosenthal@ucsd.edu) April 15, 2016 Prototype for tool to be added to Search Goals Step1: Test drug_gene_heatprop module This...
Python Code: # import some useful packages import numpy as np import matplotlib.pyplot as plt import seaborn import networkx as nx import pandas as pd import random import json # latex rendering of text in graphs import matplotlib as mpl mpl.rc('text', usetex = False) mpl.rc('font', family = 'serif') % matplotlib inlin...
9,001
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 DeepMind Technologies Limited. 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 ...
Python Code: !pip install dm-acme !pip install dm-acme[reverb] !pip install dm-acme[tf] !pip install dm-sonnet Explanation: Copyright 2020 DeepMind Technologies Limited. 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...
9,002
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatial Joins A spatial join uses binary predicates such as intersects and crosses to combine two GeoDataFrames based on the spatial relationship between their geometries. A common use cas...
Python Code: %matplotlib inline from shapely.geometry import Point from geopandas import datasets, GeoDataFrame, read_file # NYC Boros zippath = datasets.get_path('nybb') polydf = read_file(zippath) # Generate some points b = [int(x) for x in polydf.total_bounds] N = 8 pointdf = GeoDataFrame([ {'geometry': Point(x,...
9,003
Given the following text description, write Python code to implement the functionality described below step by step Description: EXP 1-Random In this experiment we generate 1000 sequences each comprising 10 SDRs generated at random. We present these sequences to the TM with learning "on". Each training epoch starts by...
Python Code: import numpy as np import random import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from nupic.bindings.algorithms import TemporalMemory as TM from htmresearch.support.neural_correlations_utils import * uintType = "uint32" random.seed(1) symbolsPerSequence = 10 numSequences = 1000...
9,004
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading the data Step1: Build clustering model Here we build a kmeans model , and select the "optimal" of clusters. Here we see that the optimal number of clusters is 2. Step2: Build the o...
Python Code: def loadContributions(file, withsexe=False): contributions = pd.read_json(path_or_buf=file, orient="columns") rows = []; rindex = []; for i in range(0, contributions.shape[0]): row = {}; row['id'] = contributions['id'][i] rindex.append(contributions['id'][i]) ...
9,005
Given the following text description, write Python code to implement the functionality described below step by step Description: Cell Magic Tutorial Interactions with MLDB occurs via a REST API. Interacting with a REST API over HTTP from a Notebook interface can be a little bit laborious if you're using a general-purp...
Python Code: %reload_ext pymldb Explanation: Cell Magic Tutorial Interactions with MLDB occurs via a REST API. Interacting with a REST API over HTTP from a Notebook interface can be a little bit laborious if you're using a general-purpose Python library like requests directly, so MLDB comes with a Python library called...
9,006
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Week 3 Step1: Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers...
Python Code: import pandas as pd import numpy as np Explanation: Regression Week 3: Assessing Fit (polynomial regression) In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you wil...
9,007
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Topics Step1: Using scalar aggregates in filters Step2: We could always compute some aggregate value from the table and use that in another expression, or we can use a data-derive...
Python Code: import ibis import os hdfs_port = os.environ.get('IBIS_WEBHDFS_PORT', 50070) hdfs = ibis.hdfs_connect(host='quickstart.cloudera', port=hdfs_port) con = ibis.impala.connect(host='quickstart.cloudera', database='ibis_testing', hdfs_client=hdfs) ibis.options.interactive = True Explan...
9,008
Given the following text description, write Python code to implement the functionality described below step by step Description: Filtro dos 10 crimes com mais ocorrências em abril Step1: Todas as ocorrências criminais de abril Step2: As 5 regiões com mais ocorrências Step3: Acima podemos ver que a região 1 teve o m...
Python Code: all_crime_tipos.head(10) all_crime_tipos_top10 = all_crime_tipos.head(10) all_crime_tipos_top10.plot(kind='barh', figsize=(12,6), color='#3f3fff') plt.title('Top 10 crimes por tipo (Abr 2017)') plt.xlabel('Número de crimes') plt.ylabel('Crime') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter...
9,009
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Example 1b Step3: Simulation 1 Step4: Simulation 2 Step5: Simulation 3 Step6: Simulation 4 Step7: Simulation 5 Step8: Create Plot
Python Code: import contextlib import time import numpy as np from scipy.optimize import curve_fit import matplotlib import matplotlib.pyplot as plt %matplotlib inline from qutip import * from qutip.ipynbtools import HTMLProgressBar from qutip.nonmarkov.heom import HEOMSolver, BosonicBath, DrudeLorentzBath, DrudeLorent...
9,010
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Variational Autoencoder to Generate Digital Numbers Variational Autoencoders (VAEs) are very popular approaches to unsupervised learning of complicated distributions. In this example, ...
Python Code: # a bit of setup import numpy as np from bigdl.nn.criterion import * from bigdl.dataset import mnist from zoo.pipeline.api.keras.layers import * from zoo.pipeline.api.keras.models import Model from zoo.pipeline.api.keras.utils import * import datetime as dt IMAGE_SIZE = 784 IMAGE_ROWS = 28 IMAGE_COLS = 28 ...
9,011
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute all-to-all connectivity in sensor space Computes the Phase Lag Index (PLI) between all gradiometers and shows the connectivity in 3D using the helmet geometry. The left visual stimul...
Python Code: # Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu> # # License: BSD (3-clause) import mne from mne import io from mne.connectivity import spectral_connectivity from mne.datasets import sample from mne.viz import plot_sensors_connectivity print(__doc__) Explanation: Compute all-to-all connectivity in sen...
9,012
Given the following text description, write Python code to implement the functionality described below step by step Description: HyperParameter Tuning keras.wrappers.scikit_learn Example adapted from Step1: Data Preparation Step2: Build Model Step3: GridSearch HyperParameters
Python Code: import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.utils import np_utils from keras.wrappers.scikit_learn im...
9,013
Given the following text description, write Python code to implement the functionality described below step by step Description: Concatenated all 4 databases into one called "MyLA311_All_Requests.csv" Step1: Parsed the merged database for all empty coordinates and removed them Step2: Splitting the CreatedDate column...
Python Code: fifteen = pd.read_csv("MyLA311_Service_Request_Data_2015.csv", low_memory = False) sixteen = pd.read_csv("MyLA311_Service_Request_Data_2016.csv", low_memory = False) seventeen = pd.read_csv("MyLA311_Service_Request_Data_2017.csv", low_memory = False) eighteen = pd.read_csv("MyLA311_Service_Request_Data_201...
9,014
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis When you vizualize your network, you also want to analize the network. In this section, you can learn basic analysis methods to network. The methods used in this section are prepare...
Python Code: # import data from url from py2cytoscape.data.cyrest_client import CyRestClient from IPython.display import Image # Create REST client for Cytoscape cy = CyRestClient() # Reset current session for fresh start cy.session.delete() # Load a sample network network = cy.network.create_from('http://chianti.ucsd....
9,015
Given the following text description, write Python code to implement the functionality described below step by step Description: Function histogram Synopse Image histogram. h = histogram(f) f Step1: Function Code for brute force implementation Step2: Function code for bidimensional matrix implementation Step3: Exam...
Python Code: import numpy as np def histogram(f): return np.bincount(f.ravel()) Explanation: Function histogram Synopse Image histogram. h = histogram(f) f: Input image. Pixel data type must be integer. h: Output, integer vector. Description This function computes the number of occurrence of each pixel value. The ...
9,016
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to pandas Pandas! They are adorable animals. You might think they are the worst animal ever but that is not true. You might sometimes think pandas is the worst library every,...
Python Code: # import pandas, but call it pd. Why? Because that's What People Do. import pandas as pd Explanation: An Introduction to pandas Pandas! They are adorable animals. You might think they are the worst animal ever but that is not true. You might sometimes think pandas is the worst library every, and that is on...
9,017
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Part 15 Step1: To begin, let's import all the libraries we'll need and load the dataset (which comes bundled with Tensorflow). Step2: Let's view some of the images to get an idea ...
Python Code: !curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import conda_installer conda_installer.install() !/root/miniconda/bin/conda info -e !pip install --pre deepchem import deepchem deepchem.__version__ Explanation: Tutorial Part 15: Training a Gen...
9,018
Given the following text description, write Python code to implement the functionality described below step by step Description: First Python Notebook Step1: There. You've just written your first Python code. You've entered two integers (the 2's) and added them together using the plus sign operator. Not so bad, right...
Python Code: 2+2 Explanation: First Python Notebook: Scripting your way to the story By Ben Welsh A step-by-step guide to analyzing data with Python and the Jupyter Notebook. This tutorial will teach you how to use computer programming tools to analyze data by exploring contributors to campaigns for and again Propositi...
9,019
Given the following text description, write Python code to implement the functionality described below step by step Description: This tutorial takes you through the basics of analysing Mitty data with some help from cytoolz and pandas Step1: Ex1 Step2: Ex2 Step3: Ex3 Step4: Ex2 More involved example showing, in se...
Python Code: %load_ext autoreload %autoreload 2 import time import matplotlib.pyplot as plt import cytoolz.curried as cyt from bokeh.plotting import figure, show, output_file import mitty.analysis.bamtoolz as bamtoolz import mitty.analysis.bamfilters as mab import mitty.analysis.plots as mapl # import logging # FORMAT ...
9,020
Given the following text description, write Python code to implement the functionality described below step by step Description: Toy weather data Here is an example of how to easily manipulate a toy weather dataset using xarray and other recommended Python libraries Step1: Examine a dataset with pandas and seaborn Co...
Python Code: import numpy as np import pandas as pd import seaborn as sns import xarray as xr np.random.seed(123) xr.set_options(display_style="html") times = pd.date_range("2000-01-01", "2001-12-31", name="time") annual_cycle = np.sin(2 * np.pi * (times.dayofyear.values / 365.25 - 0.28)) base = 10 + 15 * annual_cycle....
9,021
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started with the Gluon Interface In this example from the Github repository we will build and train a simple two-layer artificial neural network (ANN) called a multilayer perceptron....
Python Code: import mxnet as mx from mxnet import gluon, autograd, ndarray import numpy as np Explanation: Getting Started with the Gluon Interface In this example from the Github repository we will build and train a simple two-layer artificial neural network (ANN) called a multilayer perceptron. First, we need to impo...
9,022
Given the following text description, write Python code to implement the functionality described below step by step Description: Create Schema Using the # operator you can execute sql statements as a script Note Step1: Insert some data Let's insert a single user into the database using the ! operator Step2: Or inser...
Python Code: help(queries.create_schema) queries.create_schema(conn) Explanation: Create Schema Using the # operator you can execute sql statements as a script Note: Variable substitution is not possible End of explanation queries.add_user(conn, **{"username": "badger77", "firstname": "Mike", "lastname": "Jones"}) Expl...
9,023
Given the following text description, write Python code to implement the functionality described below step by step Description: Probability distributions - 1 ToC - Axioms of probability - Conditional probability - Bayesian conditional probability - Random variables - Properties of discrete random variables ...
Python Code: import matplotlib.pyplot as plt %matplotlib inline from matplotlib_venn import venn2 venn2(subsets = (0.45, 0.15, 0.05), set_labels = ('A', 'B')) Explanation: Probability distributions - 1 ToC - Axioms of probability - Conditional probability - Bayesian conditional probability - Random variables -...
9,024
Given the following text description, write Python code to implement the functionality described below step by step Description: Construct a 5x3 matrix, uninitialized Step1: Construct a randomly initialized matrix Step2: Construct a matrix filled zeros and of dtype long Step3: Construct a tensor directly from data ...
Python Code: x = torch.empty(5,3) print(x) Explanation: Construct a 5x3 matrix, uninitialized: End of explanation x = torch.rand(5,3) print(x) Explanation: Construct a randomly initialized matrix: End of explanation x = torch.zeros(5,3,dtype=torch.long) print(x) Explanation: Construct a matrix filled zeros and of dtype...
9,025
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
9,026
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing tutor-student matching with rate-based simulations Step1: Define target motor programs Step2: Choose target Step12: General definitions Here we define some classes and functions t...
Python Code: %matplotlib inline import matplotlib as mpl import matplotlib.ticker as mtick import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') plt.rc('text', usetex=True) plt.rc('font', family='serif', serif='cm') plt.rcParams['figure.titlesize'] = 10 plt.rcParams['axes.labelsize'] = 8 plt.rcPa...
9,027
Given the following text description, write Python code to implement the functionality described below step by step Description: RNNs tutorial Step1: An LSTM/RNN overview Step2: Note that when we create the builder, it adds the internal RNN parameters to the ParameterCollection. We do not need to care about them, bu...
Python Code: # we assume that we have the dynet module in your path. import dynet as dy Explanation: RNNs tutorial End of explanation pc = dy.ParameterCollection() NUM_LAYERS=2 INPUT_DIM=50 HIDDEN_DIM=10 builder = dy.LSTMBuilder(NUM_LAYERS, INPUT_DIM, HIDDEN_DIM, pc) # or: # builder = dy.SimpleRNNBuilder(NUM_LAYERS, IN...
9,028
Given the following text description, write Python code to implement the functionality described below step by step Description: Hands-on! Nessa prática, sugerimos alguns pequenos exemplos para você implementar sobre o Spark. Apriorando o Word Count Memória Postumas de Brás Cubas Memórias Póstumas de Brás Cubas é um r...
Python Code: # Bibliotecas from pyspark.ml import Pipeline from pyspark.ml.feature import Tokenizer, StopWordsRemover, CountVectorizer, NGram livro = sc.textFile("Machado-de-Assis-Memorias-Postumas.txt") text = "" for line in livro.collect(): text += " " + line data = spark.createDataFrame([(0, text)], ["id", "text...
9,029
Given the following text description, write Python code to implement the functionality described below step by step Description: Ne pas faire un "execute all" Step1: Exercice Step2: TensorFlow (II) La même chose mais une session interactive, ce qui nous permet d'être un peu plus lâche dans l'ordre d'opérations. St...
Python Code: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) Explanation: Ne pas faire un "execute all" : la dernière cellule est très lourde. Introduction à TensorFlow Ce code est basé sur des tutoriel à tensorflow.org. Nous allons utiliser _so...
9,030
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 4 Imports Step2: Line with Gaussian noise Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 4 Imports End of explanation def random_line(m, b, sigma, size=10): Create a line y = m*x + b + N(0,sigm...
9,031
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizing optimization results Tim Head, August 2016. Reformatted by Holger Nahrstaedt 2020 .. currentmodule Step1: Toy models We will use two different toy models to demonstrate how Ste...
Python Code: print(__doc__) import numpy as np np.random.seed(123) import matplotlib.pyplot as plt Explanation: Visualizing optimization results Tim Head, August 2016. Reformatted by Holger Nahrstaedt 2020 .. currentmodule:: skopt Bayesian optimization or sequential model-based optimization uses a surrogate model to mo...
9,032
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-esm2-sr5', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-ESM2-SR5 Topic: Seaice Sub-Topics: Dynamics, Therm...
9,033
Given the following text description, write Python code to implement the functionality described below step by step Description: This is the demonstration how to use NEDO data process utility Step1: Load the data into a NEDOLocation object Step2: main_df adds the column names into the raw data and convert it to a pa...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import os from pypvcell.solarcell import SQCell,MJCell,TransparentCell from pypvcell.illumination import Illumination from pypvcell.spectrum import Spectrum from pypvcell.metpv_reade...
9,034
Given the following text description, write Python code to implement the functionality described below step by step Description: 문자열을 인쇄하는 다양한 방법 활용 파이썬 2.x에서는 print 함수의 경우 인자들이 굳이 괄호 안에 들어 있어야 할 필요는 없다. 또한 여러 개의 값을 동시에 인쇄할 수도 있다. 이때 인자들은 콤마로 구분지어진다. Step1: 주의 Step2: 하지만 위와 같이 괄호를 사용하지 않는 방식은 파이썬 3.x에서는 지원되지 않는다. 따라...
Python Code: a = "string" b = "string1" print a, b print "The return value is", a Explanation: 문자열을 인쇄하는 다양한 방법 활용 파이썬 2.x에서는 print 함수의 경우 인자들이 굳이 괄호 안에 들어 있어야 할 필요는 없다. 또한 여러 개의 값을 동시에 인쇄할 수도 있다. 이때 인자들은 콤마로 구분지어진다. End of explanation print(a, b) print("The return value is", a) Explanation: 주의: 아래와 같이 하면 모양이 기대와 다르게 나...
9,035
Given the following text description, write Python code to implement the functionality described below step by step Description: <br> Weighted kernel density estimation to quickly reproduce the profile of a diffractometer <br> <br> This example shows a work-arround for a quick visualization of a diffractorgram (simila...
Python Code: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from ImageD11.columnfile import columnfile from ImageD11 import weighted_kde as wkde %matplotlib inline plt.rcParams['figure.figsize'] = (6,4) plt.rcParams['figure.dpi'] = 150 plt.rcParams['mathtext.fontset'] = 'cm' plt.rcParams['f...
9,036
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to the jupyter notebook! To run any cell, press Shit+Enter or Ctrl+Enter. IMPORTANT Step1: Notebook Basics A cell contains any type of python inputs (expression, function definitio...
Python Code: # Useful starting lines %matplotlib inline import numpy as np import matplotlib.pyplot as plt %load_ext autoreload %autoreload 2 Explanation: Welcome to the jupyter notebook! To run any cell, press Shit+Enter or Ctrl+Enter. IMPORTANT : Please have a look at Help-&gt;User Interface Tour and Help-&gt;Keyboar...
9,037
Given the following text description, write Python code to implement the functionality described below step by step Description: Customer migration from Prestashop to Woocommerce part 1 Step1: Loading the data from Prestashop backend and sql. Note that Prestashop backend can generate some table for you by a default ...
Python Code: import pandas as pd import numpy as np import csv Explanation: Customer migration from Prestashop to Woocommerce part 1 : Gathering raw customer information from Prestashop This is the product migration of the book store from Prestashop to Woocommerce format. Unlike the product, users (customers in Woocomm...
9,038
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'miroc', 'miroc-es2h', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MIROC Source ID: MIROC-ES2H Topic: Aerosol Sub-Topics: Transport, Emiss...
9,039
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook 2 Our current dataset suffers from duplicate tweet's from bots, hacked accounts etc. As such, this notebook will show you how to deal with these duplicates in a manner that does not...
Python Code: import pandas as pd import arrow # way better than datetime import numpy as np import random import re %run helper_functions.py import string new_df = unpickle_object("new_df.pkl") # this loads up the dataframe from our previous notebook new_df.head() #sorted first on date and then time! new_df.iloc[0, 3] ...
9,040
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning to Resize in Computer Vision Author Step1: Define hyperparameters In order to facilitate mini-batch learning, we need to have a fixed shape for the images inside a given batch. Thi...
Python Code: from tensorflow.keras import layers from tensorflow import keras import tensorflow as tf import tensorflow_datasets as tfds tfds.disable_progress_bar() import matplotlib.pyplot as plt import numpy as np Explanation: Learning to Resize in Computer Vision Author: Sayak Paul<br> Date created: 2021/04/30<br> L...
9,041
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: ユニバーサルセンテンスエンコーダー Lite の実演 <table class="tfo-notebook-buttons" align="left"...
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-2.0 # # Unless re...
9,042
Given the following text description, write Python code to implement the functionality described below step by step Description: Delayed Extra Sources in NuPyCEE Created by Benoit Côté This notebook introduces the general delayed-extra set of parameters in NuPyCEE that allows to include any enrichment source that requ...
Python Code: import matplotlib import matplotlib.pyplot as plt import numpy as np from NuPyCEE import sygma Explanation: Delayed Extra Sources in NuPyCEE Created by Benoit Côté This notebook introduces the general delayed-extra set of parameters in NuPyCEE that allows to include any enrichment source that requires a de...
9,043
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction $\newcommand{\G}{\mathcal{G}}$ $\newcommand{\V}{\mathcal{V}}$ $\newcommand{\E}{\mathcal{E}}$ $\newcommand{\R}{\mathbb{R}}$ This notebook shows how to apply our graph ConvNet (pa...
Python Code: from lib import models, graph, coarsening, utils import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Introduction $\newcommand{\G}{\mathcal{G}}$ $\newcommand{\V}{\mathcal{V}}$ $\newcommand{\E}{\mathcal{E}}$ $\newcommand{\R}{\mathbb{R}}$ This notebook shows how to apply our gr...
9,044
Given the following text description, write Python code to implement the functionality described below step by step Description: Time and coordinates Step1: We are going to use astropy to find out whether the Large Magellanic Cloud (LMC) is visible from the a given observatory at a given time and date. In the proces...
Python Code: import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Time and coordinates End of explanation import astropy.units as u from astropy.time import Time from astropy.coordinates import SkyCoord, EarthLocation, AltAz Explanation: We are goi...
9,045
Given the following text description, write Python code to implement the functionality described below step by step Description: LDA预处理 方案 1 将每张订单作为一个document 方案2 将每个用户作为一个document 将每个product作为一个Document 将每个aisle作为一个Document 将每个department作为Document 方案3 product name 无结构文本 <font color=red>方案2 part 1</font> Step1: <font...
Python Code: #方案2 orders = tle.get_orders() users_orders = tle.get_users_orders('prior') # 将product_id转换为str users_products_matrix = users_orders.groupby(['user_id'])['product_id'].apply(utils.series_to_str) # 构造vocabulary tf = CountVectorizer(analyzer = 'word', lowercase = False, max_df=0.95, min_df=2,) tf_matrix = tf...
9,046
Given the following text description, write Python code to implement the functionality described below step by step Description: Temporal whitening with AR model Here we fit an AR model to the data and use it to temporally whiten the signals. Step1: Plot the different time series and PSDs
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import numpy as np from scipy import signal import matplotlib.pyplot as plt import mne from mne.time_frequency import fit_iir_model_raw from mne.datasets import sample print(__doc__) data_path = sample.data_path() raw_fna...
9,047
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-3', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-3 Topic: Land Sub-Topics: Soil, Snow, Vegetat...
9,048
Given the following text description, write Python code to implement the functionality described below step by step Description: Aufgabe 2 Step1: First we create a training set of size num_samples and num_features. Step2: Next we run a performance test on the created data set. Therefor we train a random forest class...
Python Code: # imports from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier import time import matplotlib.pyplot as plt import seaborn as sns Explanation: Aufgabe 2: Classification A short test to examine the performance gain when using multiple cores on sklearn's esemble...
9,049
Given the following text description, write Python code to implement the functionality described below step by step Description: Text classification from scratch Authors Step1: Load the data Step2: The aclImdb folder contains a train and test subfolder Step3: The aclImdb/train/pos and aclImdb/train/neg folders cont...
Python Code: import tensorflow as tf import numpy as np Explanation: Text classification from scratch Authors: Mark Omernick, Francois Chollet<br> Date created: 2019/11/06<br> Last modified: 2020/05/17<br> Description: Text sentiment classification starting from raw text files. Introduction This example shows how to do...
9,050
Given the following text description, write Python code to implement the functionality described below step by step Description: Once we've trained a model, we might want to better understand what sequence motifs the first convolutional layer has discovered and how it's using them. Basset offers two methods to help us...
Python Code: model_file = '../data/models/pretrained_model.th' seqs_file = '../data/encode_roadmap.h5' Explanation: Once we've trained a model, we might want to better understand what sequence motifs the first convolutional layer has discovered and how it's using them. Basset offers two methods to help users explore th...
9,051
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-2', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: SANDBOX-2 Topic: Atmosc...
9,052
Given the following text description, write Python code to implement the functionality described below step by step Description: 编码分类特征 在机器学习中,特征经常不是数值型的而是枚举型的.举个例子,一个人可能有 ["male", "female"],["from Europe", "from US", "from Asia"],["uses Firefox", "uses Chrome", "uses Safari", "uses Internet Explorer"]等枚举类型的特征.这些特征能够被...
Python Code: from sklearn import preprocessing enc = preprocessing.OneHotEncoder() enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]]) enc.transform([[0, 1, 3]]).toarray() Explanation: 编码分类特征 在机器学习中,特征经常不是数值型的而是枚举型的.举个例子,一个人可能有 ["male", "female"],["from Europe", "from US", "from Asia"],["uses Firefox", "uses Chrome...
9,053
Given the following text description, write Python code to implement the functionality described below step by step Description: Bean Stalk Series Step1: Now lets import the tetravolume.py module, which in turn has dependencies, to get these volumes directly, based on edge lengths. I'll use the edges given in Fig. 9...
Python Code: import gmpy2 from gmpy2 import sqrt as rt2 from gmpy2 import mpfr gmpy2.get_context().precision=200 root2 = rt2(mpfr(2)) root3 = rt2(mpfr(3)) root5 = rt2(mpfr(5)) ø = (root5 + 1)/2 ø_down = ø ** -1 ø_up = ø E_vol = (15 * root2 * ø_down ** 3)/120 # a little more than 1/24, volume of T module print(E_vol) Ex...
9,054
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <figure> <IMG SRC="../../logo/logo.png" WIDTH=250 ALIGN="right"> </figure> IHE Python course, 2017 CHIRPS data for precipitation (worldwide between 50S and 50N latitude) Never again...
Python Code: import numpy as np from pprint import pprint def prar(A, ncol=8, maxsize=1000): prints 2D arrays the Matlab 2 (more readable) if A.size>1000: # don't try to print a million values, or your pc will hang. print(A) return n = A.shape[1] # print columns in formatted chu...
9,055
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples and Exercises from Think Stats, 2nd Edition http Step1: Survival analysis If we have an unbiased sample of complete lifetimes, we can compute the survival function from the CDF and...
Python Code: from __future__ import print_function, division %matplotlib inline import warnings warnings.filterwarnings('ignore', category=FutureWarning) import numpy as np import pandas as pd import random import thinkstats2 import thinkplot Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thin...
9,056
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook we'll look at interfacing between the composability and ability to generate complex visualizations that HoloViews provides, the power of pandas library dataframes for manipu...
Python Code: import itertools import numpy as np import pandas as pd import seaborn as sb import holoviews as hv np.random.seed(9221999) Explanation: In this notebook we'll look at interfacing between the composability and ability to generate complex visualizations that HoloViews provides, the power of pandas library d...
9,057
Given the following text description, write Python code to implement the functionality described below step by step Description: For high dpi displays. Step1: 0. General note This example compares pressure calculated from pytheos and original publication for the gold scale by Dorogokupets 2015. 1. Global setup Step2:...
Python Code: %config InlineBackend.figure_format = 'retina' Explanation: For high dpi displays. End of explanation import matplotlib.pyplot as plt import numpy as np from uncertainties import unumpy as unp import pytheos as eos Explanation: 0. General note This example compares pressure calculated from pytheos and orig...
9,058
Given the following text description, write Python code to implement the functionality described below step by step Description: Code Testing and CI Version 0.1 The notebook contains problems about code testing and continuous integration. E Tollerud (STScI) Problem 1 Step1: 1b Step2: 1d Step3: 1e Step4: 1f Step5: ...
Python Code: !conda install pytest pytest-cov Explanation: Code Testing and CI Version 0.1 The notebook contains problems about code testing and continuous integration. E Tollerud (STScI) Problem 1: Set up py.test in you repo In this problem we'll aim to get the py.test testing framework up and running in the code repo...
9,059
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute ICA on MEG data and remove artifacts ICA is fit to MEG raw data. The sources matching the ECG and EOG are automatically found and displayed. Subsequently, artifact detection and reje...
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import mne from mne.preprocessing import ICA from mne.preprocessing import create_ecg_epochs, create_eog_epochs from mne.datasets impor...
9,060
Given the following text description, write Python code to implement the functionality described below step by step Description: Classifying Default of Credit Card Clients <hr> The dataset can be downloaded from Step1: Feature importances with forests of trees This examples shows the use of forests of trees to evalu...
Python Code: import os from sklearn.tree import DecisionTreeClassifier, export_graphviz import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split from sklearn import cross_validation, metrics from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import Bernoulli...
9,061
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Quiz 1 - Number of rainy days Step3: count(*) 0 10 Quiz 2 - Temp on Foggy and Nonfoggy Days Step5: fog max(maxtempi) 0 0 86 1 1 81 Quiz 3 - Mea...
Python Code: import pandas import pandasql def num_rainy_days(filename): ''' This function should run a SQL query on a dataframe of weather data. The SQL query should return: - one column and - one row - a count of the `number of days` in the dataframe where the rain column is equal to 1 (i...
9,062
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a csv file which looks like
Problem: from sklearn.cluster import KMeans df = load_data() kmeans = KMeans(n_clusters=2) labels = kmeans.fit_predict(df[['mse']])
9,063
Given the following text description, write Python code to implement the functionality described below step by step Description: Load and pre-process data Step1: Impute PE First, I will impute PE by replacing missing values with the mean PE. Second, I will impute PE using a random forest regressor. I will compare the...
Python Code: from sklearn import preprocessing filename = '../facies_vectors.csv' train = pd.read_csv(filename) # encode well name and formation features le = preprocessing.LabelEncoder() train["Well Name"] = le.fit_transform(train["Well Name"]) train["Formation"] = le.fit_transform(train["Formation"]) data_loaded = tr...
9,064
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 5 The goal of this assignment is to train a Word2Vec skip-gram model over Text8 data. Step2: Download the data from the source website if necessary. Step4: Read th...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. %matplotlib inline from __future__ import print_function import collections import math import numpy as np import os import random import tensorflow as tf import zipfile from matplotlib import pylab...
9,065
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic plot example Step1: $$c = \sqrt{a^2 + b^2}$$ $$ \begin{align} c =& \sqrt{a^2 + b^2} \ =&\sqrt{4+16} \ \end{align} $$ $$ \begin{align} f(x)= & x^2 \ = & {{x[1]}} \end{align} $$ This t...
Python Code: from matplotlib.pyplot import figure, plot, xlabel, ylabel, title, show x=linspace(0,5,10) y=x**2 figure() plot(x,y,'r') xlabel('x') ylabel('y') title('title') show() Explanation: Basic plot example End of explanation from IPython.display import display text = widgets.FloatText() floatText = widgets.FloatT...
9,066
Given the following text description, write Python code to implement the functionality described below step by step Description: Data wrangling Who we are Jackie Kazil (@JackieKazil), author of the O'Reilly book Data Wrangling with Python Abe Epton (@aepton) What we'll cover Loading data Transforming it Storing it How...
Python Code: import agate table = agate.Table.from_csv('data/contracts_data.csv') print table Explanation: Data wrangling Who we are Jackie Kazil (@JackieKazil), author of the O'Reilly book Data Wrangling with Python Abe Epton (@aepton) What we'll cover Loading data Transforming it Storing it How we'll do it We'll be w...
9,067
Given the following text description, write Python code to implement the functionality described below step by step Description: Hands-On Exercise 2 Step1: There is a lot of information for each source, and the overall image, in each of these catalog files. As a demonstration of the parameters available for each sour...
Python Code: reference_catalog = '../data/PTF_Refims_Files/PTF_d022683_f02_c06_u000114210_p12_sexcat.ctlg' # select R-band data (f02) Explanation: Hands-On Exercise 2: Making a Lightcurve from PTF catalog data Version 0.2 This "hands-on" session will proceed differently from those that are going to follow. Below, we ha...
9,068
Given the following text description, write Python code to implement the functionality described below step by step Description: Functions Making reusable blocks of code. Starting point Step1: What about for $a = 2$, $b = 8$, and $c = 1$? Step3: Functions Step5: Observe how this function works. Step7: Summarize St...
Python Code: ## Code here Explanation: Functions Making reusable blocks of code. Starting point: In this exercise, we're going to calculate one of the roots from the quadratic formula: $r_{p} = \frac{-b + \sqrt{b^{2} - 4ac}}{2a}$ Determine $r_{p}$ for $a = 1$, $b=4$, and $c=3$. End of explanation ## Code here Explanat...
9,069
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculate performance of kWIP The next bit of python code calculates the performance of kWIP against the distance between samples calulcated from the alignments of their genomes. This code c...
Python Code: expts = list(map(lambda fp: path.basename(fp.rstrip('/')), glob('data/*/'))) print("Number of replicate experiments:", len(expts)) def process_expt(expt): expt_results = [] def extract_info(filename): return re.search(r'kwip/(\d\.?\d*)x-(0\.\d+)-(wip|ip).dist', filename).groups() ...
9,070
Given the following text description, write Python code to implement the functionality described below step by step Description: Transfer function of a position sensor. Andrés Marrugo, PhD Universidad Tecnológica de Bolívar. The transfer function of a small position sensor is evaluated experimentally. The sensor is...
Python Code: import matplotlib.pyplot as plt import numpy as np %matplotlib inline d = np.array([0,0.08,0.16,0.24,0.32,0.4,0.48,0.52]) f = np.array([0,0.576,1.147,1.677,2.187,2.648,3.089,3.295]) plt.plot(f,d,'*') plt.ylabel('Displacement [mm]') plt.xlabel('Force [mN]') plt.show() Explanation: Transfer function of a pos...
9,071
Given the following text description, write Python code to implement the functionality described below step by step Description: Módulo 2 Step9: Construção Series Step20: DataFrame Step21: Acessando valores Definição das Variáveis Step22: Slicing Series Step30: DataFrame Step33: * Atribuição de Valores em DataFr...
Python Code: import numpy as np import pandas as pd Explanation: Módulo 2: Introdução à Lib Pandas Tutorial Imports para a Aula End of explanation Construtor padrão pd.Series( name="Compras", index=["Leite", "Ovos", "Carne", "Arroz", "Feijão"], data=[2, 12, 1, 5, 2] ) Construtor padrão: dados desconhec...
9,072
Given the following text description, write Python code to implement the functionality described below step by step Description: AST 337 In-Class Lab #1 Wednesday, September 6, 2017 In this lab, you'll learn to read in and manipulate tabular data with the python package pandas and plot that data with the plotting modu...
Python Code: #load packages import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: AST 337 In-Class Lab #1 Wednesday, September 6, 2017 In this lab, you'll learn to read in and manipulate tabular data with the python package pandas and plot that data with the plotting mo...
9,073
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: NumPy API on TensorFlow <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Enabling NumPy beha...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
9,074
Given the following text description, write Python code to implement the functionality described below step by step Description: I started here Step2: cf. 3.2 Datasets, 3.2.1 MNIST Dataset Step3: GPU note Using the GPU THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python myscriptIwanttorunonthegpu.py From the...
Python Code: import theano import theano.tensor as T # cf. https://github.com/lisa-lab/DeepLearningTutorials/blob/c4db2098e6620a0ac393f291ec4dc524375e96fd/code/logistic_sgd.py Explanation: I started here: Deep Learning tutorial End of explanation import cPickle, gzip, numpy import os os.getcwd() os.listdir( os.getcwd(...
9,075
Given the following text description, write Python code to implement the functionality described below step by step 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 are similar in meaning are also close in...
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 vectorspace. Getting ...
9,076
Given the following text description, write Python code to implement the functionality described below step by step Description: Building your Deep Neural Network Step2: 2 - Outline of the Assignment To build your neural network, you will be implementing several "helper functions". These helper functions will be used...
Python Code: import numpy as np import h5py import matplotlib.pyplot as plt from testCases_v3 import * from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rc...
9,077
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Exercise 1 Step2: b. Spearman Rank Correlation Find the Spearman rank correlation coefficient for the relationship between x and y using the stats.rankdata function and th...
Python Code: import numpy as np import pandas as pd import scipy.stats as stats import matplotlib.pyplot as plt import math Explanation: Exercises: Spearman Rank Correlation Lecture Link This exercise notebook refers to this lecture. Please use the lecture for explanations and sample code. https://www.quantopian.com/le...
9,078
Given the following text description, write Python code to implement the functionality described below step by step Description: 5. Impulse response functions Impulse response functions (IRFs) are a standard tool for analyzing the short run dynamics of dynamic macroeconomic models, such as the Solow growth model, in r...
Python Code: # use tab completion to see the available attributes and methods... solowpy.impulse_response.ImpulseResponse. Explanation: 5. Impulse response functions Impulse response functions (IRFs) are a standard tool for analyzing the short run dynamics of dynamic macroeconomic models, such as the Solow growth model...
9,079
Given the following text description, write Python code to implement the functionality described below step by step Description: Applied example of scraping the Handbook of Birds of the World to get a list of subspecies for a given bird species. Step1: Introspection of the source HTML of the species web page reveals ...
Python Code: #Import modules import requests from bs4 import BeautifulSoup #Example URL theURL = "https://www.hbw.com/species/brown-wood-owl-strix-leptogrammica" #Get content of the species web page response = requests.get(theURL) #Convert to a "soup" object, which BS4 is designed to work with soup = BeautifulSoup(resp...
9,080
Given the following text description, write Python code to implement the functionality described below step by step Description: Cadenas o strings En Python las cadenas son definidas como listas de caracteres, por lo que es posible aplicarles rebanado y las demás operaciones que vimos en la sección anterior. Una caden...
Python Code: fruta = "banano" dulce = 'bocadillo' Explanation: Cadenas o strings En Python las cadenas son definidas como listas de caracteres, por lo que es posible aplicarles rebanado y las demás operaciones que vimos en la sección anterior. Una cadena se puede formar usando comillas dobles o sencillas, de la siguien...
9,081
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize channel over epochs as an image This will produce what is sometimes called an event related potential / field (ERP/ERF) image. Two images are produced, one with a good channel and ...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import numpy as np import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample print(__doc__) data_path = sample.data_path() Explanation: Visualize channel over epochs as an image This wi...
9,082
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 2 Step1: If you get an error stating that database "homework2" does not exist, make sure that you followed the instructions above exactly. If necessary, drop the database you creat...
Python Code: import pg8000 conn = pg8000.connect(database="homework2") Explanation: Homework 2: Working with SQL (Data and Databases 2016) This homework assignment takes the form of an IPython Notebook. There are a number of exercises below, with notebook cells that need to be completed in order to meet particular crit...
9,083
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis_v3 requires Step1: Create processing pipeline <br> <br> Requires Step2: SweepPoints Step3: Measured-objects-sweep-points map Step4: Ramsey single qubit Step5: Create pipeline S...
Python Code: from pycqed.analysis_v3.processing_pipeline import ProcessingPipeline # [ # {'node_name1': function_name1, keys_in: keys_in_list1, **node_params1}, # {'node_name2': function_name2, keys_in: keys_in_list2, **node_params2}, # . # . # . # {'node_nameN': function_nameN, keys_in: keys_in...
9,084
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Tutorial Eine minimale Einführung in Python für Studierende mit Programmiererfahrung die keinen Anspruch auf Vollständigkeit erhebt. Ausführlichere Einführungen und Tutorials finden s...
Python Code: print('Hello, world!') Explanation: Python Tutorial Eine minimale Einführung in Python für Studierende mit Programmiererfahrung die keinen Anspruch auf Vollständigkeit erhebt. Ausführlichere Einführungen und Tutorials finden sich an zahlreichen Stellen im Internet. Beispielsweise Learn Python the Hard Way ...
9,085
Given the following text description, write Python code to implement the functionality described. Description: Maximize sum of absolute difference between adjacent elements in Array with sum K Function for maximising the sum ; Difference is 0 when only one element is present in array ; Difference is K when two elements...
Python Code: def maxAdjacentDifference(N , K ) : if(N == 1 ) : return 0 ;  if(N == 2 ) : return K ;  return 2 * K ;  N = 6 ; K = 11 ; print(maxAdjacentDifference(N , K ) ) ;
9,086
Given the following text description, write Python code to implement the functionality described below step by step Description: Converting incoming CDX files to Parquet Quick look at file sizes Step1: Note Step2: Load in the unzipped file, filetering out any line that starts with a blank or has essentially no conte...
Python Code: !ls -lh eot2012_surt_index.cdx* Explanation: Converting incoming CDX files to Parquet Quick look at file sizes: End of explanation !gunzip eot2012_surt_index.cdx.gz Explanation: Note: Spark can typically load *.gz files just fine, but that support comes from Hive integration, which seems to be missing here...
9,087
Given the following text description, write Python code to implement the functionality described below step by step Description: Guide To Encoding Categorical Values in Python Supporting notebook for article on Practical Business Python. Import the pandas, scikit-learn, numpy and category_encoder libraries. Step1: Ne...
Python Code: import pandas as pd import numpy as np from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder from sklearn.compose import make_column_transformer from sklearn.linear_model import LinearRegression from sklearn.pipeline import make_pipeline from sklearn.model_selection import cross_val_score import ...
9,088
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: What is the equivalent of R's ecdf(x)(x) function in Python, in either numpy or scipy? Is ecdf(x)(x) basically the same as:
Problem: import numpy as np grades = np.array((93.5,93,60.8,94.5,82,87.5,91.5,99.5,86,93.5,92.5,78,76,69,94.5, 89.5,92.8,78,65.5,98,98.5,92.3,95.5,76,91,95,61)) def ecdf_result(x): xs = np.sort(x) ys = np.arange(1, len(xs)+1)/float(len(xs)) return ys result = ecdf_result(grades)
9,089
Given the following text description, write Python code to implement the functionality described below step by step Description: Iterators and Generators Homework Problem 1 Create a generator that generates the squares of numbers up to some number N. Step1: Problem 2 Create a generator that yields "n" random numbers ...
Python Code: def gensquares(N): for i in range(N): yield i**2 for x in gensquares(10): print x Explanation: Iterators and Generators Homework Problem 1 Create a generator that generates the squares of numbers up to some number N. End of explanation import random random.randint(1,10) def rand_num(low,hi...
9,090
Given the following text description, write Python code to implement the functionality described below step by step Description: Ritz method for a beam November, 2018 We want to find a Ritz approximation of the deflection $w$ of a beam under applied transverse uniform load of intensity $f$ per unit lenght and an end m...
Python Code: import numpy as np import matplotlib.pyplot as plt from sympy import * %matplotlib notebook init_printing() # Graphics setup gray = '#757575' plt.rcParams["mathtext.fontset"] = "cm" plt.rcParams["text.color"] = gray plt.rcParams["font.size"] = 12 plt.rcParams["xtick.color"] = gray plt.rcParams["ytick.color...
9,091
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 4 – Training Linear Models This notebook contains all the sample code and solutions to the exercises in chapter 4. Setup First, let's make sure this notebook works well in both pytho...
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 np.random.seed(42) # To plot pretty figures %matplotlib inline import matplotlib import matplotlib.pypl...
9,092
Given the following text description, write Python code to implement the functionality described below step by step Description: Autoencoder + UMAP This notebook extends the last notebook to train the embedding jointly on the reconstruction loss, and UMAP loss, resulting in slightly better reconstructions, and a sligh...
Python Code: from tensorflow.keras.datasets import mnist (train_images, Y_train), (test_images, Y_test) = mnist.load_data() train_images = train_images.reshape((train_images.shape[0], -1))/255. test_images = test_images.reshape((test_images.shape[0], -1))/255. Explanation: Autoencoder + UMAP This notebook extends the l...
9,093
Given the following text description, write Python code to implement the functionality described below step by step Description: Image embeddings in BigQuery for image similarity and clustering tasks This notebook shows how to do use a pre-trained embedding as a vector representation of an image in Google Cloud Storag...
Python Code: BUCKET='ai-analytics-solutions-kfpdemo' # CHANGE to a bucket you own Explanation: Image embeddings in BigQuery for image similarity and clustering tasks This notebook shows how to do use a pre-trained embedding as a vector representation of an image in Google Cloud Storage. Given this embedding, we can lo...
9,094
Given the following text description, write Python code to implement the functionality described below step by step Description: Forte Tutorial 1.02 Step2: First we will run psi4 using the function forte.utils.psi4_scf Step3: Reading options Step4: Setting the molecular orbital spaces Step5: Building a ForteIntegr...
Python Code: import psi4 import forte import forte.utils Explanation: Forte Tutorial 1.02: Forte's determinant class In this tutorial we are going to explore how to create a simple FCI code using forte's Python API. Import modules Here we import forte.utils bto access functions to directly run an SCF computation in psi...
9,095
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducing the Keras Sequential API Learning Objectives 1. Build a DNN model using the Keras Sequential API 1. Learn how to use feature columns in a Keras model 1. Learn how to train ...
Python Code: import datetime import os import shutil import numpy as np import pandas as pd import tensorflow as tf from matplotlib import pyplot as plt from tensorflow import keras from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers import Dense, DenseFeatures from tensorflow.keras.models i...
9,096
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Machine Learning using tf.estimator </h1> In this notebook, we will create a machine learning model using tf.estimator and evaluate its performance. The dataset is rather small (7700 s...
Python Code: # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.6 import tensorflow as tf import pandas as pd import numpy as np import shutil print(tf.__version__) Explanation: <h1> Machine Learning using tf.estimator </h1> In this notebook, we will create a machine learning model ...
9,097
Given the following text description, write Python code to implement the functionality described below step by step Description: Test datasets http Step1: General guides to Bayesian regression http
Python Code: import pandas as pd import statsmodels.api as sm # Normal response variable stackloss_conversion = sm.datasets.get_rdataset("stackloss", "datasets") #print (stackloss_conversion.__doc__) # Lognormal response variable engel_food = sm.datasets.engel.load_pandas() #print (engel_food.data) # Binary response va...
9,098
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a Regression Model for a Financial Dataset In this notebook, you will build a simple linear regression model to predict the closing AAPL stock price. The lab objectives are Step1: ...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip install --user google-cloud-bigquery==1.25.0 Explanation: Building a Regression Model for a Financial Dataset In this notebook, you will build a simple linear regression model to predict the closing AAPL stock price. The lab objectives...
9,099
Given the following text description, write Python code to implement the functionality described below step by step Description: Dense Sentiment Classifier In this notebook, we build a dense neural net to classify IMDB movie reviews by their sentiment. Load dependencies Step1: Set hyperparameters Step2: Load data Fo...
Python Code: import keras from keras.datasets import imdb from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Dense, Flatten, Dropout from keras.layers import Embedding # new! from keras.callbacks import ModelCheckpoint # new! import os # new! from sklea...