Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
400 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unstructured Mesh Tallies with CAD Geometry in OpenMC
In the first notebook on this topic, we looked at how to set up a tally using an unstructured mesh in OpenMC.
In this notebook, we will ... | Python Code:
import os
from IPython.display import Image
import openmc
import openmc.lib
assert(openmc.lib._dagmc_enabled())
Explanation: Unstructured Mesh Tallies with CAD Geometry in OpenMC
In the first notebook on this topic, we looked at how to set up a tally using an unstructured mesh in OpenMC.
In this notebook, ... |
401 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explicit 1D Benchmarks
This file demonstrates how to generate, plot, and output data for 1d benchmarks
Choose from
Step1: Generate the data with noise
Step2: Plot inline and save image
Ste... | Python Code:
from pypge.benchmarks import explicit
import numpy as np
# visualization libraries
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# plot the visuals in ipython
%matplotlib inline
Explanation: Explicit 1D Benchmarks
This file demonstrates how to generate, plot, and output data for 1... |
402 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A simple example of multilabel learning
Step1: Data loading
Load yeast dataset.
Step2: Features
Step3: Labels
Step4: Data analysis
Step5: Histogram of #positive labels.
Step8: Dataset... | Python Code:
%matplotlib inline
import os, sys, time
import pickle as pkl
import numpy as np
import pandas as pd
import sklearn as sk
import cython
import itertools
from scipy.io import arff
from scipy.optimize import minimize
from scipy.optimize import check_grad
from sklearn.linear_model import LogisticRegression
fro... |
403 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ripple Counter from Toggle Flip-Flops
In this example we create a ripple counter from toggle flip-flops.
We also show how to define new Magma Circuits
and introduce generators.
Step1: In t... | Python Code:
import magma as m
Explanation: Ripple Counter from Toggle Flip-Flops
In this example we create a ripple counter from toggle flip-flops.
We also show how to define new Magma Circuits
and introduce generators.
End of explanation
from mantle import DFF
class TFF(m.Circuit):
io = m.IO(O=m.Out(m.Bit)) + m.... |
404 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tracking Parameters and Metrics for Vertex AI Custom Training Jobs
Learning objectives
In this notebook, you learn how to
Step1: Please ignore the incompatibility errors.
Restart the kernel... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
# Inst... |
405 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trends Places To BigQuery Via Values
Move using hard coded WOEID values.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use th... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: Trends Places To BigQuery Via Values
Move using hard coded WOEID values.
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.
Yo... |
406 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Processes in Shogun
By Heiko Strathmann - <a href="mailto
Step1: Some Formal Background (Skip if you just want code examples)
This notebook is about Bayesian regression models with... | Python Code:
%matplotlib inline
# import all shogun classes
from shogun import *
import random
import numpy as np
import matplotlib.pyplot as plt
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from math import exp
Explanation: Gaussian Processes in Shogun
By Heiko Strathmann - <a href="mailto:h... |
407 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Características de HoG
En este notebook creará un conjunto de imagenes con caras y no caras mediante las que obtendremos las características de HoG que nos servirán como conjunto de entrenam... | Python Code:
from sklearn.datasets import fetch_lfw_people
faces = fetch_lfw_people()
positive_patches = faces.images
positive_patches.shape
Explanation: Características de HoG
En este notebook creará un conjunto de imagenes con caras y no caras mediante las que obtendremos las características de HoG que nos servirán c... |
408 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background information on configurations
This tutorial gives a short introduction to MNE configurations.
Step1: MNE-python stores configurations to a folder called .mne in the user's
home d... | Python Code:
import os.path as op
import mne
from mne.datasets.sample import data_path
fname = op.join(data_path(), 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname).crop(0, 10)
original_level = mne.get_config('MNE_LOGGING_LEVEL', 'INFO')
Explanation: Background information on configurations
Th... |
409 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: 函数式 API
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 简介
Keras 函数式 API 是一种比 tf.keras.Sequentia... | 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... |
410 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
automaton.is_synchronized
Whether the automaton is synchronized
Step1: The following automaton is not synchronized, because a transition with less letters on the second tape $a| \varepsilon... | Python Code:
import vcsn
ctx = vcsn.context("lat<law_char, law_char>, b")
Explanation: automaton.is_synchronized
Whether the automaton is synchronized:
- every transition has the same number of letters on every tape, except for a few leading to final states
- in each accepting path, disregarding spontaneous transitions... |
411 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
机器学习纳米学位
监督学习
项目2
Step1: 练习:数据探索
首先我们对数据集进行一个粗略的探索,我们将看看每一个类别里会有多少被调查者?并且告诉我们这些里面多大比例是年收入大于50,000美元的。在下面的代码单元中,你将需要计算以下量:
总的记录数量,'n_records'
年收入大于50,000美元的人数,'n_greater_50k'.
年收入最多为50,000美元... | Python Code:
# 检查你的Python版本
from sys import version_info
if version_info.major != 2 and version_info.minor != 7:
raise Exception('请使用Python 2.7来完成此项目')
# 为这个项目导入需要的库
import numpy as np
import pandas as pd
from time import time
from IPython.display import display # 允许为DataFrame使用display()
# 导入附加的可视化代码visuals.py
impo... |
412 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 4
Step8: PMI
Point-wise mutual information is a measure of association used in information theory and statistics. In the words of Jurafsky and Martin
Step24: Unigram and Skipgram
To tr... | Python Code:
from collections import defaultdict, Counter
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Lab 4: Pointwise Mutual Information
This lab is about applications of Pointwise Mutual Information (PMI) in natural language processing.
Tasks
Find collocations with PMI.
Create d... |
413 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FiPy 1D two-phase flow in porous mediaq, 11 October, 2019
Different approaches
Step1: Visualize the relative permeability and fractional flow curves
Step2: Equations
$$\varphi \frac{\parti... | Python Code:
from fipy import *
# relperm parameters
swc = 0.1
sor = 0.1
krw0 = 0.3
kro0 = 1.0
nw = 2.0
no = 2.0
# domain and boundaries
k = 1e-12 # m^2
phi = 0.4
u = 1.e-5
p0 = 100e5 # Pa
Lx = 100.
Ly = 10.
nx = 100
ny = 10
dx = Lx/nx
dy = Ly/ny
# fluid properties
muo = 0.002
muw = 0.001
# define the fractional flow f... |
414 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interacting with models
November 2014, by Max Zwiessele
with edits by James Hensman
The GPy model class has a set of features which are designed to make it simple to explore the parameter sp... | Python Code:
m = GPy.examples.regression.sparse_GP_regression_1D(plot=False, optimize=False)
Explanation: Interacting with models
November 2014, by Max Zwiessele
with edits by James Hensman
The GPy model class has a set of features which are designed to make it simple to explore the parameter space of the model. By def... |
415 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Estimator で線形モデルを構築する
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: Titanic データセットを読み込む
Titani... | 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... |
416 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Simple Autoencoder
We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
Explanation: A Simple Autoencoder
We'll start off by building a simple autoencoder to c... |
417 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Handling categorical data
In this notebook, I'll demonstrate different ways of mapping or encoding categorical data.
Step1: 1. Mapping ordinal features
Create a mapping dictionary first and... | Python Code:
# create a pandas dataframe with categorical variables to work with
import pandas as pd
df = pd.DataFrame([['green', 'M', 10.1, 'class1'],
['red', 'L', 13.5, 'class2'],
['blue', 'XL', 15.3, 'class1']])
df.columns = ['color', 'size', 'price', 'classlabel']
df
Explanatio... |
418 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: In order to use wget inside a Python program, you have to install it with pip
Step2: Then, you have to import the wget package
Step3: Now, let's develop a python fun... | Python Code:
!wget ftp://igs.bkg.bund.de/EUREF/BRDC/2022/033/BRDC00WRD_R_20220330000_01D_MN.rnx.gz
Explanation: <a href="https://colab.research.google.com/github/OSGeoLabBp/tutorials/blob/master/english/data_processing/lessons/download_gnss_data.ipynb" target="_parent"><img src="https://colab.research.google.com/assets... |
419 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Doc2Vec Tutorial on the Lee Dataset
Step1: What is it?
Doc2Vec is an NLP tool for representing documents as a vector and is a generalizing of the Word2Vec method. This tutorial will serve a... | Python Code:
import gensim
import os
import collections
import smart_open
import random
Explanation: Doc2Vec Tutorial on the Lee Dataset
End of explanation
# Set file names for train and test data
test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data'])
lee_train_file = test_data_dir + os.sep... |
420 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DTOcean Tidal Hydrodynamics Example
Note, this example assumes the Hydroynamics Module has been installed
Step1: Create the core, menus and pipeline tree
The core object carrys all the syst... | Python Code:
%matplotlib inline
from IPython.display import display, HTML
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (14.0, 8.0)
import numpy as np
from dtocean_core import start_logging
from dtocean_core.core import Core
from dtocean_core.menu import DataMenu, ModuleMenu, ProjectMenu
from dtocean... |
421 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sebastian Raschka, 2015
https
Step1: Overview
Building, compiling, and running expressions with Theano
What is Theano?
First steps with Theano
Configuring Theano
Working with array structur... | Python Code:
%load_ext watermark
%watermark -a 'Sebastian Raschka' -u -d -v -p numpy,matplotlib,theano,keras
# to install watermark just uncomment the following line:
#%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py
Explanation: Sebastian Raschka, 2015
https://github.com/rasbt/python-... |
422 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 1
The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.
This notebook ... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import time
from datetime import timedelta
import tarfile
from IPython.display import di... |
423 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing Bike-Share data with Pandas
(they're just so cute and helpful)
Grace & Tanner
1. Compute the average temperature by season ('season_desc'), fixing season error in original data.
S... | Python Code:
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
weather = pd.read_table('data/daily_weather.tsv')
weather
type(weather)
weather.groupby('season_desc')['temp'].mean()
weather.loc[weather['season_code'] == 1, 'season_desc'] = 'winter'
weather
weather.loc[weather['season_code'] == ... |
424 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: TensorFlow Addons 回调:TQDM 进度条
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 导入并归一化数据
Step3: 构... | 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... |
425 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Module for computations (if needed)
Step1: Lab 05
Step2: Analytical solutions
Step3: Simulations' data | Python Code:
import FEM_utilities as FEM
Explanation: Module for computations (if needed)
End of explanation
def write_inp_file(L, z0, nn, eltype, elname, isRiks, matname, A, E, ν, increment, t_data, F):
n_coords = np.zeros((nn,2))
for ni in range(1,nn):
n_coords[ni,:] = ni/(nn-1)*np.array([L,... |
426 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regresión en Scikit-Learn
Step1: Dataset
Cargamos los cuatro conjuntos de datos como arreglos numpy. Los datos reales corresponden a mediciones verificadas con algún instrumento. En la prác... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from semana2_datos import *
Explanation: Regresión en Scikit-Learn
End of explanation
X_1 = np.... |
427 | 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', 'cccma', 'sandbox-2', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: CCCMA
Source ID: SANDBOX-2
Topic: Seaice
Sub-Topics: Dynamics, Thermodynam... |
428 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welch's periodograms and spectrograms
Step1: Computing the power spectrum
The spectral power computes the power of the signal at a frequency. The spectral amplitude distribution is the seri... | Python Code:
%pylab inline
from matplotlib import style
style.use('fivethirtyeight')
from numpy import pi as PI
from scipy import signal
from scipy.integrate import simps
Explanation: Welch's periodograms and spectrograms
End of explanation
%ls data
Explanation: Computing the power spectrum
The spectral power computes ... |
429 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercícios
1 - Aplique os algoritmos K-means [1] e AgglomerativeClustering [2] em qualquer dataset que você desejar (recomendação
Step1: 1ª Questão
Step2: Visualização dos Dados
Step3: Ap... | Python Code:
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
Explanation: Exercícios
1 - Aplique os algoritmos K-means [1] e AgglomerativeClustering [2] em ... |
430 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OpenStreetMap is an open project, which means it's free and everyone can use it and edit as they like. OpenStreetMap is direct competitor of Google Maps. How OpenStreetMap can compete with t... | Python Code:
pipeline = [{'$match': {'address.street':{'$exists':1}}},
{'$project': {'_id': '$address.street'}},
{'$limit' : 5}]
result = db.jktosm.aggregate(pipeline)['result']
pprint.pprint(result)
Explanation: OpenStreetMap is an open project, which means it's free and everyone can use it an... |
431 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iris Dataset
From Wikipedia
Step1: read_html
Wikipedia has the same dataset as a html table at https
Step2: Plotting
Let's use pandas to plot the sepal_length vs the petal_length.
Step3: ... | Python Code:
import pandas as pd
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
df = pd.read_csv(url,names=['sepal_length',
'sepal_width',
'petal_length',
'petal_width',
'spe... |
432 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DataPack
Structure
matchzoo.DataPack is a MatchZoo native data structure that most MatchZoo data handling processes build upon. A matchzoo.DataPack consists of three parts
Step1: The main r... | Python Code:
data_pack = mz.datasets.toy.load_data()
data_pack.left.head()
data_pack.right.head()
data_pack.relation.head()
Explanation: DataPack
Structure
matchzoo.DataPack is a MatchZoo native data structure that most MatchZoo data handling processes build upon. A matchzoo.DataPack consists of three parts: left, righ... |
433 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Uncertainty quantification
R.A. Collenteur, University of Graz, WIP (May-2021)
In this notebook it is shown how to compute the uncertainty of the model simulation using the built-in uncertai... | Python Code:
import pandas as pd
import pastas as ps
import matplotlib.pyplot as plt
ps.set_log_level("ERROR")
ps.show_versions()
Explanation: Uncertainty quantification
R.A. Collenteur, University of Graz, WIP (May-2021)
In this notebook it is shown how to compute the uncertainty of the model simulation using the buil... |
434 | 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... |
435 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Silicon Forest Math Series<br/>Oregon Curriculum Network
Generators and Coroutines
Generator functions relate to generator expressions, objects which delay exectution until pressed into serv... | Python Code:
powers = (lambda x: pow(x, n) for n in range(-4,5))
phi = (1 + pow(5,0.5)) * 0.5 # golden proportion
for n, f in enumerate(powers, start=-4): # iterates through lambda expressions
print("phi ** {:2} == {:10.8f}".format(n, f(phi)))
Explanation: Silicon Forest Math Series<br/>Oregon Curriculum Network
G... |
436 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plots for Fig. 1 and Fig. 4b for Meg Urry's 2016 NSF Proposal
Grant Tremblay, Yale University
Step1: For now, I'll use the matplotlib ggplot style from R. It's pretty.
Step2: Find the data... | Python Code:
import os
import glob
import math
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import ascii
from astropy.table import vstack
from astropy import units as u
from astropy import constants as const
Explanation: Plots for Fig. 1 and Fig. 4b for Meg Urry's 2016 NSF Proposal
Grant Tremblay,... |
437 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data readout basics i.e. for some analysis or plotting.
This notebook is intended to show the readout of created hdf5 files with python. For the handling of the measured file qkit provides a... | Python Code:
## start qkit and import the needed modules. we here assume an already configured qkit analysis environment
import qkit
qkit.start()
from qkit.storage.store import Data
Explanation: Data readout basics i.e. for some analysis or plotting.
This notebook is intended to show the readout of created hdf5 files w... |
438 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to use Siphon and Cartopy to visualize data served by a THREDDS Data Server (TDS) via ncWMS
Step1: Use Siphon to get the latest run of the NCEP 2.5 km HRRR run
HRRR => High Resolution R... | Python Code:
import cartopy
import matplotlib as mpl
import matplotlib.pyplot as plt
from owslib.wms import WebMapService
from siphon.catalog import get_latest_access_url
Explanation: How to use Siphon and Cartopy to visualize data served by a THREDDS Data Server (TDS) via ncWMS
End of explanation
catalog = 'http://thr... |
439 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text Analysis and Visualization with Python and the NLTK
This notebook was originally prepared for use during a workshop called "An Introduction to Visualizing Text with Python," which took ... | Python Code:
# Get the Natural Language Processing Toolkit
import nltk
nltk.download('book') # You only need to run this command once, to get the NLTK book data.
# Get the data science package Pandas
import pandas as pd
# Get the library matplotlib for making pretty charts
import matplotlib
import matplotlib.pyplot as... |
440 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tabular data
Step1: Starting from reading this dataset, to answering questions about this data in a few lines of code
Step2: How does the survival rate of the passengers differ between sex... | Python Code:
df = pd.read_csv("data/titanic.csv")
df.head()
Explanation: Tabular data
End of explanation
df['Age'].hist()
Explanation: Starting from reading this dataset, to answering questions about this data in a few lines of code:
What is the age distribution of the passengers?
End of explanation
df.groupby('Sex')[[... |
441 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VaR computation for single risk factor / scenario set
Step1: Scenarios are already available. We will load the csv file into Spark (no Big Data here to see, move along).
Step2: Now let's c... | Python Code:
Simulation = namedtuple('Simulation', ('date', 'neutral', 'scenarios'))
RFScenario = namedtuple('RFScenario', ('rf', 'date', 'neutral', 'scenarios'))
from pyspark.mllib.linalg import Vectors, DenseVector, SparseVector, _convert_to_vector
def parse(row):
DATE_FMT = "%Y-%m-%d"
row[0] = datetime.date... |
442 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 5
Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
Step2: Interact with SVG display
SVG is a simple way of drawing vec... | Python Code:
# YOUR CODE HERE
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.html import widgets
from IPython.display import SVG, display
Explanation: Interact Exercise 5
Imports
Put the standard imports for Matplotlib, Nu... |
443 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
연습문제
아래 문제들을 해결하는 코드를 lab07.py 파일에 작성하여 제출하라.
연습 1
미국 해양대기청(NOAA)은 전세계 날씨를 실시간으로 제공한다. 한국의 경우 공항이 있는 도시의 날씨정보를 제공하며 평택도 포함된다. 평택의 현재 날씨 정보를 텍스트파일로 얻고자 하면 아래 NOAA 사이트를 클릭해서 파일을 다운로드받으면 된다.
아니... | Python Code:
import urllib
def NOAA_string():
url = "http://weather.noaa.gov/pub/data" +\
"/observations/metar/decoded/RKSG.TXT"
noaa_data_string = urllib.urlopen(url).read()
return noaa_data_string
print(NOAA_string())
def NOAA_temperature(s):
L = s.split('\n')
Line7 = L[6].split()
prin... |
444 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recognizing a Digit
In this example, we try to recognise digits of class 9 given training
examples from classes 0-8.
Step1: The $8\times 8$ images of digits are loaded from scikit-learn. An... | Python Code:
import os
from IPython.display import Image
import numpy as np
from pathlib import Path
from sklearn import metrics
cwd = os.getcwd()
os.chdir(Path(cwd).parents[1])
from lsanomaly import LSAnomaly
import lsanomaly.notebooks.digits as demo
digits = os.path.join(os.getcwd(), "lsanomaly", "notebooks", "digits... |
445 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2. Classify Manhattan with TensorFlow
In this codelab, we will use TensorFlow to train a neural network to predict whether a location is in Manhattan or not, by looking at its longitude and ... | Python Code:
import tensorflow as tf
tf.__version__
Explanation: 2. Classify Manhattan with TensorFlow
In this codelab, we will use TensorFlow to train a neural network to predict whether a location is in Manhattan or not, by looking at its longitude and latitude.
<br/>
<br/>
<br/>
Labs and Solutions
In this codelab th... |
446 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CS446/546 - Class Session 8 - Components
In this class session we are going to find the number of proteins that are in the giant component of the (undirected) protein-protein interaction net... | Python Code:
from igraph import Graph
from igraph import summary
import pandas
import numpy
Explanation: CS446/546 - Class Session 8 - Components
In this class session we are going to find the number of proteins that are in the giant component of the (undirected) protein-protein interaction network, using igraph.
End o... |
447 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data generation
Step1: Utility Methods
The below methods are used to load the data, prepare the data, parse the classifier and classification parameters, and fit and run the classifier. The... | Python Code:
from os.path import join, exists, split, sep, expandvars
from os import makedirs, getpid
from glob import glob
from shutil import rmtree
import csv
import json
import tempfile
from itertools import product
from qiime2.plugins import feature_classifier
from qiime2 import Artifact
from joblib import Paralle... |
448 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LeNet Lab
Source
Step1: The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.
However, the LeNet architecture only accepts 32x32xC images, where C is the number of color channel... | Python Code:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", reshape=False)
X_train, y_train = mnist.train.images, mnist.train.labels
X_validation, y_validation = mnist.validation.images, mnist.validation.labels
X_test, y_test = mnist.tes... |
449 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.ml - Texte et machine learning
Revue de méthodes de word embedding statistiques (~ NLP) ou comment transformer une information textuelle en vecteurs dans un espace vectoriel (features) ? ... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 2A.ml - Texte et machine learning
Revue de méthodes de word embedding statistiques (~ NLP) ou comment transformer une information textuelle en vecteurs dans un espace vectoriel (features) ? Deux exercices sont ajoutés à la fin.
En... |
450 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Fully-Connected Neural Nets
In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t... | Python Code:
# As usual, a bit of setup
from __future__ import print_function
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
fro... |
451 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
blank
Data Science meets <br/> Software Data
<b>Markus Harrer</b>, Software Development Analyst
@feststelltaste
<small>20 Jahre INNOQ Event, 13.09.2019</small>
<img src="../resources/innoq_l... | Python Code:
import pandas as pd
log = pd.read_csv("../dataset/git_log_intellij.csv.gz")
log.head()
Explanation: blank
Data Science meets <br/> Software Data
<b>Markus Harrer</b>, Software Development Analyst
@feststelltaste
<small>20 Jahre INNOQ Event, 13.09.2019</small>
<img src="../resources/innoq_logo.jpg" width=20... |
452 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training Logistic Regression via Stochastic Gradient Ascent
The goal of this notebook is to implement a logistic regression classifier using stochastic gradient ascent. You will
Step1: Load... | Python Code:
from __future__ import division
import graphlab
Explanation: Training Logistic Regression via Stochastic Gradient Ascent
The goal of this notebook is to implement a logistic regression classifier using stochastic gradient ascent. You will:
Extract features from Amazon product reviews.
Convert an SFrame int... |
453 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tabulated weak nuclear reaction rates
The reaction rate parameterizations in pynucastro/library/tabular were obtained from
Step1: Load a tabulated rate
Step2: A human readable string descr... | Python Code:
import pynucastro as pyrl
Explanation: Tabulated weak nuclear reaction rates
The reaction rate parameterizations in pynucastro/library/tabular were obtained from:
Toshio Suzuki, Hiroshi Toki and Ken'ichi Nomoto (2016):
ELECTRON-CAPTURE AND beta-DECAY RATES FOR sd-SHELL NUCLEI IN STELLAR ENVIRONMENTS RELEVA... |
454 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyses with NetworkX
Social networks have become a fixture of modern life thanks to social networking sites like Facebook and Twitter. Social networks themselves are not new, however. The ... | Python Code:
%matplotlib inline
import os
import random
import community
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from tribe.utils import *
from tribe.stats import *
from operator import itemgetter
## Some Helper constants
FIXTURES = os.path.join(os.getcwd(), "fixtures")
GRAPHML = os.pa... |
455 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DTMF
Step1: Repeating the signal ten times
Step2: Q
Step3: Check that peaks are at the correct frequencies
Step4: Processing a noisy signal
Step5: exercise | Python Code:
Fs = 32768
duration = 0.25
t = np.linspace(0, duration, duration * Fs)
f1, f2 = 697, 1336
y1 = np.sin(2 * np.pi * f1 * t);
y2 = np.sin(2 * np.pi * f2 * t);
y = (y1 + y2) / 2
plt.plot(t, y)
from IPython.display import Audio
Audio(y, rate=44100)
Explanation: DTMF: Linear combination of two sinusoids
End of e... |
456 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Curves
Curves are one of the fundamental objects in welly.
Well objects include collections of Curve objects. Multiple Well objects can be stored in a Project.
On this page, we take a closer... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import welly
welly.__version__
Explanation: Curves
Curves are one of the fundamental objects in welly.
Well objects include collections of Curve objects. Multiple Well objects can be stored in a Project.
On this page, we take a closer look at the Curve obj... |
457 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: TF-Hub CORD-19 Swivel 임베딩 살펴보기
<table class="tfo-notebook-buttons" align="l... | Python Code:
# Copyright 2019 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... |
458 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Description
In this challenge, you will be given a set of circles, defined by their centers and radii. Your goal is to find the bounding rectangle which will contain all of the circles comp... | Python Code:
from matplotlib import pyplot as plt
from matplotlib import patches as patches
from matplotlib import ticker as ticker
from math import atan, degrees, cos, sin
%matplotlib inline
Explanation: Description
In this challenge, you will be given a set of circles, defined by their centers and radii. Your goal i... |
459 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Непараметрические критерии
Критерий | Одновыборочный | Двухвыборочный | Двухвыборочный (связанные выборки)
------------- | -------------|
Знаков | $\times$ | | $\times$
Ранговый | $\... | Python Code:
import numpy as np
import pandas as pd
import itertools
from scipy import stats
from statsmodels.stats.descriptivestats import sign_test
from statsmodels.stats.weightstats import zconfint
from statsmodels.stats.weightstats import *
%pylab inline
Explanation: Непараметрические критерии
Критерий | Одновыборо... |
460 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gallery for DR6
The purpose of this notebook is to build the gallery for the sixth Legacy Survey data release, DR6. The theme of this gallery is...the NGC catalog!
For future reference
Step... | Python Code:
import os, sys
import shutil, time, warnings
from contextlib import redirect_stdout
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.table import Table, Column, vstack
from astropy.io import ascii
from P... |
461 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
K-Nearest Neighbors (KNN)
by Chiyuan Zhang and Sören Sonnenburg
This notebook illustrates the <a href="http
Step1: Let us plot the first five examples of the train data (first row) and... | Python Code:
import numpy as np
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from scipy.io import loadmat, savemat
from numpy import random
from os import path
mat = loadmat(os.path.join(SHOGUN_DATA_DIR, 'multiclass/usps.mat'))
Xall = mat['data']
Yall = np.array(mat['label'].squeeze... |
462 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MLPaint
Step1: The notebook cells below use pymldb's Connection class to make REST API calls. You can check out the Using pymldb Tutorial for more details.
Step2: ... and other Python libr... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo("WGdLCXDiDSo")
Explanation: MLPaint: Real-Time Handwritten Digits Recognizer
The automatic recognition of handwritten digits is now a well understood and studied Machine Vision and Machine Learning problem. We will be using MNIST (check out Wikipedia's ... |
463 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Local Group Halo Properties
Step1: Inside the Likelihood object is a "triplet" object called T, which contains an array of sample local groups, each with kinematic parameters consistent wit... | Python Code:
%matplotlib inline
import localgroup
import triangle
import sklearn
from sklearn import mixture
import numpy as np
import pickle
import matplotlib.patches as mpatches
Explanation: Local Group Halo Properties: Demo Inference
We approximate the local group distance, radial velocity and proper motion likeliho... |
464 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GARD data loading with WDI
Example of how to use wikidata integrator to add synonyms from GARD. GARD data has already PARTIALLY been loaded into Wikidata via Mix N Match. It is important not... | Python Code:
from wikidataintegrator import wdi_core, wdi_login
from wikidataintegrator.ref_handlers import update_retrieved_if_new_multiple_refs
import pandas as pd
from pandas import read_csv
import requests
from tqdm.notebook import trange, tqdm
import ipywidgets
import widgetsnbextension
import time
Explanation: G... |
465 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Combine train and test data for one-hot encoding
Step1: Adjust for multicollinearity
Idea
Step2: Train the model
Step3: Prediction
Step4: Combine submission | Python Code:
train["data"] = "train"
test["data"] = "test"
combined_data = pd.concat([train, test])
encoded = pd.get_dummies(combined_data[["X0", "X1", "X2", "X3", "X4", "X5", "X6", "X8"]])
drop_cat = combined_data.drop(["X0", "X1", "X2", "X3", "X4", "X5", "X6", "X8"], axis=1)
combined_data_clean = drop_cat.join(encode... |
466 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div class="alert alert-block alert-info" style="margin-top
Step1: <a id="ref0"></a>
<h2> Logistic Function </h2>
Step2: Create a tensor ranging from -10 to 10
Step3: When you use sequent... | Python Code:
import torch.nn as nn
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px">
<a href="http://cocl.us/pytorch_link_top"><img src = "http://cocl.us/Pytorch_top" width = 950, align = "center"></a>
<img src... |
467 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Day 12
Step1: Day 12.2
A function to transform terms of the form "[key]"
Step2: Track the regions to ignore
Step3: Regions to erase may come out nested. If one region to erase is included... | Python Code:
with open('inputs/input12.txt') as f_input:
s = next(f_input).rstrip()
import re
def sum_numbers(s):
p = re.compile('[-]?[\d]+')
numbers = list(map(int, p.findall(s)))
return sum(numbers)
sum_numbers(s)
Explanation: Day 12: JSAbacusFramework.io
Day 12.1
End of explanation
def transform_reds... |
468 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nurgle
"Buboes, phlegm, blood and guts! Boils, bogeys, rot and pus! Blisters, fevers, weeping sores! From your wounds the fester pours."
-- <cite>The Chant of Nurgle</cite>
The following ana... | Python Code:
from jupyterthemes.stylefx import set_nb_theme
set_nb_theme('grade3')
import os
PREFIX = os.environ.get('PWD', '.')
# PREFIX = "../build/outputs"
import numpy
import pandas
import plotly.graph_objs as go
import plotly.figure_factory as ff
from plotly.offline import init_notebook_mode, iplot
init_notebook_m... |
469 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas Data Structures
Step1: Understanding language's data structures is the most important part for a good programming experience. Poor understanding of data structures leads to poor code... | Python Code:
import numpy as np
import pandas as pd
Explanation: Pandas Data Structures
End of explanation
d = {'a':5.,'b':5.,'c':5.}
i = ['x','y','z']
s1 = pd.Series(d)
print(s1)
s1.index
Explanation: Understanding language's data structures is the most important part for a good programming experience. Poor understand... |
470 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table style="border
Step1: This last statement will make some aggregation and mutation statements look a little different to the cheat sheet as spark functions will be prefixed by F.
The s... | Python Code:
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
Explanation: <table style="border: none" align="left">
<tr style="border: none">
<th style="border: none"><img src="http://i.imgur.com/o1X3CAd.jpg" alt="Icon" align="left"></th>
</tr>
<tr style="border: none">
<th style="b... |
471 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Morphological Image Processing in Python
Tanmoy Dasgupta
thetdg@live.com | Assistant Professor | Department of Electrical Engineering | Techno India University, Kolkata
Step1: Binary Morpho... | Python Code:
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import PIL
import cv2
import skimage as sk
%pylab inline
Explanation: Morphological Image Processing in Python
Tanmoy Dasgupta
thetdg@live.com | Assistant Professor | Department of Electrical Engineering | Techno India University, Kolkat... |
472 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Crime Analytics
Step1: Initial observations
The two data sets have different set of attributes and structure and cannot be directly compared
San Fransisco data set has the additional inform... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
sanfran = pd.read_csv('sanfrancisco_incidents_summer_2014.csv')
pd.DataFrame(sanfran.columns)
seattle = pd.read_csv('seattle_incidents_summer_2014.csv'
,parse_dates=['Occurre... |
473 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exceptions
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
You've already seen some exceptions
Step1: ... | Python Code:
def divide1(numerator, denominator):
try:
result = numerator/denominator
print("result = %f" % result)
except:
print("You can't divide by 0!!")
divide1(1.0, 2)
divide1(1.0, 0)
divide1("x", 2)
Explanation: Exceptions
An exception is an event, which occurs during the execution of a ... |
474 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Pattern Roto-Translation Documentation
This notebook explains and documents the logic for generating a multispot pattern
with arbitrary translation, rotation and different X and Y pit... | Python Code:
def rotate(x, y, angle):
Rotate the point (x, y) (or array of points) with respect to the origin.
Arguments:
x, y (floats or arrays): input coordinates to be transformed.
angle (float): rotation angle in degrees. When the Y axis points
up and the X axis points right... |
475 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self Employment Data 2015
from OECD
Step1: Exercise 1
Create a barchart, which shows the selfemployment-rates for men-women by country.
Outcome should look similar to | Python Code:
countries = ['AUS', 'AUT', 'BEL', 'CAN', 'CZE', 'FIN', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ITA', 'JPN',
'KOR', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT', 'SVK', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR',
'USA', 'CHL', 'COL', 'EST', 'ISR', 'RUS', 'SVN', 'EU28', 'EA19', 'LVA']
male_selfemp... |
476 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
full_backend
debugging the full backend code
Step1: import the new haven report card module
Step2: now determine the root directory for the repo
Step3: read in the issue data from file (t... | Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
Explanation: full_backend
debugging the full backend code
End of explanation
import nhrc2
from nhrc2.backend import get_neighborhoods as get_ngbrhd
from nhrc2.backend import read_issues as ri
import pandas as pd
import numpy as np
Explanation: import th... |
477 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulated Linear Regression
Abstract
In order to understand what TensorFlow can do, here is a little demo that makes up some phony data following a certain rulw, and then fits a line to it u... | Python Code:
import numpy as np
num_points = 1000
vectors_set = []
for i in range(num_points):
x1= np.random.normal(0.0, 0.55)
y1= x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
vectors_set.append([x1, y1])
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]
Explanation: S... |
478 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Restructure Data
We will sort landmark data according to stype and organize it in a two tiered dictionary according to sample type (s) and channel (c).
Step1: Set up graph data
Step2: Grap... | Python Code:
oldlm.stype.unique()
Dlm = {}
for stype in tqdm.tqdm(oldlm.stype.unique()):
# These two lines may need to be modified based on stype structure
s = stype.split('-')[0]
c = stype.split('-')[-1]
# Add sample type dictionary if not already present
if s not in Dlm.keys():
Dlm[s]... |
479 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explanation
The HSC data is too large to store as one sqlite database file using github. So instead, it needs to be fetched by the user, separately from cloning the repository. This noteboo... | Python Code:
from __future__ import division, print_function
# give access to importing dwarfz
import os, sys
dwarfz_package_dir = os.getcwd().split("dwarfz")[0]
if dwarfz_package_dir not in sys.path:
sys.path.insert(0, dwarfz_package_dir)
import dwarfz
from dwarfz.hsc_credentials import credential
from dwarfz.hsc_... |
480 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TIS Analysis Framework Examples
This notebook provides an overview of the TIS analysis framework in OpenPathSampling. We start with the StandardTISAnalysis object, which will probably meet t... | Python Code:
%%time
storage = paths.AnalysisStorage(filename)
network = storage.networks[0]
scheme = storage.schemes[0]
stateA = storage.volumes['A']
stateB = storage.volumes['B']
stateC = storage.volumes['C']
all_states = [stateA, stateB, stateC] # all_states gives the ordering
Explanation: TIS Analysis Framework Exa... |
481 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ANLP 2015 Text Classification Assignment
Emily Scharff and Juan Shishido
Write Up
Introduction
This notebook contains the code and documentation that we used to obtain our score of 0.58541 o... | Python Code:
%matplotlib inline
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import regexp_tokenize
from nltk.stem.porter import PorterStemmer
from sklearn import cross_validation
from sklearn.feature_extraction.text im... |
482 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Importance Reweighting
Setup
First, let's set up some environmental dependencies. These just make the numerics easier and adjust some of the plotting defaults to make things more legible.
St... | Python Code:
# system functions that are always useful to have
import time, sys, os
# basic numeric setup
import numpy as np
from numpy import linalg
# inline plotting
%matplotlib inline
# plotting
import matplotlib
from matplotlib import pyplot as plt
# seed the random number generator
rstate = np.random.default_rng(5... |
483 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic
Step1: Load the train and test datasets to create two DataFrames
Step2: Print the 'head' of the train and test dataframes
Step3: Understanding your data
Step4: Rose vs Jack, or F... | Python Code:
import pandas as pd
Explanation: Titanic: Machine Learning from Disaster
Get the Data with Pandas
Import the Pandas library
End of explanation
train_url = "http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/train.csv"
train = pd.read_csv(train_url)
test_url = "http://s3.amazonaws.com/assets.datacamp... |
484 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Representation of data submission workflow components based on W3C-PROV
Step1: Model is along the concept described in https
Step2: Example name spaces
(from DOI
Step3: assign information... | Python Code:
%load_ext autoreload
%autoreload 2
from prov.model import ProvDocument
d1 = ProvDocument()
d1.deserialize?
Explanation: Representation of data submission workflow components based on W3C-PROV
End of explanation
from IPython.display import display, Image
Image(filename='key-concepts.png')
from dkrz_forms im... |
485 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 4 - Inheritance and abstraction. Graphical User Interfaces (GUIs)
Learning Objectives
Describe inheritance in the context of object oriented programming
List situations in which inherit... | Python Code:
class Item(object):
def __init__(self, name, description, location):
self.name = name
self.description = description
self.location = location
def update_location(self, new_location):
pass
class Equipment(Item):
pass
class Consumable(It... |
486 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pi Day Fun
March 14, 2016
Updated since.
Step2: Reference Pi
Step5: The Youtube above describes how to use successive primes in successive terms to build a running product that converges t... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo("HrRMnzANHHs")
Explanation: Pi Day Fun
March 14, 2016
Updated since.
End of explanation
from fractions import Fraction
from itertools import count, islice
from decimal import Decimal, localcontext
def convert(f):
get a Decimal from a Fraction (and m... |
487 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
Explanation: Generative Adversarial Network
In this notebook, we'll be building a gen... |
488 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Splunk<> Graphistry
Graphistry brings modern visual analytics to event data in Splunk. The full platform is intended for enterprise teams, while this tutorials shares visibility techniques f... | Python Code:
#splunk
SPLUNK = {
'host': 'MY.SPLUNK.com',
'scheme': 'https',
'port': 8089,
'username': 'MY_SPLUNK_USER',
'password': 'MY_SPLUNK_PWD'
}
Explanation: Splunk<> Graphistry
Graphistry brings modern visual analytics to event data in Splunk. The full platform is intended for enterprise te... |
489 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get the Data
Step1: Make the column names ints not strings for handling
Step2: Turn population into bubble sizes. Use min_size and factor to tweak.
Step3: Use pandas categories and catego... | Python Code:
fertility_df = pd.read_csv('data/fertility.csv', index_col='Country')
life_expectancy_df = pd.read_csv('data/life_expectancy.csv', index_col='Country')
population_df = pd.read_csv('data/population.csv', index_col='Country')
regions_df = pd.read_csv('data/regions.csv', index_col='Country')
Explanation: Get ... |
490 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NOAA SPC Convective Outlook
Demonstrate the use of geoJSON and shapefile data with PlotGeometry in MetPy's simplified
plotting interface. This example walks through plotting the Day 1 Convec... | Python Code:
import geopandas
from metpy.cbook import get_test_data
from metpy.plots import MapPanel, PanelContainer, PlotGeometry
Explanation: NOAA SPC Convective Outlook
Demonstrate the use of geoJSON and shapefile data with PlotGeometry in MetPy's simplified
plotting interface. This example walks through plotting th... |
491 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 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 Licens... | Python Code:
import tensorflow as tf
from tensorflow.keras.datasets import mnist
import numpy as np
import copy
Explanation: Copyright 2019 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 License at... |
492 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simplest possible example
Compute the fluxes of atmospheric leptons for a standard set of models at a fixed zenith angle.
Step1: Create an instance of an MCEqRun class. Most options are def... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
#import solver related modules
from MCEq.core import MCEqRun
import mceq_config as config
#import primary model choices
import crflux.models as pm
Explanation: Simplest possible example
Compute the fluxes of atmospheric leptons for a standard set of models... |
493 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random Forest
A single decision tree - tasked to learn a dataset - might not be able to perform well due to the outliers and the breadth and depth complexity of the data.
So instead of relyi... | Python Code:
import pandas as pd
import time
# Grab the DLA HAR dataset from the links above
# we assume that is stored in a dataset folder
#
# Load up the dataset into dataframe 'X'
#
X = pd.read_csv("../datasets/dataset-har-PUC-rio-ugulino.csv", sep=';', low_memory=False)
X.head(2)
X.describe()
Explanation: Random Fo... |
494 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GeoWave Spatial Join Demo
This demo runs a distance join using an GPX dataset for Germany and the GDELT dataset. We use this demo to run a distance join using our tiered join algorithm on tw... | Python Code:
#!pip install --user --upgrade pixiedust
#Stop old session
spark.stop()
Explanation: GeoWave Spatial Join Demo
This demo runs a distance join using an GPX dataset for Germany and the GDELT dataset. We use this demo to run a distance join using our tiered join algorithm on two large datasets to get what GPX... |
495 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex SDK
Step1: Install the Google cloud-storage library as well.
Step2: Restart the Kernel
Once you've installed the Vertex SDK and Google cloud-storage, you need to restart the noteboo... | Python Code:
! pip3 install -U google-cloud-aiplatform --user
Explanation: Vertex SDK: AutoML natural language text classification model
Installation
Install the latest (preview) version of Vertex SDK.
End of explanation
! pip3 install google-cloud-storage
Explanation: Install the Google cloud-storage library as well.
... |
496 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with CTF data
Step1: To reduce memory consumption and running time, some of the steps are
precomputed. To run everything from scratch change use_precomputed to
False. With use_preco... | Python Code:
# Authors: Mainak Jas <mainak.jas@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#
# License: BSD-3-Clause
import os.path as op
import pandas as pd
import numpy as np
import mne
from mne import combine_evoked
from mne.minimum_n... |
497 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <a href="https
Step2: adjust_brightness
Shifts the brightness of an RGB image by a given amount
Step3: adjust_contrast
Adjusts the contrast of an RGB image by a given multiplicative... | Python Code:
%%capture
!pip install dm-pix
!git clone https://github.com/deepmind/dm_pix.git
import dm_pix as pix
import jax.numpy as jnp
import numpy as np
import PIL.Image as pil
from jax import random
IMAGE_PATH = '/content/dm_pix/examples/assets/jax_logo.jpg'
# Helper functions to read images and display them
def g... |
498 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Romania Kendo Stats
25 years of Kendo History in Romania, visualized
Data cleaning workbook
Created by Dénes Csala | 2019 | MIT License
For any improvement suggestions and spotted processin... | Python Code:
import pandas as pd, numpy as np, json
import members_loader, matches_loader, clubs_loader, point_utils, save_utils
Explanation: Romania Kendo Stats
25 years of Kendo History in Romania, visualized
Data cleaning workbook
Created by Dénes Csala | 2019 | MIT License
For any improvement suggestions and spott... |
499 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TV Script Generation
In this project, we'll generate our own Simpsons TV scripts using RNNs. We'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Network you'... | Python Code:
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, we'll generate our own Simpsons TV scripts using RNNs. We'll be using part of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.