Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
5,900 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this example, we will assume that the stimuli are patches of different motion directions. These stimuli span a 360-degree, circular feature space. We will build an encoding model that has... | Python Code:
# Set up parameters
n_channels = 6
cos_exponent = 5
range_start = 0
range_stop = 360
feature_resolution = 360
iem_obj = IEM.InvertedEncoding1D(n_channels, cos_exponent, stimulus_mode='circular', range_start=range_start,
range_stop=range_stop, channel_density=feature_resoluti... |
5,901 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 线程与协程(1)
要说到线程(Thread)与协程(Coroutine)似乎总是需要从并行(Parallelism)与并发(Concurrency)谈起,关于并行与并发的问题,Rob Pike 用 Golang 小地鼠烧书的例子给出了非常生动形象的说明。简单来说并行就是我们现实世界运行的样子,每个人都是独立的执行单元,各自完成自己的任务,这对应着计算机中的分布式(... | Python Code:
from threading import Thread
import time
def _sum(x, y):
print("Compute {} + {}...".format(x, y))
time.sleep(2.0)
return x+y
def compute_sum(x, y):
result = _sum(x, y)
print("{} + {} = {}".format(x, y, result))
start = time.time()
threads = [
Thread(target=compute_sum, args=(0,0... |
5,902 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grid Searches
<img src="figures/grid_search_cross_validation.svg" width=100%>
Grid-Search with build-in cross validation
Step1: Define parameter grid
Step2: A GridSearchCV object behaves j... | Python Code:
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVC
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data,
... |
5,903 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Redoing Weka Stuff
In this section we will try to redo some of the things we have already done in Weka.
Objective
Step1: Feature creations - Math Expressions
Step2: Creating many features ... | Python Code:
%matplotlib inline
import numpy as np
from scipy.io import arff
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import patsy
import statsmodels.api as sm
from sklearn import tree, linear_model, metrics, dummy, naive_bayes, neighbors
from IPython.display import Image
import pydotpl... |
5,904 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ugly To Pretty for CSVS
Run on linux. Set an import path and an export path to folders.
Will take every file in import directory that is a mathematica generated CSV and turn it into a nicely... | Python Code:
importpath = "/home/jwb/repos/github-research/csvs/Individuals/Ugly/Stack/"
exportpath = "/home/jwb/repos/github-research/csvs/Individuals/Pretty/Stack/"
Explanation: Ugly To Pretty for CSVS
Run on linux. Set an import path and an export path to folders.
Will take every file in import directory that is a m... |
5,905 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2 align="center">点击下列图标在线运行HanLP</h2>
<div align="center">
<a href="https
Step1: 加载模型
HanLP的工作流程是先加载模型,模型的标示符存储在hanlp.pretrained这个包中,按照NLP任务归类。
Step2: 调用hanlp.load进行加载,模型会自动下载到本地缓存。自... | Python Code:
!pip install hanlp -U
Explanation: <h2 align="center">点击下列图标在线运行HanLP</h2>
<div align="center">
<a href="https://colab.research.google.com/github/hankcs/HanLP/blob/doc-zh/plugins/hanlp_demo/hanlp_demo/zh/srl_mtl.ipynb" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" ... |
5,906 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using an SVM classifier with RBF kernel
Contest entry by
Step1: This data is from the Council Grove gas reservoir in Southwest Kansas. The Panoma Council Grove Field ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.metrics import f1_score, accuracy_score, make_scorer
from sklearn.model_selection import LeaveOneGroupOut, validation_curve
import pandas as pd
from pandas import se... |
5,907 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Diversified economy
Matrix $X$ - production needs, where $x_{ij}$ is how much of $i$-th product is needed to make $j$-th product
Step1: Vector $y$ - consumer needs, where $y_i$ shows how mu... | Python Code:
X = np.array([[500, 300], [150, 200]])
Explanation: Diversified economy
Matrix $X$ - production needs, where $x_{ij}$ is how much of $i$-th product is needed to make $j$-th product
End of explanation
y = np.array([900, 500])
Explanation: Vector $y$ - consumer needs, where $y_i$ shows how much of $i$-th pro... |
5,908 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification using Machine Learning- Random Forest
Contest entry by Priyanka Raghavan and Steve Hall
This notebook demonstrates how to train a machine learning algorithm to predict ... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from sklearn.ensemble import RandomForestClassifier
from pandas import set_option
set_option("display... |
5,909 | 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, x, b, sigma, size=10):
Create a line y = m*x + b + N(0,s... |
5,910 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic setup
Step4: The problems
When using the any search function to search for two different terms, the results are wrong.
Problem 1
Step6: Solving problem 1
This query gets wrong result... | Python Code:
# coding: utf-8
import os
from cheshire3.baseObjects import Session
from cheshire3.document import StringDocument
from cheshire3.internal import cheshire3Root
from cheshire3.server import SimpleServer
session = Session()
session.database = 'db_dickens'
serv = SimpleServer(session, os.path.join(cheshire3... |
5,911 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jiří Polcar <polcar@physics.muni.cz>
Úvod
Motivace
Workflow
Základní dělení metod strojového učení
Redukce dimenzi & feature importance
Vyhodnocení modelů
Cross validation & Grid searc... | Python Code:
from sklearn import datasets
from sklearn import metrics
digits = datasets.load_digits()
fig, axes = plt.subplots(5, 10, figsize=(8, 5))
fig.subplots_adjust(hspace=0.1, wspace=0.1)
for i, ax in enumerate(axes.flat):
ax.imshow(digits.images[i], cmap='binary')
ax.text(0.05, 0.05, str(digits.target[i]... |
5,912 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Slater module about the slater's rule
Germain Salvato-Vallverdu germain.vallverdu@uni... | Python Code:
import slater
print(slater.__doc__)
Explanation: Slater module about the slater's rule
Germain Salvato-Vallverdu germain.vallverdu@univ-pau.fr
Atomic orbitals
The Klechk... |
5,913 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sebastian Raschka
back to the matplotlib-gallery at https
Step1: Errorbar Plots in matplotlib
Sections
Standard Deviation, Standard Error, and Confidence Intervals
Adding error bars to a ba... | Python Code:
%load_ext watermark
%watermark -u -v -d -p matplotlib,numpy,scipy
%matplotlib inline
Explanation: Sebastian Raschka
back to the matplotlib-gallery at https://github.com/rasbt/matplotlib-gallery
End of explanation
import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import t
# Generating... |
5,914 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
X-ray Speckle Visibility Spectroscopy
The analysis module "skxray/core/speckle" https
Step1: Easily switch between interactive and static matplotlib plots¶
Step2: This data provided by Dr.... | Python Code:
import xray_vision
import xray_vision.mpl_plotting as mpl_plot
import skxray.core.speckle as xsvs
import skxray.core.roi as roi
import skxray.core.correlation as corr
import skxray.core.utils as utils
import numpy as np
import os, sys
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib... |
5,915 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: TensorFlow 2 quickstart for beginners
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: If yo... | 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... |
5,916 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Home Depot Product Search Relevance
The challenge is to predict a relevance score for the provided combinations of search terms and products. To create the ground truth labels, Home Depot ha... | Python Code:
import graphlab as gl
from nltk.stem import *
Explanation: Home Depot Product Search Relevance
The challenge is to predict a relevance score for the provided combinations of search terms and products. To create the ground truth labels, Home Depot has crowdsourced the search/product pairs to multiple human ... |
5,917 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: TF.Text Metrics
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: ROUGE-L
The Rouge-L metric ... | 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... |
5,918 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this tutorial, we illustrate how to generate decision landscape visualisations. As an example, we use the data from O'Hora et al.(2013).
First, download the data from https
Step1: Cache ... | Python Code:
import os
from pydlv import data_reader, derivative_calculator
dr = data_reader.DataReader()
dc = derivative_calculator.DerivativeCalculator()
data = dr.read_data(path='../../../../data/scirep_locdyn')
# rewards_sum defines the experimental conditions to be analysed (see data description on OSF for details... |
5,919 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hands-On Exercise 6
Step1: The first thing to notice is that the table does not include magnitude measurements. Gaaaasp The horror!!
As an important point of background - Firth et al. norma... | Python Code:
# execute this cell
SNlcs = Table.read("../data/Firth14Tbl2.txt", format = 'ascii')
SNlcs
Explanation: Hands-On Exercise 6: Determining $H_0$ with Type Ia SNe from PTF
Version 0.1
Today we learned about a variety of different explosive, extragalactic transients. While the lectures focused on recently disco... |
5,920 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BigQuery Query To Table
Save query results into a BigQuery table.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: BigQuery Query To Table
Save query results into a BigQuery table.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may o... |
5,921 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grade
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 created (w... | Python Code:
import pg8000
conn = pg8000.connect(user='postgres', password='password', database="homework2_radhika")
Explanation: Grade: 6 / 6 -- but search "TA-COMMENT" to see a few notes on some of the problems.
Homework 2: Working with SQL (Data and Databases 2016)
This homework assignment takes the form of an IPyth... |
5,922 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Active Subspaces Example Function
Step1: First we draw M samples randomly from the input space.
Step2: Now we normalize the inputs, linearly scaling each to the interval $[-1, 1]$.
Step3: ... | Python Code:
import active_subspaces as ac
import numpy as np
%matplotlib inline
# The piston_functions.py file contains two functions: the piston function (piston(xx))
# and its gradient (piston_grad(xx)). Each takes an Mx7 matrix (M is the number of data
# points) with rows being normalized inputs; piston returns a c... |
5,923 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Inference Button
Step1: Generating data
Create some toy data to play around with and scatter-plot it.
Essentially we are creating a regression line defined by intercept and slope and a... | Python Code:
%matplotlib inline
from pymc3 import *
import numpy as np
import matplotlib.pyplot as plt
Explanation: The Inference Button: Bayesian GLMs made easy with PyMC3
Author: Thomas Wiecki
This tutorial appeared as a post in a small series on Bayesian GLMs on my blog:
The Inference Button: Bayesian GLMs made eas... |
5,924 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pvsystem tutorial
This tutorial explores the pvlib.pvsystem module. The module has functions for importing PV module and inverter data and functions for modeling module and inverter performa... | Python Code:
# built-in python modules
import os
import inspect
import datetime
# scientific python add-ons
import numpy as np
import pandas as pd
# plotting stuff
# first line makes the plots appear in the notebook
%matplotlib inline
import matplotlib.pyplot as plt
# seaborn makes your plots look better
try:
impo... |
5,925 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 2nd step
Step1: In the following example, the data of the Object which x refered did not change but x refered new Object.
Step2: Basic Data type
Plese refer Python3 reference for de... | Python Code:
x = 1
print('x =', x, type(x))
x = 'abc'
print('x =', x, type(x))
Explanation: Python 2nd step: Variables and Data type
In case of C or other compile langueage, variables need to be declared with data type.
In Python, Object have data type, variables just refer Object. Following sequence is valid in Python... |
5,926 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Weather Forecast with PixieDust
This notebook shows how to
Step1: 2. Get weather data
Find the latitude and longitude of your current location by running this magic javascript cell. Then fi... | Python Code:
#!pip install --upgrade pixiedust
#!pip install --upgrade bokeh
import requests
import json
import pandas as pd
import numpy as np
from datetime import datetime
import time
import pixiedust
Explanation: Weather Forecast with PixieDust
This notebook shows how to:
1. use the Weather Company Data API to get w... |
5,927 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Module 2
Convolutions
First let's have a look at what convolutions do
Learning Activity 1
Step1: Learning Activity 2
Step2: The flag flatten means you imported the image as a grey-scale im... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
from scipy import misc
% matplotlib inline
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.cmap'] = 'gray'
Explanation: Module 2
Convolutions
First let's have a look at what convolutions do
Learning Activity 1: Load the Python libra... |
5,928 | 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', 'dwd', 'mpi-esm-1-2-hr', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: DWD
Source ID: MPI-ESM-1-2-HR
Topic: Seaice
Sub-Topics: Dynamics, Therm... |
5,929 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook 8
Step1: Download the sequence data
Sequence data for this study are archived on the NCBI sequence read archive (SRA). Below I read in SraRunTable.txt for this project which contai... | Python Code:
### Notebook 8
### Data set 8: Barnacles
### Authors: Herrera et al. 2015
### Data Location: SRP051026
Explanation: Notebook 8:
This is an IPython notebook. Most of the code is composed of bash scripts, indicated by %%bash at the top of the cell, otherwise it is IPython code. This notebook includes code to... |
5,930 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 3
Previously in 2_fullyconnected.ipynb, you trained a logistic regression and a neural network model.
The goal of this assignment is to explore regularization techni... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
import cPickle as pickle
import numpy as np
import tensorflow as tf
Explanation: Deep Learning
Assignment 3
Previously in 2_fullyconnected.ipynb, you trained a logistic regression and a neural netwo... |
5,931 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explore surface Argo oxygen float and World Ocean Atlas data
Get cached surface data and compare with data from the World Ocean Atlas
Build local cache of data from some floats known to have... | Python Code:
from biofloat import ArgoData
from os.path import join, expanduser
ad = ArgoData(cache_file = join(expanduser('~'),
'biofloat_fixed_cache_variablesDOXY_ADJUSTED-PSAL_ADJUSTED-TEMP_ADJUSTED_wmo1900650-1901157-5901073.hdf'))
Explanation: Explore surface Argo oxygen float and World Ocean Atlas data
Get ... |
5,932 | 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):
pass
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,high,n):
pass
for num in rand_nu... |
5,933 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3.2. Increasing dataset size
The next thing we're going to try is to increase the size of our dataset. On the previous trainings we used a small subset of the book "Don Quijote de La Mancha"... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils
Explanation: 3.2. Increasing dataset size
The nex... |
5,934 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Please find torch implementation of this notebook here
Step1: Implementation from scratch
For fully connected layers, we take the average along minibatch samples for each dimension independ... | Python Code:
import jax
import jax.numpy as jnp # JAX NumPy
import matplotlib.pyplot as plt
import math
from IPython import display
try:
from flax import linen as nn # The Linen API
except ModuleNotFoundError:
%pip install -qq flax
from flax import linen as nn # The Linen API
from flax.training import tr... |
5,935 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib
Introduccion
Matplotlib es la libreria ejemplar para la visualización de información en Python. Fue creada por John Hunter con la intención de replicar las capacidaddes para grafi... | Python Code:
import matplotlib.pyplot as plt
Explanation: Matplotlib
Introduccion
Matplotlib es la libreria ejemplar para la visualización de información en Python. Fue creada por John Hunter con la intención de replicar las capacidaddes para graficar de MatLab.
Es una excelente libreria para graficar 2D y 3D así como ... |
5,936 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 9
Step1: As you can see, this folder holds a number of plain text files, ending in the .txt extension. Let us open a random file
Step2: Here, we use the open() function to create a... | Python Code:
ls data/arabian_nights
Explanation: Chapter 9: What we have covered so far (and a bit more)
In this chapter, we will work our way through a concise review of the Python functionality we have covered so far. Throughout this chapter, we will work with a interesting, yet not too large dataset, namely the well... |
5,937 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Schauen wir uns den Flughafen Basel an
Step1: Die Dokumentatiovon BeautifulSoup ist wirklich sehr beautiful. Es lohnt sich hier einen Blick darauf zu werfen. Beginnen wir damit, die Arrival... | Python Code:
import requests
from bs4 import BeautifulSoup
import pandas as pd
Explanation: Schauen wir uns den Flughafen Basel an
End of explanation
url = "https://www.euroairport.com/en/flights/daily-arrivals.html"
response = requests.get(url)
arrivals_soup = BeautifulSoup(response.text, 'html.parser')
arrivals_soup
... |
5,938 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DESI spectral extraction code benchmarks
Stephen Bailey<br/>
Lawrence Berkeley National Lab<br/>
Spring 2017
Update 2017-03-12
Intel engineers identified the cause of the previous lack of sc... | Python Code:
%pylab inline
import numpy as np
from astropy.table import Table
#- Scaling with OMP_NUM_THREADS (or not)
nt_hsw = Table.read('data/extract/ex-nthread-hsw-1.dat', format='ascii')
nt_knl = Table.read('data/extract/ex-nthread-knl-1.dat', format='ascii')
plot(nt_hsw['OMP_NUM_THREADS'], nt_hsw['time'], 'bs-')
... |
5,939 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NCEMPY's 3D slicer
Interactively scroll through all images in a 3D dataset
Ideal for time series data and can be used for volume data
Set the dirName nad fName below to point to your data an... | Python Code:
# Set the data location
dirName = r'c:\users\linol\data'
fName = '10_series_1.ser'
# Load needed modules
%matplotlib widget
from pathlib import Path
import matplotlib.pyplot as plt
import ncempy.io as nio
import ipywidgets as widgets
from ipywidgets import interact, interactive
Explanation: NCEMPY's 3D sli... |
5,940 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Geowave GPX Demo
This Demo runs KMeans on the GPX dataset consisting of approximately 285 million point locations. We use a cql filter to reduce the KMeans set to a bounding box over Berlin,... | Python Code:
#!pip install --user --upgrade pixiedust
import pixiedust
import geowave_pyspark
Explanation: Geowave GPX Demo
This Demo runs KMeans on the GPX dataset consisting of approximately 285 million point locations. We use a cql filter to reduce the KMeans set to a bounding box over Berlin, Germany. Simply focus ... |
5,941 | 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', 'noaa-gfdl', 'gfdl-cm4', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: GFDL-CM4
Topic: Atmoschem
Sub-Topics: Transp... |
5,942 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--
27/10
Ordenamientos y búsquedas.
Excepciones. Funciones anónimas.(Pablo o Andres)
-->
Ordenamiento de listas
Las listas se pueden ordenar fácilmente usando la función sorted
Step1: Per... | Python Code:
lista_de_numeros = [1, 6, 3, 9, 5, 2]
lista_ordenada = sorted(lista_de_numeros)
print lista_ordenada
print lista_de_numeros
Explanation: <!--
27/10
Ordenamientos y búsquedas.
Excepciones. Funciones anónimas.(Pablo o Andres)
-->
Ordenamiento de listas
Las listas se pueden ordenar fácilmente usando la funció... |
5,943 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CNTK Time series prediction with LSTM
This demo demonstrates how to use CNTK to predict future values in a time series using a Recurrent Neural Network (RNN). It is based on a LSTM tutorial ... | Python Code:
# Standard packages
import math
from matplotlib import pyplot as plt
import numpy as np
import os
import pandas as pd
import time
# Helpers for reading stock prices
import pandas_datareader.data as pdr
import datetime as dt
# Images
from IPython.display import Image
# CNTK packages
import cntk as C
import ... |
5,944 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
API example for the formal integral
There are currently two ways to invoke the calculation of the formal integral with tardis. The first is for the use in interactive shells and scripts and ... | Python Code:
%pylab notebook
import tardis
from tardis.io.config_reader import Configuration
from tardis.simulation import Simulation
config_fname = tardis.__path__[0] + '/../../data/tardis_example/tardis_example_integral.yml'
Explanation: API example for the formal integral
There are currently two ways to invoke the c... |
5,945 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
k-Nearest Neighbor (kNN) exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ... | Python Code:
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
import numpy.linalg as la
import seaborn as sns
import itertools
import pandas as pd
sns.set_style('whitegrid')
# create a palette generator
palette = iterto... |
5,946 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DTM Example
In this example we will present a sample usage of the DTM wrapper. Prior to using this you need to compile the DTM code yourself or use one of the binaries.
This tutorial is on W... | Python Code:
import logging
import os
from gensim import corpora, utils
from gensim.models.wrappers.dtmmodel import DtmModel
import numpy as np
Explanation: DTM Example
In this example we will present a sample usage of the DTM wrapper. Prior to using this you need to compile the DTM code yourself or use one of the bina... |
5,947 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 4 - stripy gradients
SRFPACK is a Fortran 77 software package that constructs a smooth interpolatory or approximating surface to data values associated with arbitrarily distributed p... | Python Code:
import stripy as stripy
xmin = 0.0
xmax = 10.0
ymin = 0.0
ymax = 10.0
extent = [xmin, xmax, ymin, ymax]
spacingX = 0.2
spacingY = 0.2
mesh = stripy.cartesian_meshes.elliptical_mesh(extent, spacingX, spacingY, refinement_levels=3)
print("number of points = {}".format(mesh.npoints))
Explanation: Example 4 - ... |
5,948 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial showing how to create Parcels in Agulhas animated gif
This brief tutorial shows how to recreate the animated gif showing particles in the Agulhas region south of Africa.
We start wi... | Python Code:
from parcels import FieldSet, ParticleSet, JITParticle, AdvectionRK4, ErrorCode
from datetime import timedelta
import numpy as np
Explanation: Tutorial showing how to create Parcels in Agulhas animated gif
This brief tutorial shows how to recreate the animated gif showing particles in the Agulhas region so... |
5,949 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inference with Discrete Latent Variables
This tutorial describes Pyro's enumeration strategy for discrete latent variable models.
This tutorial assumes the reader is already familiar with th... | Python Code:
import os
import torch
import pyro
import pyro.distributions as dist
from torch.distributions import constraints
from pyro import poutine
from pyro.infer import SVI, Trace_ELBO, TraceEnum_ELBO, config_enumerate, infer_discrete
from pyro.infer.autoguide import AutoNormal
from pyro.ops.indexing import Vindex... |
5,950 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a CNN model with the CIFAR-10 dataset in ML Engine
The trainer package source is inside the cifar10 directory. It was based from Tensorflow's CNN tutorial and one of the Datalab ima... | Python Code:
%%bash
cd cifar10
# Clean old builds
rm -rf build dist
# Build wheel distribution
python setup.py bdist_wheel --universal
# Check the built package
ls -al dist
Explanation: Training a CNN model with the CIFAR-10 dataset in ML Engine
The trainer package source is inside the cifar10 directory. It was based f... |
5,951 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extracting information about sequence quality and enrichment
Enrichment
Often want to compare two datasets (tissue 1 vs. tissue 2; -drug vs. +drug; etc.)
Done by taking ratio of counts for s... | Python Code:
print(chr(33))
print(chr(34))
print(chr(35))
print("...")
print(chr(74))
print(chr(75))
Explanation: Extracting information about sequence quality and enrichment
Enrichment
Often want to compare two datasets (tissue 1 vs. tissue 2; -drug vs. +drug; etc.)
Done by taking ratio of counts for sequences between... |
5,952 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Construct structures defining the DSLWP-B telemetry.
Step1: Load frames from CSV file. proxy_time is set by the client when sending the frame (using groundstation PC clock). server_time is ... | Python Code:
TMPrimaryHeader = BitStruct('transfer_frame_version_number' / BitsInteger(2),
'spacecraft_id' / BitsInteger(10),
'virtual_channel_id' / BitsInteger(3),
'ocf_flag' / Flag,
'master_channel_frame_co... |
5,953 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Continuous Target Decoding with SPoC
Source Power Comodulation (SPoC)
Step1: Plot the contributions to the detected components (i.e., the forward model) | Python Code:
# Author: Alexandre Barachant <alexandre.barachant@gmail.com>
# Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
import mne
from mne import Epochs
from mne.decoding import SPoC
from mne.datasets.fieldtrip_cmc import data_path
from sklearn.pipeline i... |
5,954 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 Google LLC.
Step1: Object pose alignment
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Now that Tensorflow Graphics is i... | 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... |
5,955 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FPLCPlot (FPLC Chromatogram plotting tool)
Interactive Jupyter notebok interface to FPLCPlot.
An interactive Jupyter notebook to plot chromatograms outputted from GE Life Sciences / Amersha... | Python Code:
%matplotlib inline
from fplcplot.chromatogram import plotTraces
Explanation: FPLCPlot (FPLC Chromatogram plotting tool)
Interactive Jupyter notebok interface to FPLCPlot.
An interactive Jupyter notebook to plot chromatograms outputted from GE Life Sciences / Amersham Biosciences UNICORN 5.X software. To u... |
5,956 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 3 Tutorial Notebook
We'll be using this notebook to follow the slides from the workshop. You can also use it to experiment with Python yourself! Simply add a cell wherever you want, t... | Python Code:
# When a line begins with a '#' character, it designates a comment. This means that it's not actually a line of code
# This is how you say hello world
print('hello world')
# Can you make Python print the staircase below:
#
# ========
# | |
# ==========... |
5,957 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
k-Nearest Neighbor (kNN) exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ... | Python Code:
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsi... |
5,958 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
루프(Loop)
시퀀스 자료형을 for 문 또는 while 문과 조합하여 사용하면 간단하지만 강력한 루프 프로그래밍을 완성할 수 있다. 특히 range 또는 xrange 함수를 유용하게 활용할 수 있다.
for 문 루프
리스트 활용
Step1: 서식 있는 print 문
위 코드에서는 서식이 있는 print문(formatted print)... | Python Code:
animals = ['cat', 'dog', 'mouse']
for x in animals:
print("This is the {}.".format(x))
Explanation: 루프(Loop)
시퀀스 자료형을 for 문 또는 while 문과 조합하여 사용하면 간단하지만 강력한 루프 프로그래밍을 완성할 수 있다. 특히 range 또는 xrange 함수를 유용하게 활용할 수 있다.
for 문 루프
리스트 활용
End of explanation
for x in animals:
print("{}!, this is the {}.".for... |
5,959 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting Earnings from Census Data with Decision Tree
taken from The Analytics Edge
The Task
The United States government periodically collects demographic information by conducting a cens... | Python Code:
import pandas as pd
import numpy as np
Explanation: Predicting Earnings from Census Data with Decision Tree
taken from The Analytics Edge
The Task
The United States government periodically collects demographic information by conducting a census.
In this problem, we are going to use census information about... |
5,960 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step8: Lending Club Data Explorations
Preprocess Data
Step9: Load Data
Step10: Load data dictionary
Step11: The first thing I am going to do is find the percentage of missing values in my... | Python Code:
%pylab inline
# Import libraries
from __future__ import absolute_import, division, print_function
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
from sklearn.externals import joblib
# Graphing Libraries
import matplotlib.pyplot as pyplt
import sea... |
5,961 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 线程与协程(2)
我之前翻译了Python 3.5 协程原理这篇文章之后尝试用了 Tornado + Motor 模式下的协程进行异步开发,确实感受到协程所带来的好处(至少是语法上的
Step1: 后来又新增了 yield from 语法,可以将生成器串联起来:
Step3: yield from/send 似乎已经满足了协程所定义的需求,最初也确实是用 @t... | Python Code:
def jump_range(upper):
index = 0
while index < upper:
jump = yield index
if jump is None:
jump = 1
index += jump
jump = jump_range(5)
print(jump)
print(jump.send(None))
print(jump.send(3))
print(jump.send(None))
Explanation: Python 线程与协程(2)
我之前翻译了Python 3.5 协程原理这... |
5,962 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read motifs from files in other formats.
Step1: You can convert a motif to several formats.
Step2: Some other useful tidbits.
Step3: To convert a motif to an image, use to_img(). Supporte... | Python Code:
with open("MA0099.3.jaspar") as f:
motifs = read_motifs(f, fmt="jaspar")
print(motifs[0])
Explanation: Read motifs from files in other formats.
End of explanation
with open("example.pfm") as f:
motifs = read_motifs(f)
# pwm
print(motifs[0].to_pwm())
# pfm
print(motifs[0].to_pfm())
# consensus seque... |
5,963 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
Step1: <div id="toc"></div>
Step2: Step 1) Load bhm_e
Step3: Load detector pair dictionaries.
Step4: Step 2) Produce bhp_e
Step5: Look at subsets of pairs later. For now I'll assum... | Python Code:
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')
Explanation: Goal: Build and plot bhp_e
P. Schuster, University of Michigan
June 21, 2018
Load bhm_e
Build a function to sum across custom pairs for bhp_e
Plot it
Plot slices
End of explanation
%load_ex... |
5,964 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BGS Spectral Simulations
The goal of this notebook is to do some BGS spectral simulations for paper one.
Getting started.
First, import all the package dependencies.
Step1: Specify the para... | Python Code:
import os
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.table import Table
import yaml
import desispec.io
import desisim.io
from desisim.scripts import quickgen
from desispec.scripts import group_spectra
from desispec.io.util import write_bin... |
5,965 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RedCap Status Dashboard - One Line Per Form
Creating a dashboard of one form per line
Parametrization
Step1: Import Libraries
Set up libraries to display each form and navigate paths to fin... | Python Code:
site: str
arm: str
form: str
Explanation: RedCap Status Dashboard - One Line Per Form
Creating a dashboard of one form per line
Parametrization
End of explanation
from IPython.display import display, Markdown, Latex
import pandas as pd
from pathlib import Path
import sys
sys.path.append('/sibis-software/nc... |
5,966 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SMI - Similarity of Matrices Index
SMI is a measure of the similarity between the dominant subspaces of two matrices. It comes in two flavours (projections)
Step1: Next, load the data that ... | Python Code:
import hoggorm as ho
import hoggormplot as hop
import pandas as pd
import numpy as np
Explanation: SMI - Similarity of Matrices Index
SMI is a measure of the similarity between the dominant subspaces of two matrices. It comes in two flavours (projections):
- OP - Orthogonal Projections
- PR - Procrustes R... |
5,967 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FD_1D_DX4_DT4_LW 1-D acoustic Finite-Difference modelling
GNU General Public License v3.0
Author
Step1: Input Parameter
Step2: Preparation
Step3: Create space and time vector
Step4: Sour... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Explanation: FD_1D_DX4_DT4_LW 1-D acoustic Finite-Difference modelling
GNU General Public License v3.0
Author: Florian Wittkamp
Finite-Difference acoustic seismic wave simulation
Discretization of the first-order acoustic wave equation
T... |
5,968 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The author-topic model
Step1: In the following sections we will load the data, pre-process it, train the model, and explore the results using some of the implementation's functionality. Fee... | Python Code:
!wget -O - 'http://www.cs.nyu.edu/~roweis/data/nips12raw_str602.tgz' > /tmp/nips12raw_str602.tgz
import tarfile
filename = '/tmp/nips12raw_str602.tgz'
tar = tarfile.open(filename, 'r:gz')
for item in tar:
tar.extract(item, path='/tmp')
Explanation: The author-topic model: LDA with metadata
In this tuto... |
5,969 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Download, Parse and Interrogate Apple Health Export Data
The first part of this program is all about getting the Apple Health export and putting it into an analyzable format. At that point ... | Python Code:
import xml.etree.ElementTree as et
import pandas as pd
import numpy as np
from datetime import *
import matplotlib.pyplot as plt
import re
import os.path
import zipfile
import pytz
%matplotlib inline
plt.rcParams['figure.figsize'] = 16, 8
Explanation: Download, Parse and Interrogate Apple Health Export D... |
5,970 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Christofides algorithm
Create a minimum spanning tree T of G.
Let O be the set of vertices with odd degree in T. By the handshaking lemma, O has an even number of vertices.
Find a minimum-we... | Python Code:
def Christofides(G):
T = nx.algorithms.minimum_spanning_tree(G)
O = {n for n, d in T.degree(T.nodes_iter()).items() if d%2 == 1}
induced_subgraph = nx.Graph(G.subgraph(O))
M = minimum_perfect_matching(induced_subgraph)
T.add_weighted_edges_from([(u,v,M[u][v]['weight']) for u... |
5,971 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Water Filling in Communications
by Robert Gowers, Roger Hill, Sami Al-Izzi, Timothy Pollington and Keith Briggs
from Boyd and Vandenberghe, Convex Optimization, example 5.2 page 145
Convex o... | Python Code:
#!/usr/bin/env python3
# @author: R. Gowers, S. Al-Izzi, T. Pollington, R. Hill & K. Briggs
import numpy as np
import cvxpy as cp
def water_filling(n, a, sum_x=1):
'''
Boyd and Vandenberghe, Convex Optimization, example 5.2 page 145
Water-filling.
This problem arises in information theor... |
5,972 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re goin... |
5,973 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Linear Programming with Python - Part 2
Introduction to PuLP
PuLP is an open source linear programming package for python. PuLP can be installed using pip, instructions here.... | Python Code:
import pulp
Explanation: Introduction to Linear Programming with Python - Part 2
Introduction to PuLP
PuLP is an open source linear programming package for python. PuLP can be installed using pip, instructions here.
In this notebook, we'll explore how to construct and solve the linear programming problem d... |
5,974 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Here is a rather difficult problem. | Problem:
import numpy as np
A = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
B = np.argwhere(A)
(ystart, xstart), (ystop, xstop... |
5,975 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ch 04
Step1: Set up some data to work with
Step2: Define the placeholders, variables, model, cost function, and training op
Step3: Train the logistic model on the data
Step4: Now let's s... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
learning_rate = 0.01
training_epochs = 1000
Explanation: Ch 04: Concept 02
Logistic regression
Import the usual libraries, and set up the usual hyper-parameters:
End of explanation
x1 = np.random.normal(-4, 2, 100... |
5,976 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 2
Step1: Configure sql magic to output queries as pandas dataframes
Step2: Import the data analysis libraries
Step3: Import the MySQLdb library
Step4: Connect to the MySQL databas... | Python Code:
%load_ext sql
Explanation: Lesson 2: Setup Jupyter Notebook for Data Analysis
Learning Objectives:
<ol>
<li>Create Python tools for data analysis using Jupyter Notebooks</li>
<li>Learn how to access data from MySQL databases for data analysis</li>
</ol>
Exercise 1: Install Anaconda
Access https://c... |
5,977 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
License
Copyright (C) 2017 J. Patrick Hall, jphall@gwu.edu
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (t... | Python Code:
# numpy for matrix operations
import numpy as np
# matplotlib for plotting
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import proj3d
%matplotlib inline
# scikit for data set and easy standardization
from sklearn import datasets
from sklearn import ... |
5,978 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Traffic flow with an on-ramp
In this chapter we return to the LWR traffic model that we investigated in two earlier chapters. The LWR model involves a single length of one-way road; in this... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from clawpack import pyclaw
from clawpack import riemann
from ipywidgets import interact
from ipywidgets import widgets
from exact_solvers import traffic_ramps
from utils import riemann_tools
def c(rho, xi):
return (1.-2*rho)
def mak... |
5,979 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Starting comments
Charles Le Losq, Geophysical Laboratory, Carnegie Institution for Science. 7 April 2015.
This IPython notebook is aimed to show how you can easily fit a Raman spectrum with... | Python Code:
%matplotlib inline
import time
import numpy as np # For data manipulation
import scipy # For data manipulation
import random
import matplotlib.pyplot as plt # For doing the plots
Explanation: Starting comments
Charles Le Losq, Geophysical Laboratory, Carnegie Institution for Science. 7 April 2015.
This IPy... |
5,980 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Sklearn Stratified K-Fold - Splitting Data & Saving to File
| Python Code::
import pandas as pd
from sklearn.model_selection import StratifiedKFold
df = pd.read_csv('data/raw/train.csv')
# initialise a StratifiedKFold object with 5 folds and
# declare the column that we which to group by which in this
# case is the column called "label"
skf = StratifiedKFold(n_splits=5)
target = ... |
5,981 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is my third attempt at creating a model using sklearn alogithms
In this iteration of analysis we'll be looking at breaking out categorical varaibles and making them binary, and seeing i... | Python Code:
# start with imports
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import json
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
Explanation: This is my third attempt at creating a model using sklearn alogithms
In this iteration ... |
5,982 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this tutorial will write a alignment algorithm with MDAnalysis functions and later look into the documentation to find functions for the implementation of the algorithm.
Step1: First we ... | Python Code:
from __future__ import print_function
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import MDAnalysis as mda
Explanation: In this tutorial will write a alignment algorithm with MDAnalysis functions and later look into the documentation to find functions for the implementation of the... |
5,983 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
```
Copyright 2018 Google LLC
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 Li... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import scipy.ndimage
import lib.eval
import collections
import tensorflow as tf
import glob
import lib.utils
import all_aes
from absl import flags
import sys
FLAGS = flags.FLAGS
FLAGS(['--lr', '0.0001'])
import os
if not os.path.exists('... |
5,984 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cloud AI Platform + What-if Tool
Step1: Loading the test dataset
The model we'll be exploring here is a binary classification model built with XGBoost and trained on a mortgage dataset. It ... | Python Code:
import sys
python_version = sys.version_info[0]
# If you're running on Colab, you'll need to install the What-if Tool package and authenticate on the TF instance
def pip_install(module):
if python_version == '2':
!pip install {module} --quiet
else:
!pip3 install {module} --quiet
try... |
5,985 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Answer the following questions in Python by defining a function. Ensure you have a docstring and that your function succeeds on the example use.
Create a function which takes two arguments
S... | Python Code:
#The points awarded this cell corresopnd to partial credit and/or documentation
### BEGIN SOLUTION
def power(x, p=2):
'''Computes x^p
Args:
x: input number
p: input power, defaults to 2
returns: x^p as a floating point
'''
return x**p
### END SOLUTION
'''Ch... |
5,986 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Airport Wait Time Simulation
Step1: For this simulation, we'll be using numpy and scipy for their statistical and matrix math prowess and matplotlib as our primary plotting tool
Step2: Set... | Python Code:
%matplotlib inline
#Imports for solution
import numpy as np
import scipy.stats as sp
from matplotlib.pyplot import *
#Setting Distribution variables
##All rates are in per Minute.
Explanation: Airport Wait Time Simulation
End of explanation
#Everything will me modeled as a Poisson Process
SIM_TIME = 180
QU... |
5,987 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t... |
5,988 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bcc', 'sandbox-1', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: BCC
Source ID: SANDBOX-1
Topic: Ocean
Sub-Topics: Timestepping Framework, Adve... |
5,989 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have the tensors: | Problem:
import numpy as np
import pandas as pd
import torch
ids, x = load_data()
idx = ids.repeat(1, 114).view(30, 1, 114)
result = torch.gather(x, 1, idx)
result = result.squeeze(1) |
5,990 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Knapsack Problem
Bin packing tried to minimize the number of bins needed for a fixed number of items, if we instead fix the number of bins and assign some way to value objects, then the knap... | Python Code:
from pulp import *
import numpy as np
Explanation: Knapsack Problem
Bin packing tried to minimize the number of bins needed for a fixed number of items, if we instead fix the number of bins and assign some way to value objects, then the knapsack problem tells us which objects to take to maximize our total ... |
5,991 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We use pyfst, a pyhton wrapper for the great openfst library. Thanks to Victor Chahuneau for the wrapper (check it on github).
Step5: Helper code
Step6: Input
sigma and delta are the sourc... | Python Code:
import fst
Explanation: We use pyfst, a pyhton wrapper for the great openfst library. Thanks to Victor Chahuneau for the wrapper (check it on github).
End of explanation
# Let's see the input as a simple linear chain FSA
def make_input(srcstr, sigma = None):
converts a nonempty string into a linea... |
5,992 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> 1. Exploring natality dataset </h1>
This notebook illustrates
Step2: <h2> Explore data </h2>
The data is natality data (record of births in the US). My goal is to predict the baby's we... | Python Code:
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
%%bash
if ! gsutil ls | grep -q gs://${BUCKET}/; then
gsutil mb -l ${REG... |
5,993 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ISQA 8080 Homework 2.2
Brian Detweiler
Step1: Tasks
The fourth task is to upload a dataset and to write and run different queries on this dataset.
The fifth task starts with Redis. First, i... | Python Code:
import pymongo
from pymongo import MongoClient
import datetime
import re
from pymongo import InsertOne, DeleteOne, ReplaceOne
import datetime
client = MongoClient()
client = MongoClient('mongodb://localhost:27017/')
db = client.homework2
users = db.users
movies = db.movies
Explanation: ISQA 8080 Homework 2... |
5,994 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
4. Mutant lists and other X-Men (or X-People, as you prefer)
Lists are simultaneously among the most useful and most confusing data structures in Python. Why? Because of mutability.
Mutating... | Python Code:
a = list(range(5))
print ("The list we created:", a, "of length", len(a))
b = list(range(6,10))
print ("The second list we created:", b, "of length", len(b))
a[1:3] = b # Line 7
print ("The first list after we changed a couple of elements is", a, "with length", len(a))
Explanation: 4. Mutant lists and othe... |
5,995 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extinction
Step1: As always, let's do imports and initialize a logger and a new bundle.
Step2: First we'll define the system parameters
Step3: And then create three light curve datasets a... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: Extinction: Eclipse Depth Difference as Function of Temperature
In this example, we'll reproduce Figure 3 in the extinction release paper (Jones et al. 2020).
NOTE: this script takes a long time to run.
<img src="jones+20_fig3.png" alt="Figure 3" width="800p... |
5,996 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CSE 6040, Fall 2015 [24]
Step5: Scalability with the problem size
To start, here is some code to help generate synthetic problems of a certain size, namely, $m \times (d+1)$, where $m$ is t... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: CSE 6040, Fall 2015 [24]: "Online" regression
This notebook continues the linear regression problem from last time, but asks about a method that can estimate the regression coefficients when you only get to see samples "one-... |
5,997 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
處理旅程資訊
先照之前的,讀取資料
Step1: 時間的格式固定
Step2: 先用慢動作來解析看看格式
先抓出第 0 筆資料的 TripInformation
看看要怎麼拆解這個字串,得到我們要的資料
Step3: 用迴圈來對前十筆資料做相同的事情
Step4: 偵測站
手冊附錄
https
Step5: Q
查看一下內容,比方看國道五號
python
node_d... | Python Code:
import tqdm
import tarfile
import pandas
from urllib.request import urlopen
# 檔案名稱格式
filename_format="M06A_{year:04d}{month:02d}{day:02d}.tar.gz".format
xz_filename_format="xz/M06A_{year:04d}{month:02d}{day:02d}.tar.xz".format
csv_format = "M06A/{year:04d}{month:02d}{day:02d}/{hour:02d}/TDCS_M06A_{year:04d... |
5,998 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
News classification with topic models in gensim
News article classification is a task which is performed on a huge scale by news agencies all over the world. We will be looking into how topi... | Python Code:
import os
import re
import operator
import matplotlib.pyplot as plt
import warnings
import gensim
import numpy as np
warnings.filterwarnings('ignore') # Let's not pay heed to them right now
from gensim.models import CoherenceModel, LdaModel, LsiModel, HdpModel
from gensim.models.wrappers import LdaMallet
... |
5,999 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Imports
Step1: Simple Mock Data
Lets create a simple mock dataset with one independent variable and one dependent variable with a little noise.
Step2: Boston Housing Dataset
feautres
Step3... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.contrib import keras
from sklearn import datasets
from sklearn import linear_model
import statsmodels.api as sm
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
Explanation: Imports
End of explanation
Nsa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.