Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
12,300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test divergence and curl module
This document present tests on divergence and curl module calculation using pygsf.
Preliminary settings
The modules to import for dealing with grids are
Step1... | Python Code:
from pygsf.mathematics.arrays import *
from pygsf.spatial.rasters.geotransform import *
from pygsf.spatial.rasters.fields import *
Explanation: Test divergence and curl module
This document present tests on divergence and curl module calculation using pygsf.
Preliminary settings
The modules to import for d... |
12,301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supervised Learning
Step1: Now, as data scientists we dont know this relationship between y and x. Rather we have collected observations of y. These observations are bound to have some err... | Python Code:
# import libraries
import matplotlib
import IPython
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import pylab
import seaborn as sns
import sklearn as sk
%matplotlib inline
Explanation: Supervised Learning : Population line, estimator, overfitting
Let's exp... |
12,302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text classification for SMS spam detection
Outline
Step1: Training a Classifier on Text Features
We can now train a classifier, for instance a Multinomial Naive Bayesian classifier which is... | Python Code:
!head "datasets/smsspam/SMSSpamCollection"
import os
with open(os.path.join("datasets", "smsspam", "SMSSpamCollection")) as f:
lines = [line.strip().split("\t") for line in f.readlines()]
text = [x[1] for x in lines]
y = [x[0] == "ham" for x in lines]
text[:10]
y[:10]
type(text)
type(y)
from sklearn.cr... |
12,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Introduction to scikit-learn
Scikit-learn is a machine learning library in Python.
Scikit-learn is the first of the several machine learning libraries we will explore ... | Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribute... |
12,304 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Programming Microblaze Subsystems from Jupyter
In the Base I/O overlays that accompany the PYNQ release Microblazes are used to control peripherals attached to the various connectors. These ... | Python Code:
from pynq.overlays.base import BaseOverlay
base = BaseOverlay('base.bit')
Explanation: Programming Microblaze Subsystems from Jupyter
In the Base I/O overlays that accompany the PYNQ release Microblazes are used to control peripherals attached to the various connectors. These can either be programmed with ... |
12,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GIScript-开放地理空间信息处理与分析Python库
GIScript是一个开放的地理空间心处理与分析Python框架,GIS内核采用SuperMap UGC封装,集成多种开源软件,也可以使用其它的商业软件引擎。
by wangerqi@supermap.com, 2016-05-03。
本文档介绍GIScript的安装和配置,并进行简单的运行测试,以确认安装的软件正常... | Python Code:
from PyUGC import *
from PyUGC.Stream import UGC
from PyUGC.Base import OGDC
from PyUGC import Engine
from PyUGC import FileParser
from PyUGC import DataExchange
import datasource
Explanation: GIScript-开放地理空间信息处理与分析Python库
GIScript是一个开放的地理空间心处理与分析Python框架,GIS内核采用SuperMap UGC封装,集成多种开源软件,也可以使用其它的... |
12,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
同時方程式体系
『Rによる計量経済学』第10章「同時方程式体系」をPythonで実行する。
テキスト付属データセット(「k1001.csv」等)については出版社サイトよりダウンロードしてください。
また、以下の説明は本書の一部を要約したものですので、より詳しい説明は本書を参照してください。
例題10.1
次のような供給関数と需要関数を推定する。
$Q_{t} = \alp... | Python Code:
%matplotlib inline
# -*- coding:utf-8 -*-
from __future__ import print_function
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.sandbox.regression.gmm import IV2SLS
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# データ読み込み
data = pd.rea... |
12,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading the model.
Step1: Loading the dataset
Step2: The TensorFlow graph
Look at all operations to find out the ones that are interesting for weights/activations.
Step3: TensorFlow expos... | Python Code:
# Restore model.
sess = tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('tf_mnist_model_layers/tf_mnist_model.ckpt.meta')
saver.restore(sess,tf.train.latest_checkpoint('tf_mnist_model_layers/'))
Explanation: Loading the model.
End of explanation
dataset ... |
12,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Symbulate Documentation
Random Processes
<a id='contents'></a>
RandomProcess and TimeIndex
Defining a RandomProcess explicitly as a function of time
Process values at particular time points
... | Python Code:
from symbulate import *
%matplotlib inline
Explanation: Symbulate Documentation
Random Processes
<a id='contents'></a>
RandomProcess and TimeIndex
Defining a RandomProcess explicitly as a function of time
Process values at particular time points
Mean function
Defining a RandomProcess incrementally
< Condit... |
12,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network ... |
12,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
StyleGAN2
Step1: Load stylegan
You can see what pre-trained models are available with stylegan2.get_pretrained_models.
Step2: The variable network_pkl refers to the location of the trained... | Python Code:
%tensorflow_version 1.x
!pip3 install --quiet ml4a
Explanation: StyleGAN2: hi-res generative modeling
StyleGAN2 is a generative model architecture which generates state-of-the-art, high-resolution images. This module is based on the original code and paper by NVIDIA, and comes with several pre-trained mode... |
12,311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a recommendation model for Google Analytics data using BigQuery ML
This notebook accompanies the article
Training a recommendation model for Google Analytics data using BigQuery ML
... | Python Code:
%%bigquery df
WITH CTE_visitor_content_time AS (
SELECT
fullVisitorID AS visitorId,
visitNumber,
(SELECT MAX(IF(index=10, value, NULL)) FROM UNNEST(hits.customDimensions)) AS latestContentId,
hits.time AS hit_time
FROM
`cloud-training-demos.GA360_test.ga_sess... |
12,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyGSLIB
Introduction
This is a simple example on how to use raw pyslib to compute variograms with gridded data
Step1: Getting the data ready for work
You can use Pandas to import your data ... | Python Code:
#general imports
import matplotlib.pyplot as plt
import pygslib
#make the plots inline
%matplotlib inline
Explanation: PyGSLIB
Introduction
This is a simple example on how to use raw pyslib to compute variograms with gridded data
End of explanation
#get the data in GSLIB format into a pandas D... |
12,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is my fourth 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 ... | Python Code:
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 fourth attempt at creating a model using sklearn alogithms
In this iteration of analysis we'll be... |
12,314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CS224U Homework 5
This homework is distributed in three content-identical formats (html, py, ipynb) as part of the SippyCup codebase. All seven problems are required. You're encouraged to tu... | Python Code:
from arithmetic import ArithmeticDomain
from parsing import parse_to_pretty_string
# Import the domain and make sure all is well:
math_domain = ArithmeticDomain()
# Core grammar:
math_grammar = math_domain.grammar()
# A few examples:
parses = math_grammar.parse_input("minus two plus three")
for parse in pa... |
12,315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word2Vec
Learning Objectives
Compile all steps into one function
Prepare training data for Word2Vec
Model and Training
Embedding lookup and analysis
Introduction
Word2Vec is not a singular a... | Python Code:
# Use the chown command to change the ownership of repository to user.
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
!pip install -q tqdm
# You can use any Python source file as a module by executing an import statement in some other Python source file.
# The import statement combines ... |
12,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
the orange slope is the most important and you expect a slope of around -1 unless you work with cells badly synchronized or with weird karyotype
resolution= size of bins
Step1: In Y we have... | Python Code:
from pytadbit.mapping.analyze import plot_genomic_distribution
plot_genomic_distribution("results/HindIII/03_filtering/reads12.tsv", resolution=500000, show=True)
Explanation: the orange slope is the most important and you expect a slope of around -1 unless you work with cells badly synchronized or with we... |
12,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Init config
Select appropriate
Step1: Count number of tweets per day for every news, calculate cummulative diffusion
Step2: Plot diffusion for every day for all news together
Step3: Plot ... | Python Code:
client = pymongo.MongoClient("46.101.236.181")
db = client.allfake
# get collection names
collections = sorted([collection for collection in db.collection_names()])
Explanation: Init config
Select appropriate:
- database server (line 1): give pymongo.MongoClient() an appropriate parameter, else it is local... |
12,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing PHOEBE 2 vs PHOEBE Legacy
NOTE
Step1: As always, let's do imports and initialize a logger and a new bundle.
Step2: Adding Datasets and Compute Options
Step3: Let's add compute o... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: Comparing PHOEBE 2 vs PHOEBE Legacy
NOTE: PHOEBE 1.0 legacy is an alternate backend and is not installed with PHOEBE 2. In order to run this backend, you'll need to have PHOEBE 1.0 installed and manually build the python bindings in the phoebe-py directory.... |
12,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification
$$
\renewcommand{\like}{{\cal L}}
\renewcommand{\loglike}{{\ell}}
\renewcommand{\err}{{\cal E}}
\renewcommand{\dat}{{\cal D}}
\renewcommand{\hyp}{{\cal H}}
\renewcommand{\Ex}[... | Python Code:
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import pandas as pd
pd.set_option('display.width', 500)
pd.set_option('display.max_columns', 100)
pd.set_option('display.... |
12,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer learning
In the previous exercise we introduced the TinyImageNet-100-A dataset, and combined a handful of pretrained models on this dataset to improve our classification performance... | Python Code:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
from time import time
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading extenrnal modules
# ... |
12,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'messy-consortium', 'emac-2-53-aerchem', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: MESSY-CONSORTIUM
Source ID: EMAC-2-53-AERCHEM
Topic: Land
S... |
12,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: get email of author
compare to list of known persons of interest
return boolean if author is person of interest
aggregate count over all emails to person
Step2: Beware of BUGS!!!
Whe... | Python Code:
from __future__ import division
data_point = data_dict['METTS MARK']
frac = data_point["from_poi_to_this_person"] / data_point["to_messages"]
print frac
def computeFraction( poi_messages, all_messages ):
given a number messages to/from POI (numerator)
and number of all messages to/from a pers... |
12,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ... | Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment_network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment_network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent ... |
12,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wiki2vec
Jupyter notebook for creating a Word2vec model from a Wikipedia dump. This model file can then be read into gensim's Word2Vec class. Feel free to edit this script as you see fit.
De... | Python Code:
WIKIPEDIA_DUMP_PATH = './data/wiki-corpuses/enwiki-latest-pages-articles.xml.bz2'
# Choose a path that the word2vec model should be saved to
# (during training), and read from afterwards.
WIKIPEDIA_W2V_PATH = './data/enwiki.model'
Explanation: Wiki2vec
Jupyter notebook for creating a Word2vec model from a ... |
12,325 | 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.function 提高性能
<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... |
12,326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Splitting a simulation
Included in this notebook
Step1: The optimum way to use storage depends on whether you're doing production or analysis. For analysis, you should open the file as an A... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import openpathsampling as paths
import numpy as np
Explanation: Splitting a simulation
Included in this notebook:
Split a full simulation file into trajectories and the rest
End of explanation
%%time
storage = paths.AnalysisStorage("mstis.nc")
st_split = ... |
12,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Activation Maximization on MNIST
Lets build the mnist model and train it for 5 epochs. It should get to about ~99% test accuracy.
Step1: Dense Layer Visualizations
To visualize activation o... | Python Code:
from __future__ import print_function
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Activation, Input
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
batch_size = 128... |
12,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ePSproc LF/AF function verification & tests
26/06/20 v2
19/06/20 v1
For LF and AF calculations, trying to get to the bottom of issues with magnitudes and/or phases and/or formalism differenc... | Python Code:
# Imports
import numpy as np
import pandas as pd
import xarray as xr
# Special functions
# from scipy.special import sph_harm
import spherical_functions as sf
import quaternion
# Performance & benchmarking libraries
# from joblib import Memory
# import xyzpy as xyz
import numba as nb
# Timings with ttictoc... |
12,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotly maps
with Plotly's Python API library and Basemap
This notebook comes in response to <a href="https
Step1: From root
Step2: Import the plotly graph objects (in particular Contour) t... | Python Code:
import plotly
plotly.__version__
Explanation: Plotly maps
with Plotly's Python API library and Basemap
This notebook comes in response to <a href="https://twitter.com/rjallain/status/496767038782570496" target="_blank">this</a> Rhett Allain tweet.
Although Plotly does not feature built-in maps functionalit... |
12,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regular Expressions in Python (A Short Tutorial)
This is a tutorial showing how regular expressions are supported in Python.
The assumption is that the reader already has a grasp of the conc... | Python Code:
import re
Explanation: Regular Expressions in Python (A Short Tutorial)
This is a tutorial showing how regular expressions are supported in Python.
The assumption is that the reader already has a grasp of the concept of
regular expressions as it is taught in lectures
on formal languages, for example in
... |
12,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Prediction
Objectives
1. Build a linear, DNN and CNN model in Keras.
2. Build a simple RNN model and a multi-layer RNN model in Keras.
In this lab we will start with a linear, ... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
!pip install --user google-cloud-bigquery==1.25.0
Explanation: Time Series Prediction
Objectives
1. Build a linear, DNN and CNN model in Keras.
2. Build a simple RNN model and a multi-layer RNN model in Keras.
In this lab we will start wi... |
12,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Neural Structured Learning Authors
Step1: 合成グラフを使ってセンチメント分類を実施するためのグラフ正則化
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="http... | 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... |
12,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <img src="images/utfsm.png" alt="" width="200px" align="right"/>
USM Numérica
Librería numpy
Objetivos
Conocer la librería numpy y su aplicación para cálculo numérico.
Aprender las di... | Python Code:
IPython Notebook v4.0 para python 3.0
Librerías adicionales: numpy, matplotlib
Contenido bajo licencia CC-BY 4.0. Código bajo licencia MIT.
(c) Sebastian Flores, Christopher Cooper, Alberto Rubio, Pablo Bunout.
# Configuración para recargar módulos y librerías dinámicamente
%reload_ext autoreload
%autorel... |
12,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The perceptron - limitations
<div>Table of contents</div>
<div id="toc"></div>
Step1: As in the previous simulation we implement a very simple network. It will only have two input units plu... | Python Code:
%matplotlib inline
from pylab import *
from utils import *
Explanation: The perceptron - limitations
<div>Table of contents</div>
<div id="toc"></div>
End of explanation
#-------------------------------------------------
# Training
# Constants
# Number of input elements
n = 2
# Learning rate
eta = ... |
12,335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homogeneous Gas
Here is a notebook for homogeneous gas model.
Here we are talking about a homogeneous gas bulk of neutrinos with single energy. The EoM is
$$
i \partial_t \rho_E = \left[ \fr... | Python Code:
# This line configures matplotlib to show figures embedded in the notebook,
# instead of opening a new window for each figure. More about that later.
# If you are using an old version of IPython, try using '%pylab inline' instead.
%matplotlib inline
%load_ext snakeviz
import numpy as np
from scipy.optimi... |
12,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
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', 'sandbox-1', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: SANDBOX-1
Topic: Ocnbgchem
Sub-Topics: Trac... |
12,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
\title{myHDL to PYNQ Fabric Only Exsample}
\author{Steven K Armour}
\maketitle
Refrances
Libraries and Helper functions
Step2: Project 1
Step3: myHDL Testing
Step4: Verilog Code
Step5: \... | Python Code:
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sympy import *
init_printing()
import random
#https://github.com/jrjohansson/version_information
%load_ext version_information
%version_information myhdl, myhdlpee... |
12,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Plots
Step1: Duncan's Prestige Dataset
Load the Data
We can use a utility function to load any R dataset available from the great <a href="http
Step2: Influence plots
Influence ... | Python Code:
%matplotlib inline
from __future__ import print_function
from statsmodels.compat import lzip
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.formula.api import ols
Explanation: Regression Plots
End of explanation
prestige = sm.datasets.ge... |
12,339 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 07 - Non linear Elliptic problem
Keywords
Step1: 3. Affine Decomposition
For this problem the affine decomposition is straightforward
Step2: 4. Main program
4.1. Read the mesh for... | Python Code:
from dolfin import *
from rbnics import *
Explanation: Tutorial 07 - Non linear Elliptic problem
Keywords: exact parametrized functions, POD-Galerkin
1. Introduction
In this tutorial, we consider a non linear elliptic problem in a two-dimensional spatial domain $\Omega=(0,1)^2$. We impose a homogeneous Dir... |
12,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Object Oriented Programming
What is an Object?
First some semantics
Step1: Note the reference to object, this means that our new class inherits from object. We won't be going into too much ... | Python Code:
class A(object):
pass
Explanation: Object Oriented Programming
What is an Object?
First some semantics:
- An object is essentially a container which holds some data, and crucially some associated methods for working with that data.
- We define objects, and their behaviours, using something called a ... |
12,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quick Reference Guide to NLTK
In progress...
<span style="float
Step1: Ex.3. Similar tokens
Step2: Ex.2. Common Context
Step3: Ex.3. Dispersion Plot
Step4: Ex.4. Calculate Text Diversity... | Python Code:
import nltk
from __future__ import division
import matplotlib as mpl
from matplotlib import pyplot as plt
from nltk.book import *
from nltk.corpus import brown
from nltk.corpus import udhr
from nltk.corpus import wordnet as wn
from numpy import arange
import networkx as nx
%matplotlib inline
Explanation: Q... |
12,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Under Construction!
Working with External Web Services
This example shows how to use external services to set up Cytoscape session with pathways
Cytoscape 3.2.0 beta
KEGGScape 0.7.x
cy-rest ... | Python Code:
import requests
import json
import pandas as pd
import io
from IPython.display import Image
# Basic Setup
PORT_NUMBER = 1234
BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/'
# KEGG API
KEGG_API_URL = 'http://rest.kegg.jp/'
# Header for posting data to the server as JSON
HEADERS = {'Content-Type': 'ap... |
12,343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Traffic Accidents by San Diego Community
This analysis links traffic accident records from SWITRS to San Diego planning communities to see which communityies have the most traffoc accidents.... | Python Code:
import seaborn as sns
import metapack as mp
import pandas as pd
import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
from shapely.geometry import Point
%matplotlib inline
sns.set_context('notebook')
pkg = mp.jupyter.open_package()
#pkg = mp.jupyter... |
12,344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rover Project Test Notebook
This notebook contains the functions that provide the scaffolding needed to test out mapping methods. The following steps are taken to test functions and calibra... | Python Code:
#%%HTML
#<style> code {background-color : orange !important;} </style>
%matplotlib inline
#%matplotlib qt # Choose %matplotlib qt to plot to an interactive window
import cv2 # OpenCV for perspective transform
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import scipy.... |
12,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MAT245 Lab 5 - Linear Regression
Overview
Regression analysis is a set of statistical techniques for modelling the relationships between a dependent variable and a set of independent (or pre... | Python Code:
from sklearn import datasets
bost = datasets.load_boston()
bost.keys()
bost.data.shape
Explanation: MAT245 Lab 5 - Linear Regression
Overview
Regression analysis is a set of statistical techniques for modelling the relationships between a dependent variable and a set of independent (or predictor) variables... |
12,346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q3
This question will focusing on looping and using dictionaries.
Part A
In this part, you'll write a safe version of testing a dictionary for a specific key and extracting the corresponding... | Python Code:
v1 = safe_access({"one": [1, 2, 3], "two": [4, 5, 6], "three": "something"}, "three")
assert v1 == "something"
v2 = safe_access({"one": [1, 2, 3], "two": [4, 5, 6], "three": "something"}, "two", [10, 11, 12])
assert set(v2) == set((4, 5, 6))
default_val = 3
try:
value = safe_access({"one": 1, "two": 2}... |
12,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setting up the data
The plot animates with the slider showing the data over time from 1964 to 2013. We can think of each year as a seperate static plot, and when the slider moves, we use the... | Python Code:
fertility_df, life_expectancy_df, population_df_size, regions_df, years, regions_list = process_data()
sources = {}
region_name = regions_df.Group
region_name.name = 'region'
for year in years:
fertility = fertility_df[year]
fertility.name = 'fertility'
life = life_expectancy_df[year]
life.... |
12,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 8</font>
Download
Step1: Statsmodels
Linear Regression Models
Step2: Time-Series Analysis | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 8</font>
Download: http://github.com/dsacademybr
End of explanation
# Par... |
12,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unsupervised learning
In unsupervised learning problems, we only have
input data x(i) with no labels, and we want the algorithm to find some structure in the data. A clustering
algorithm suc... | Python Code:
from sklearn.datasets import make_blobs
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
plt.figure(figsize=(12, 12))
n_samples = 1500
random_state = 1760
X, y = make_blobs(n_samples=n_samples, random_state=random_state)
kmeans = KMeans(n_clusters=3)
kmeans.fit_predict(... |
12,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
El Oscilador armonico.
Dibujamos el espacio de fases para la ecuacion $$\ddot{x} = -\omega^2x$$
Para eso lo pasamos a un sistema
Step1: El Pendulo
Dibujamos el espacio de fases para la ecua... | Python Code:
@interact(xin=(-5,5,0.1),yin=(-5,5,0.1))
def plotInt(xin,yin):
xmax = 2
vmax = 5
x = linspace(-xmax, xmax, 15) # Definimos el rango en el que se mueven las variables y el paso
v = linspace(-vmax, vmax, 15)
X, V = meshgrid(x,v) # Creamos una grilla con eso
# Definimos las constantes... |
12,351 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Example from Think Stats
http
Step4: Central Limit Theorem
If you add up independent variates from a distribution with finite mean and variance, the sum converges on a normal distrib... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def decorate(**options):
Decorate the current axes.
Call decorate with keyword arguments like
decorate(title='Title',
xlabel='x',
ylabel='y')
The keyword arguments can be any ... |
12,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 2 - Stepping up with SciPy
Numpy is a powerful, yet very basic library, which can be a little abstract to introduce -- and a little tedious to practice. To perform more interesting t... | Python Code:
import scipy as sp
Explanation: Chapter 2 - Stepping up with SciPy
Numpy is a powerful, yet very basic library, which can be a little abstract to introduce -- and a little tedious to practice. To perform more interesting things to Numpy matrices, we now turn to a number of interesting libraries, which have... |
12,353 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train Model on Distributed Cluster
IMPORTANT
Step1: Start Server "Task 0" (localhost
Step2: Start Server "Task 1" (localhost
Step3: Define Compute-Heavy TensorFlow Graph
Step4: Define Sh... | Python Code:
import tensorflow as tf
cluster = tf.train.ClusterSpec({"local": ["localhost:2222", "localhost:2223"]})
Explanation: Train Model on Distributed Cluster
IMPORTANT: You Must STOP All Kernels and Terminal Session
The GPU is wedged at this point. We need to set it free!!
Define ClusterSpec
End of explanation... |
12,354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TUTORIAL coupling NPZD2 and Mussels
First create a new file by "Saving-as" NPDZ.py witha new name... lets call the new file NPZD2_Mussels.py
From now on, we are going to copy-paste from Muss... | Python Code:
# Parameters
par = {}
par['mu0'] = 0.69
par['kNO3'] = 0.5
par['kNH4'] = 0.5
par['alpha'] = 0.125
par['gmax'] = 0.6 #Original 0.6
par['kP'] = 0.44
par['mP'] = 0.15
par['tau'] = 0.005
par['thetaMax'] = 0.053
par['beta'] ... |
12,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing clusters in Python
I am wanting to see the results of clustering methods such as K-Means; this is my playground.
Initial examples are taken from K Means Clustering in Python
Step... | Python Code:
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cluster import KMeans
import sklearn.metrics as sm
import pandas as pd
import numpy as np
# Only needed if you want to display your plots inline if using Notebook
# change inline to auto if you have Spyder installed
%matplotlib inlin... |
12,356 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Case Study 1
Step4: Report some statistics about the tweets you collected
The topic of interest
Step5: 2. Find the most popular tweets in your collection of tweets
Please plot a ta... | Python Code:
# HELPER FUNCTIONS
import io
import json
import twitter
def oauth_login(token, token_secret, consumer_key, consumer_secret):
Snag an auth from Twitter
auth = twitter.oauth.OAuth(token, token_secret,
consumer_key, consumer_secret)
return auth
def save_jso... |
12,357 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load Training and Test Data
In this section, the training/validation data is loaded. The load_data function pre-balances the data set by removing images from over-represented emotion classes... | Python Code:
metaData, meta2, mCounts = bc.load_training_metadata(trainDataPath, balanceViaRemoval=True, verbose=True,
normalVsAbnormal=normalVsAbnormal)
# Actually load some representative data for model experimentation
maxData = len(metaData)
X_data, Y_data = bc.l... |
12,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning Bootcamp November 2017, GPU Computing for Data Scientists
<img src="images/bcamp.png" align="center">
Using CUDA, Jupyter, PyCUDA and PyTorch
03 PyCUDA Sigmoid()
Web
Step2: Si... | Python Code:
# !pip install pycuda
%reset -f
import pycuda
from pycuda import compiler
import pycuda.driver as cuda
import numpy
import numpy as np
from pycuda.compiler import SourceModule
cuda.init()
print("%d device(s) found." % cuda.Device.count())
for ordinal in range(cuda.Device.count()):
dev = cuda... |
12,359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncc', 'sandbox-3', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: NCC
Source ID: SANDBOX-3
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy ... |
12,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fully developed baroclinic instability of a 3-layer flow
Step1: Set up
Step2: Initial condition
Step3: Run the model
Step4: A snapshot and some diagnostics | Python Code:
import numpy as np
from numpy import pi
from matplotlib import pyplot as plt
%matplotlib inline
import pyqg
Explanation: Fully developed baroclinic instability of a 3-layer flow
End of explanation
L = 1000.e3 # length scale of box [m]
Ld = 15.e3 # deformation scale [m]
kd = 1./Ld #... |
12,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Примеры анализа данных аэрокосмической съемки
Дмитрий Колесов (kolesov.dm@gmail.com)
NextGIS
О чем пойдет речь
Что это за такие "Данные аэрокосмической съемки"
Как их обрабатывать
На чем мож... | Python Code:
import numpy as np
import pandas as pd
points = pd.read_csv('rand.txt')
points.tail()
y = points["class"]
X = points[['r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10', 'r11']]
# Разбиваем на обучающее и тестовое множества:
from sklearn.model_selection import train_test_split
X_train, X_test, y_t... |
12,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nested Statements and Scope
Now that we have gone over on writing our own functions, its important to understand how Python deals with the variable names you assign. When you create a variab... | Python Code:
x = 25
def printer():
x = 50
return x
print x
print printer()
Explanation: Nested Statements and Scope
Now that we have gone over on writing our own functions, its important to understand how Python deals with the variable names you assign. When you create a variable name in Python the name is stor... |
12,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 4
This project is for deep MNIST for experts.
Step1: Build a Multilayer Convolutional Network
This section will help to build more complex model thant the previous linear model(with... | Python Code:
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
################## build a softmax regression model
# input data
x = tf.placeholder(tf.float32, shape = [None, 784])
# real labels
y_ = tf.placeholder(tf.float3... |
12,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
17
Step1: For this example, we're going to re-create model 17 from the
Self Instructing Manual. (pp. 128)
Step2: We will use the usual choice and availability variables.
Step3: The "totco... | Python Code:
# TEST
import larch.numba as lx
import larch
import pandas as pd
pd.set_option("display.max_columns", 999)
pd.set_option('expand_frame_repr', False)
pd.set_option('display.precision', 3)
larch._doctest_mode_ = True
Explanation: 17: MTC Expanded MNL Mode Choice
End of explanation
import larch.numba as lx
d ... |
12,365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tut_artifacts_reject
Step1: .. _marking_bad_channels
Step2: Why setting a channel bad?
Step3: Let's now interpolate the bad channels (displayed in red above)
Step4: Let's plot the cl... | Python Code:
import numpy as np
import mne
from mne.datasets import sample
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname)
Explanation: .. _tut_artifacts_reject:
Rejecting bad data (channels and segments)
End of explanation
raw.in... |
12,366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HMM with Poisson observations for detecting changepoints in the rate of a signal
This notebook is based on the
Multiple Changepoint Detection and Bayesian Model Selection Notebook of TensorF... | Python Code:
from IPython.utils import io
with io.capture_output() as captured:
!pip install -qq distrax
!pip install -qq flax
import logging
logging.getLogger("absl").setLevel(logging.CRITICAL)
import numpy as np
import jax
from jax.random import split, PRNGKey
import jax.numpy as jnp
from jax import jit, lax,... |
12,367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring multidimensional data using xray
Here is a little graphical representation of the way to think about this data. For clarification on how multidimensional data are represented in xr... | Python Code:
from IPython.display import Image
Image(url='http://xray.readthedocs.org/en/latest/_images/dataset-diagram.png', embed=True, width=950, height=300)
Explanation: Exploring multidimensional data using xray
Here is a little graphical representation of the way to think about this data. For clarification on how... |
12,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 4
Step1: Polynomial regression, revisited
We build on the material from Week 3, where we wrote the function to produce an SFrame with columns containing the powers of a give... | Python Code:
import graphlab as gl
import numpy as np
Explanation: Regression Week 4: Ridge Regression (interpretation)
In this notebook, we will run ridge regression multiple times with different L2 penalties to see which one produces the best fit. We will revisit the example of polynomial regression as a means to see... |
12,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stationarity and detrending (ADF/KPSS)
Stationarity means that the statistical properties of a time series i.e. mean, variance and covariance do not change over time. Many statistical models... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
Explanation: Stationarity and detrending (ADF/KPSS)
Stationarity means that the statistical properties of a time series i.e. mean, variance and covariance do not change over time. Many sta... |
12,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Timestamps are contained in the Space Packet secondary header time code field. They are encoded as big-endian 32-bit integers counting the number of seconds elapsed since the J2000 epoch (20... | Python Code:
def timestamps(packets):
epoch = np.datetime64('2000-01-01T12:00:00')
t = np.array([struct.unpack('>I', p[ccsds.SpacePacketPrimaryHeader.sizeof():][:4])[0]
for p in packets], 'uint32')
return epoch + t * np.timedelta64(1, 's')
def load_frames(path):
frame_size = 223 * 5 - ... |
12,371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building a Random Forest Classification Model for NFL Decisions
Game Time Decisions
Its 1st and Goal with less than a minute on the clock in the 4th quarter. Your team is down by 3 points, w... | Python Code:
# Testing "min_samples_leaf"
min_samples_leaf = [1,3,6,9,12,15,18,22,25,50,75,100,125,150,175,200,225,250,275,300]
n_estimators = [30]
min_samples_leaf_scores = []
for n in n_estimators:
print('-' * 40)
for l in min_samples_leaf:
print('--- Testing', '({},{})'.format(n,l))
start = t... |
12,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
IPython, pandas and matplotlib have a number of useful options you can use to make it easier to view and format your data. This notebook collects a bunch of them in one place. I... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Introduction
IPython, pandas and matplotlib have a number of useful options you can use to make it easier to view and format your data. This notebook collects a bunch of them in one place. I hope this wil... |
12,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning Bootcamp November 2017, GPU Computing for Data Scientists
<img src="../images/bcamp.png" align="center">
13 PyTorch Logistic Regression
Web
Step1: Load a CSV file for Binary ... | Python Code:
# !pip install pycuda
%reset -f
import numpy
import numpy as np
from __future__ import print_function
from __future__ import division
import math
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd
import os
import torch
from torch.utils.data.dataset import Dataset
fro... |
12,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this week's homework assignment we want you to start playing around with different classifiers and try to submit a prediction to the Kaggle competition. Nothing fancy, just so you won't t... | Python Code:
# Import all required libraries
from __future__ import division # For python 2.*
import numpy as np
import matplotlib.pyplot as plt
import mltools as ml
np.random.seed(0)
%matplotlib inline
Explanation: In this week's homework assignment we want you to start playing around with different classifiers and tr... |
12,375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Merging annotations from tiled arrays
Overview
Step1: 1. Connect girder client and set parameters
Step2: 2. Polygon merger
The Polygon_merger() is the top level function for performing the... | Python Code:
import os
CWD = os.getcwd()
import os
import girder_client
from pandas import read_csv
from histomicstk.annotations_and_masks.polygon_merger import Polygon_merger
from histomicstk.annotations_and_masks.masks_to_annotations_handler import (
get_annotation_documents_from_contours, )
Explanation: Merging ... |
12,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading the data
Step1: Cleaning
Step2: Most bought product
Step3: Most of the reviews (68%) are rated 5
Step4: Separate what's Positive and what's Negative
Step5: This data is imbalanc... | Python Code:
products = pd.read_csv('amazon_baby.csv')
products.head()
products.count()
products.shape
def cleanNaN(value):
if pd.isnull(value):
return ""
else:
return value
Explanation: Loading the data
End of explanation
products['review'] = products['review'].apply(cleanNaN)
products['name'] ... |
12,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This script shows how to use the existing code in opengrid to create a baseload electricity consumption benchmark.
Step1: Script settings
Step2: We create one big dataframe, the columns ar... | Python Code:
import os
import sys
import inspect
import numpy as np
import datetime as dt
import time
import pytz
import pandas as pd
import pdb
import tmpo
#import charts
from opengrid import config
from opengrid.library import houseprint
c=config.Config()
DEV = c.get('env', 'type') == 'dev' # DEV is True if we are in... |
12,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Neural Networks
Step1: Run the next cell to load the "SIGNS" dataset you are going to use.
Step2: As a reminder, the SIGNS dataset is a collection of 6 signs representing num... | Python Code:
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from cnn_utils import *
%matplotlib inline
np.random.seed(1)
Explanation: Convolutional Neural Networks... |
12,379 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to optimization
The basic components
The objective function (also called the 'cost' function)
Step1: The "optimizer"
Step2: Additional components
"Box" constraints
Step3: The... | Python Code:
import numpy as np
objective = np.poly1d([1.3, 4.0, 0.6])
print(objective)
Explanation: Introduction to optimization
The basic components
The objective function (also called the 'cost' function)
End of explanation
import scipy.optimize as opt
x_ = opt.fmin(objective, [3])
print("solved: x={}".format(x_))
%... |
12,380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
String exercises
Step1: Fill in the code for the functions below. main() is already set up
to call the functions with a few different inputs,
printing 'OK' when each function is correct.
Th... | Python Code:
# Provided simple test() function
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
Explanation: String exercises
End of explanation
def doughnuts(count):
# +++your code he... |
12,381 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have this example of matrix by matrix multiplication using numpy arrays: | Problem:
from scipy import sparse
import numpy as np
sa = sparse.csr_matrix(np.array([[1,2,3],[4,5,6],[7,8,9]]))
sb = sparse.csr_matrix(np.array([0,1,2]))
result = sa.multiply(sb) |
12,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The purpose of this notebook is to determine the optimal launch azimuth and elevation angles, in order to maximize the likelihood of landing in a particular region. Eventually, this should b... | Python Code:
# all of our comparisons are ratios instead of subtractions because
# it's normalized, instead of dependent on magnitudes of variables and constraints
def objective_additive(var, cons):
return np.linalg.norm(var - cons)**2 / 2
# minimize this, **2 makes it well behaved w.r.t. when var=cons
def objectiv... |
12,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'miroc', 'sandbox-2', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: MIROC
Source ID: SANDBOX-2
Sub-Topics: Radiative Forcings.
Properties... |
12,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Load and inspect the data
Step1: Load the recent data
Step2: Visualize the data with GraphLab Canvas
Step3: Visualize the data with matplotlib
Step4: 2. A naive baseline
Step5: 3. Th... | Python Code:
import graphlab as gl
daily_stats = gl.load_timeseries('working_data/global_daily_stats.ts')
print "Number of rows:", len(daily_stats)
print "Start:", daily_stats.min_time
print "End:", daily_stats.max_time
daily_stats.print_rows(3)
Explanation: 1. Load and inspect the data: daily global earthquakes
Load t... |
12,385 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem 1 - Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the mul... | Python Code:
import math
def multiple35(n):
n3 = (n - 1) // 3
sum3 = 3 * n3 * (n3 + 1) // 2
n5 = (n - 1) // 5
sum5 = 5 * n5 * (n5 + 1) // 2
n15 = (n - 1) // 15
sum15 = 15 * n15 * (n15 + 1) // 2
return sum3 + sum5 - sum15
print(multiple35(1000))
Explanation: Problem 1 - Multiples of 3 and 5
I... |
12,386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Análise de Comics Digitais (Python) - Marvel ou DC?
Introdução
Depois de ter feito a análise do site (post aqui) e de ter feito um scraping dos dados do site da Comixology (post aqui), agora... | Python Code:
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
comixology_df = pd.read_csv("comixology_comics_dataset_19.04.2016.csv", encoding = "ISO-8859-1")
Explanation: Análise de Comics Digitais (Python) - Marvel ou DC?
In... |
12,387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
迷你项目:蒙特卡洛方法
在此 notebook 中,你将自己编写很多蒙特卡洛 (MC) 算法的实现。
虽然我们提供了一些起始代码,但是你可以删掉这些提示并从头编写代码。
第 0 部分:探索 BlackjackEnv
请使用以下代码单元格创建 Blackjack 环境的实例。
Step1: 每个状态都是包含以下三个元素的 3 元组:
- 玩家的当前点数之和 $\in {0, 1... | Python Code:
import gym
env = gym.make('Blackjack-v0')
Explanation: 迷你项目:蒙特卡洛方法
在此 notebook 中,你将自己编写很多蒙特卡洛 (MC) 算法的实现。
虽然我们提供了一些起始代码,但是你可以删掉这些提示并从头编写代码。
第 0 部分:探索 BlackjackEnv
请使用以下代码单元格创建 Blackjack 环境的实例。
End of explanation
STICK = 0
HIT = 1
Explanation: 每个状态都是包含以下三个元素的 3 元组:
- 玩家的当前点数之和 $\in {0, 1, \ldots, 31... |
12,388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 6
Step1: How would you write a for loop to walk through this list of day numbers and temperatures, and print the temp for each day?
Step2: Hot Days
Write code that walks through thi... | Python Code:
# For loop example
for counter in range(3, 7):
print counter
print "Whee!"
print "Done."
# Arrays example
children = ["Sally", "Bobby", "Tommy", "Tonya"]
ages = [12, 9, 7, 5]
print "Sally's age is ", ages[0]
print "Bobby's age is ", ages[1]
print "Tommy's age is ", ages[2]
print "Tonya's age is ",... |
12,389 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples of creating a power law distribution
The <code>distlib.MRN_dist()</code> functions return a <code>distlib.DustSpectrum</code> object.
The object contains an array of grain radii (... | Python Code:
mrn_test1 = distlib.MRN_dist(0.005, 0.3, 3.5)
mrn_test2 = distlib.MRN_dist(0.005, 0.25, 3.5)
mrn_test3 = distlib.MRN_dist(0.005, 0.3, 4.0)
mrn_test4 = distlib.MRN_dist(0.005, 0.3, 3.5, na=10, log=True)
Explanation: Examples of creating a power law distribution
The <code>distlib.MRN_dist()</code> functions ... |
12,390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple RNN Encode-Decoder for Translation
Learning Objectives
1. Learn how to create a tf.data.Dataset for seq2seq problems
1. Learn how to train an encoder-decoder model in Keras
1. Learn h... | Python Code:
pip freeze | grep nltk || pip install nltk
import os
import pickle
import sys
import nltk
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.layers import (
Dense,
Embedding,
GRU,
Input,
)
from tensorflow... |
12,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Install Dependencies
First install the libraries needed to execute recipes, this only needs to be done once, then click play.
Step1: 2. Get Cloud Project ID
To run this recipe requires a... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: 1. Install Dependencies
First install the libraries needed to execute recipes, this only needs to be done once, then click play.
End of explanation
CLOUD_PROJECT = 'PASTE PROJECT ID HERE'
print("Cloud Project Set To: %s" % CLOUD_PROJECT)
E... |
12,392 | 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.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
Explanation: Deep Learning
Assignment 3
Previously in 2_fullyconnected.ipynb,... |
12,393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Intuition for OOP
'OOP' stands for Object Orientated Programming. Today my aim to provide a quick overview of the topic which will help you develop an 'intuition' for what objects are and... | Python Code:
x = "I love cats." # <= x is a string...
print(x.upper()) # converts string to upper case
print(x.replace("c", "b")) # cats? I'm a bat kinda guy myself!
print(x.__add__(x)) # x.__add__(x) is EXACTLY the same as x + x.
print(x.__mul__(3)) # Equivalent to x * 3
Explanation: ... |
12,394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dual CRISPR Screen Analysis
Step 6
Step1: Automated Set-Up
Step2: Scoring-Ready File Preparation | Python Code:
g_dataset_name = "Notebook6Test"
g_library_fp = '~/dual_crispr/library_definitions/test_library_2.txt'
g_count_fps_or_dirs = '/home/ec2-user/dual_crispr/test_data/test_set_6a,/home/ec2-user/dual_crispr/test_data/test_set_6b'
g_time_prefixes = "T,D"
g_prepped_counts_run_prefix = ""
g_prepped_counts_dir = '~... |
12,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bayesian filtering in the frequency domain
This notebook contains an exploration of the characteristic function as a way to represent a probability distribution, yielding an efficient implem... | Python Code:
from __future__ import print_function, division
import thinkstats2
import thinkplot
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="white", palette="muted", color_codes=True)
%matplotlib inline
Explanation: Bayesian filteri... |
12,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This streams data directly into dataframes. See also
Step1: Add your custom code to read_csv_lines for processing your datafile
Step2: Code to connect to BigInsights on Cloud via WebHDFS ... | Python Code:
# Cluster number, e.g. 10000
cluster = ''
# Cluster username
username = ''
# Cluster password
password = ''
# file path in HDFS
filepath = 'yourpath/yourfile.csv'
Explanation: This streams data directly into dataframes. See also: https://github.com/snowch/biginsight-examples/blob/master/misc/WebHDFS_Exa... |
12,397 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create BigQuery stored procedures
This notebook is the second of two notebooks that guide you through completing the prerequisites for running the Real-time Item-to-item Recommendation with ... | Python Code:
!pip install -q -U google-cloud-bigquery pyarrow
Explanation: Create BigQuery stored procedures
This notebook is the second of two notebooks that guide you through completing the prerequisites for running the Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorization and ScaNN solution.
Us... |
12,398 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Understanding TensorFlow Distributions Shapes
<table class="tfo-not... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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... |
12,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Written by Bharath Ramsundar and Evan Feinberg
Copyright 2016, Stanford University
Computationally predicting molecular solubility through is useful for drug-discovery. In this tutorial, we ... | Python Code:
%autoreload 2
%pdb off
from deepchem.utils.save import load_from_disk
dataset_file= "../datasets/delaney-processed.csv"
dataset = load_from_disk(dataset_file)
print("Columns of dataset: %s" % str(dataset.columns.values))
print("Number of examples in dataset: %s" % str(dataset.shape[0]))
Explanation: Writte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.