Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
14,100 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table align="left">
<td>
<a href="https
Step1: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
Step... | 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"
! pip3... |
14,101 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Reinforcement Learning
Simple examples of RL using Tensorflow and OpenAI gym
Create cartpole environment
Step1: Check action and observation spaces dimensions
Step2: Check observatio... | Python Code:
import gym
env = gym.make('CartPole-v0')
Explanation: Basic Reinforcement Learning
Simple examples of RL using Tensorflow and OpenAI gym
Create cartpole environment
End of explanation
env.action_space, env.observation_space
Explanation: Check action and observation spaces dimensions
End of explanation
list... |
14,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
О вероятности попасть под удар фигуры, поставленной случайным образом на шахматную доску
На шахматную доску случайным образом поставлены две фигуры. С какой вероятностью первая фигура бьёт в... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from string import ascii_uppercase as alphabet
def get_board(board_size):
x, y = np.meshgrid(range(board_size), range(board_size))
board = np.empty(shape=(board_size, board_size), dtype='uint8')
text_colors = np.empty_like(bo... |
14,103 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Share the Insight
There are two main insights we want to communicate.
- Bangalore is the largest market for Onion Arrivals.
- Onion Price variation has increased in the recent years.
Let u... | Python Code:
# Import the library we need, which is Pandas and Matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
# Set some parameters to get good visuals - style to ggplot and size to 15,10
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] =... |
14,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Global Surface Temperature
This example uses historical data since 1880 on average global surface temperature changes from NASA's GISS Surface Temperature Analysis (GISTEMP) (original file) ... | Python Code:
# import the software packages needed
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
inline_rc = dict(mpl.rcParams)
Explanation: Global Surface Temperature
This example uses historical data since 1880 on average global surface temperature ... |
14,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In part 1, we ourselves created the additional features (x^2, x^3). Wouldn't it be nice if we create activation functions to do just that and let the neural network decide the weights for co... | Python Code:
import torch
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Setup the training and test tensors
# Let's generate 400 examples
N = 400
x = np.random.uniform(low=-75, high=100, size=N)
y = 2*x
X_tensor = Variable(torch.FloatTensor(x), requires_grad... |
14,106 | 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 Lattice を使った形状制約
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 必要なパッケージをインポートします。
S... | 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... |
14,107 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 Google
Step1: Data collection
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Now import Cirq, ReCirq and the module depen... | 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... |
14,108 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the Licens... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from __future__ import division
from __future__ import print_function
import math
import gym
from gym import spaces
import pandas as pd
import tensorflow as tf
from IPython import display
import time
from third_party import np_box_ops
import annotator, det... |
14,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gensim Tutorial on Online Non-Negative Matrix Factorization
This notebooks explains basic ideas behind the open source NMF implementation in Gensim, including code examples for applying NMF ... | Python Code:
import logging
import time
from contextlib import contextmanager
import os
from multiprocessing import Process
import psutil
import numpy as np
import pandas as pd
from numpy.random import RandomState
from sklearn import decomposition
from sklearn.cluster import MiniBatchKMeans
from sklearn.datasets import... |
14,110 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding Multiple Wells
This notebook shows how a WellModel can be used to fit multiple wells with one response function. The influence of the individual wells is scaled by the distance to the... | Python Code:
import numpy as np
import pandas as pd
import pastas as ps
import matplotlib.pyplot as plt
ps.show_versions()
Explanation: Adding Multiple Wells
This notebook shows how a WellModel can be used to fit multiple wells with one response function. The influence of the individual wells is scaled by the distance ... |
14,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 1
Step1: Load and prepare data
Step2: Here's the full dataset, and there are other columns. I will subselect a few of them by hand.
Step5: I will define the following functions to ex... | Python Code:
# Import the necessary packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import LeaveOneOut
from sklearn import linear_model, neighbors
%matplotlib inline
plt.style.use('ggplot')
# Where to save the figures
PROJECT_ROOT_DIR = ".."
datapath = PROJEC... |
14,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
These cells are used to pre-process the data.
They only need to be run once, and after that the saved data file can be loaded up from disk.
Step1: Load the data
Step2: Generate regularizat... | Python Code:
data = wobble.Data()
filenames = glob.glob('/Users/mbedell/python/wobble/data/toi/TOI-*_CCF_A.fits')
for filename in tqdm(filenames):
try:
sp = wobble.Spectrum()
sp.from_ESPRESSO(filename, process=True)
data.append(sp)
except Exception as e:
print("File {0} failed; e... |
14,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
W2 Lab Assignment
Internet Movie Database (IMDb) provides various information about movies, such as total budgets, lengths, actors, and user ratings. They are publicly available from here. I... | Python Code:
import csv
from itertools import islice
f = open('imdb.csv', 'r')
reader = csv.reader(f, delimiter='\t')
for row in islice(reader, 0, 5):
print(row)
print(row[1])
Explanation: W2 Lab Assignment
Internet Movie Database (IMDb) provides various information about movies, such as total budgets, lengths,... |
14,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
并发编程
不管在Python或者Java甚至js中都需要并发编程的存在.并发编程的目的是为了尽可能的使用机器的资源, 以达到更高的单机性能, 进而提升性价比.
这里有2个概念.
* 并发
Step1: 在以上代码中, 我们创建了2个线程分别根据参数进行打印操作. 思考为什么一个打印完了之后才打印另一个?
Master/Worker形式
在通常开发中, 一般很少直接将某一部分... | Python Code:
import time
# 引入多线程库
import threading
def say_hello(name):
for i in range(10):
print("hello {}".format(name))
thread1 = threading.Thread(target=say_hello, args=('small red',))
thread2 = threading.Thread(target=say_hello, args=('small light',))
thread1.start()
thread2.start()
Explanation: 并发编程
不... |
14,115 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 1
Imports
Step2: Euler's method
Euler's method is the simplest numerical approach for solving a first order ODE numerically. Given the differential ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 1
Imports
End of explanation
def solve_euler(derivs, y0, x):
Solve a 1d O... |
14,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class 10
Step1: Notice that in the previous example, the function takes no arguments and returns nothing. It just does the task that it's supposed to.
Example
Step2: Note the cobbDouglas()... | Python Code:
def hi():
print('Hello world!')
hi()
Explanation: Class 10: User-defined functions and a Solow growth model example
User-defined functions
Create a new function by using the def keyword followed by the designated name of the new function. In the definition, the function name has to be followe... |
14,117 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a model with traffic_last_5min feature
Introduction
In this notebook, we'll train a taxifare prediction model but this time with an additional feature of traffic_last_5min.
Step1: ... | Python Code:
import os
import shutil
from datetime import datetime
import pandas as pd
import tensorflow as tf
from google.cloud import aiplatform
from matplotlib import pyplot as plt
from tensorflow import keras
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.layers import Dense, DenseFeatures... |
14,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Make a plot of HICP inflation by item groups
Step1: Compute annual inflation rates
Step2: df_infl_items.rename(columns = dic)
tt = df_infl_items.copy()
tt['month'] = tt.index.month
tt['yea... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
import numpy as np
from matplotlib.ticker import FixedLocator, FixedFormatter
#import seaborn as sns
to_colors = lambda x : x/255.
ls
df_ind_items = pd.read_csv('raw_data_items.csv',header=0,index_col=0,par... |
14,119 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autoregressive Moving Average (ARMA)
Step1: Sunpots Data
Step2: Does our model obey the theory?
Step3: This indicates a lack of fit.
In-sample dynamic prediction. How good does our model ... | Python Code:
%matplotlib inline
from __future__ import print_function
import numpy as np
from scipy import stats
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.graphics.api import qqplot
Explanation: Autoregressive Moving Average (ARMA): Sunspots data
This notebook rep... |
14,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Defining a Milky Way potential model
Step1: Introduction
gala provides a simple and easy way to access and integrate orbits in an
approximate mass model for the Milky Way. The parameters of... | Python Code:
# Third-party dependencies
from astropy.io import ascii
import astropy.units as u
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq
# Gala
from gala.mpl_style import mpl_style
plt.style.use(mpl_style)
import gala.dynamics as gd
import gala.integrate as gi
import gala.pot... |
14,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cloud Dataflow Tutorial
事前準備
Google Cloud Platform の課金設定
Dataflow APIの有効化
GCSのBucketを作る
BigQueryにtestdatasetというデータセットを作る
Datalabを起動
That's it!
このNotebookをコピーするには
Datalabを開いたら、Notebookを新規に開いて... | Python Code:
import apache_beam as beam
Explanation: Cloud Dataflow Tutorial
事前準備
Google Cloud Platform の課金設定
Dataflow APIの有効化
GCSのBucketを作る
BigQueryにtestdatasetというデータセットを作る
Datalabを起動
That's it!
このNotebookをコピーするには
Datalabを開いたら、Notebookを新規に開いてください。
その後、セルに次のコードを入力して実行してください。
!git clone https://github.com/hayatoy/datafl... |
14,122 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook the datsets for the predictor will be generated.
Step1: Let's first define the list of parameters to use in each dataset.
Step2: Now, let's define the function to generate... | Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
%matplotlib inline
%pylab inline
pylab.rcParams['figure.figsize'] ... |
14,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: stringliteral
Step3: String operations
Different ways of String concatenation
Step4: String indexing and slicing
Step5: String indexing
Step6: String slicing
Step7: String sli... | Python Code:
new_string = "This is a String" # storing a string
print('ID:', id(new_string)) # shows the object identifier (address)
print('Type:', type(new_string)) # shows the object type
print('Value:', new_string) # shows the object value
# simple string
simple_string = 'Hello!' + " I'm a simple string"
print(s... |
14,124 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Box Plots
The following illustrates some options for the boxplot in statsmodels. These include violin_plot and bean_plot.
Step1: Bean Plots
The following example is taken from the docstring... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
Explanation: Box Plots
The following illustrates some options for the boxplot in statsmodels. These include violin_plot and bean_plot.
End of explanation
data = sm.datasets.anes96.load_pandas()
party_ID = np.... |
14,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST with transfer learning.
First let us build a MNIST logistic regression classifier.
We will then get better feature embeddings for images by using dvd library. This involves transfer le... | Python Code:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=False)
img = mnist.train.images[123]
img = np.reshape(img,(28,28))
plt.imshow(img, cmap = 'gray')
plt.show()
img = np... |
14,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CIFAR-10 Recipe
In this notebook, we will show how to train a state-of-art CIFAR-10 network with MXNet and extract feature from the network.
This example wiil cover
Network/Data definition
... | Python Code:
import mxnet as mx
import logging
import numpy as np
# setup logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
Explanation: CIFAR-10 Recipe
In this notebook, we will show how to train a state-of-art CIFAR-10 network with MXNet and extract feature from the network.
This example wiil cover
... |
14,127 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-3', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NIMS-KMA
Source ID: SANDBOX-3
Topic: Atmoschem
Sub-Topics: Transp... |
14,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Portfolio Optimization using Quandl, Bokeh and Gurobi
Borrowed and updated from Michael C. Grant, Continuum Analytics
Step1: First of all, we need some data to proceed. For that purpose we ... | Python Code:
import pandas as pd
import numpy as np
from math import sqrt
import sys
from bokeh.plotting import figure, show, ColumnDataSource, save
from bokeh.models import Range1d, HoverTool
from bokeh.io import output_notebook, output_file
import quandl
from gurobipy import *
# output_notebook() #To enable Bokeh out... |
14,129 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IPython
Step1: Getting help
Step2: Typing object_name? will print all sorts of details about any object, including docstrings, function definition lines (for call arguments) and constructo... | Python Code:
print("Hi")
Explanation: IPython: beyond plain Python
When executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed to make the interactive experience more fluid and efficient.
First things first: running code, getting help
In the notebook, to run a... |
14,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib
Reference Documents <A id='ref'></A>
<OL>
<LI> <A HREF="http
Step1: What is Matplotlib?
matplotlib is a library for making <B>2D plots</B> of arrays in Python. It is capable of p... | Python Code:
from IPython.display import YouTubeVideo
#YouTubeVideo("https://www.youtube.com/watch?v=P7SVi0YTIuE")
YouTubeVideo("P7SVi0YTIuE")
Explanation: Matplotlib
Reference Documents <A id='ref'></A>
<OL>
<LI> <A HREF="http://matplotlib.org/">Homepage of Matplotlib</A>
<LI> <A HREF="http://matplotlib.org/api/pyplot... |
14,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the female respondent file and display the variables names.
Step1: Make a histogram of <tt>totincr</tt> the to... | Python Code:
%matplotlib inline
import chap01soln
resp = chap01soln.ReadFemResp()
resp.columns
Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the female respondent file and display the variables names.
End of explanation
import thinkstats2
hist = thinkstats2.Hist(resp.totinc... |
14,132 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Higgs data set
URL
Step1: As done in previous notebook, create RDDs from raw data and build Gradient boosting and Random forests models. Consider doing 1% sampling since the dataset is too ... | Python Code:
#define feature names
feature_text='lepton pT, lepton eta, lepton phi, missing energy magnitude, missing energy phi, jet 1 pt, jet 1 eta, jet 1 phi, jet 1 b-tag, jet 2 pt, jet 2 eta, jet 2 phi, jet 2 b-tag, jet 3 pt, jet 3 eta, jet 3 phi, jet 3 b-tag, jet 4 pt, jet 4 eta, jet 4 phi, jet 4 b-tag, m_jj, m_jj... |
14,133 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST Image Classification with TensorFlow on Vertex AI
This notebook demonstrates how to implement different image models on MNIST using the tf.keras API.
Learning Objectives
Understand how... | Python Code:
import os
from datetime import datetime
REGION = "us-central1"
PROJECT = !(gcloud config get-value core/project)
PROJECT = PROJECT[0]
BUCKET = PROJECT
MODEL_TYPE = "cnn" # "linear", "dnn", "dnn_dropout", or "cnn"
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.enviro... |
14,134 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 9
Object Oriented Programming
Monday, October 2nd 2017
Step1: Motiviation
We would like to find a way to represent complex, structured data in the context of our programming languag... | Python Code:
from IPython.display import HTML
Explanation: Lecture 9
Object Oriented Programming
Monday, October 2nd 2017
End of explanation
def Complex(a, b): # constructor
return (a,b)
def real(c): # method
return c[0]
def imag(c):
return c[1]
def str_complex(c):
return "{0}+{1}i".format(c[0], c[1])
c... |
14,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Basics with Numpy (optional assignment)
Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help fam... | Python Code:
### START CODE HERE ### (≈ 1 line of code)
test = "Hello World"
### END CODE HERE ###
print ("test: " + test)
Explanation: Python Basics with Numpy (optional assignment)
Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will he... |
14,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Let's try to see if Pandas can read the .csv files coming from Weather Underground.
Step2: Now that we have a way of getting weather station data, let's do some time-based binning! B... | Python Code:
CSV_URL = 'https://www.wunderground.com/weatherstation/WXDailyHistory.asp?\
ID=KCABERKE22&day=24&month=06&year=2018&graphspan=day&format=1'
df = pd.read_csv(CSV_URL, index_col=False)
df
# remove every other row from the data because they contain `<br>` only
dg = df.drop([2*i + 1 for i in range(236)])
dg
de... |
14,137 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Context for this discussion (also see #19)
Step1: Inspired by varlens examples, here is how this simple function works
Step2: Let's compare the contexts for the variant and the reference a... | Python Code:
import pysam
import numpy as np
import pandas as pd
def contexify(samfile, chromosome, location, allele, radius):
# This will be our score board
counts = np.zeros(shape=((radius * 2) + 1, 5)) # 5 slots for each of the bases
d = pd.DataFrame(counts,
index=range(location - ra... |
14,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
powerindex
A python library to compute power indices
Installation
Step1: Now calculate Banzhaf and Shapley-Shubik power indices
Step2: Function calc() computes all available indices.
Thus,... | Python Code:
%matplotlib inline
import powerindex as px
game=px.Game(quota=51,weights=[51,49])
Explanation: powerindex
A python library to compute power indices
Installation: pip install powerindex
What is all about
The aim of the package is to compute different power indices of the so-called weighted voting systems (g... |
14,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Two-Level
Step2: We'll just check that the pulse area is what we want.
Step3: Plot Output
Step4: Analysis
The $4 \pi$ sech pulse breaks up into two $2 \pi$ pulses, which travel at ... | Python Code:
import numpy as np
SECH_FWHM_CONV = 1./2.6339157938
t_width = 1.0*SECH_FWHM_CONV # [τ]
print('t_width', t_width)
mb_solve_json =
{
"atom": {
"fields": [
{
"coupled_levels": [[0, 1]],
"rabi_freq_t_args": {
"n_pi": 4.0,
"centre": 0.0,
"width": %f
... |
14,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome
Welcome to Pineapple, the next generation scientific notebook.
Run Python code
Step1: You can make plots right in the notebook
Step2: Matrix operations are built-in
Pineapple uses ... | Python Code:
2 ** 64
Explanation: Welcome
Welcome to Pineapple, the next generation scientific notebook.
Run Python code
End of explanation
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10)
plt.plot(x, np.sin(x));
Explanation: You can make plots right in the notebook
End of ex... |
14,141 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Exercise-notebook-4
Step1: Exercise 1
Step2: A URL for downloading all the data as a CSV file can also be obtained via "View API L... | Python Code:
import sys
sys.version
import warnings
warnings.simplefilter('ignore', FutureWarning)
import matplotlib
matplotlib.rcParams['axes.grid'] = True # show gridlines by default
%matplotlib inline
from pandas import *
show_versions()
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Exercise... |
14,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Score mechanism
input
Step1: Get each base breeds score
Step2: Model version 1 | Python Code:
# 52 base classes:
# source 2: classified dog names
breed_classes = pd.read_csv("s3://dogfaces/tensor_model/output_labels_20170907.txt",names=['breed'])
base_breeds = breed_classes['breed'].values
base_breeds
with open('breed_lookup.pickle', 'rb') as handle:
rev_to_breed = pickle.load(handle)
len(rev_t... |
14,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dénes Csala, MCC, Kolozsvár, 2021
<small><i>This notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small>
Dimensionality Reduction
Step1: Introducing ... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
plt.style.use('seaborn')
Explanation: Dénes Csala, MCC, Kolozsvár, 2021
<small><i>This notebook was put together by Jake Vanderplas. Source and license info is on Gi... |
14,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <i class="fa fa-diamond"></i> Primero pimpea tu libreta!
Step2: <i class="fa fa-book"></i> Primero librerias
Step3: <i class="fa fa-database"></i> Vamos a crear datos de jugete
Crea... | Python Code:
from IPython.core.display import HTML
import os
def css_styling():
Load default custom.css file from ipython profile
base = os.getcwd()
styles = "<style>\n%s\n</style>" % (open(os.path.join(base,'files/custom.css'),'r').read())
return HTML(styles)
css_styling()
Explanation: <i class="fa fa-... |
14,145 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linking Plots Using Brush Interval Selector
Details on how to use the brush interval selector can be found in this notebook.
Brush interval selectors can be used where continuous updates are... | Python Code:
import numpy as np
from ipywidgets import Layout, HTML, VBox
import bqplot.pyplot as plt
Explanation: Linking Plots Using Brush Interval Selector
Details on how to use the brush interval selector can be found in this notebook.
Brush interval selectors can be used where continuous updates are not desirable ... |
14,146 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Feature Engineering in Keras
Learning Objectives
Process temporal feature columns in Keras
Use Lambda layers to perform feature engineering on geolocation features
Create bucketize... | Python Code:
import datetime
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow import feature_column as fc
from tensorflow.keras import layers, models
# set TF error log verbosity
logging.getLogger("tensorflow").setLevel(logging.ERROR)
print(tf.version.V... |
14,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NCEM's 4D-STEM Basic Jupyter Notebook
Quickly process and investigate 4D-STEM data from the TitanX
To start
Step1: Import the data and reshape to 4D
Change dirName to the directory where yo... | Python Code:
dirName = r'C:\Users\Peter\Data\Te NP 4D-STEM'
fName = r'07_45x8 ss=5nm_spot11_CL=100 0p1s_alpha=4p63mrad_bin=4_300kV.dm4'
%matplotlib widget
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import ncempy.io as nio
import ncempy.algo as nalgo
import ipywidge... |
14,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Unsupervised Learning
Project 3
Step1: Data Exploration
In this section, you will begin exploring the data through visualizations and code to understand... | Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
import renders as rs
from IPython.display import display # Allows the use of display() for DataFrames
# Show matplotlib plots inline (nicely formatted in the notebook)
%matplotlib inline
# Load the wholesale customers data... |
14,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
sharing internet on the laocal machine
ifconfig
scanning the local network to find the raspberry π
nmap -T4 -sP 192.168.2.0/24
what I used to clone the repository on the π
686 pip install p... | Python Code:
nb_pas = 12
position_present = 6
position_desired = 4
d_position = (position_desired - position_present + nb_pas//2 ) % nb_pas - nb_pas//2
print (d_position)
position_present = (position_present + d_position ) % nb_pas
print (position_present)
Explanation: sharing internet on the laocal machine
ifconfig
sc... |
14,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
4. External Quantification Tools
Step1: LCModel
LCModel requires several different files in order to process a spectrum. The actual MRS data is stored in the time domain in a .RAW file, wit... | Python Code:
import suspect
import numpy as np
from matplotlib import pyplot as plt
%matplotlib nbagg
data = suspect.io.load_rda("/home/jovyan/suspect/tests/test_data/siemens/SVS_30.rda")
Explanation: 4. External Quantification Tools
End of explanation
# create a parameters dictionary to set the basis set to use
params... |
14,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with events
This tutorial describes event representation and how event arrays are used to
subselect data.
Step1: The tutorial tut-events-vs-annotations describes in detail the
d... | Python Code:
import os
import numpy as np
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
raw.crop(tmax=60)... |
14,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Revenue Prediction for Site Selection
Whether it’s expansion, consolidation or performance monitoring, understanding revenue drivers is essential for Site Planning in many sectors such as Re... | Python Code:
import geopandas as gpd
import ipywidgets as widgets
import numpy as np
import pandas as pd
import pyproj
from cartoframes.auth import set_default_credentials
from cartoframes.data.observatory import *
from cartoframes.data.services import Geocoding, Isolines
from cartoframes.viz import *
from IPython.disp... |
14,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Maps for when the living gets tough
Step1: List of blocked reactions in the model
The following reactions were blocked in the original (Nagarajan,2013) model and still blocked in our model,... | Python Code:
import cobra
import pandas as pd
pd.set_option('display.max_colwidth', -1)
import re
import traceback
import escher
# import local functions
from show_map import show_map
# Load our modified Nagarajan et al., 2013 model
escher_file = '../Data/Escher/escher_map_c_ljungdahlii_acetogenesis_2020.json'
M = cobr... |
14,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiprocessing and multithreading
Parallelism in python
Step1: On Windows
Step2: Data parallelism versus task parallelism
Multithreading versus multiple threads
The global interpreter loc... | Python Code:
%%file multihello.py
'''hello from another process
'''
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
p = Process(target=f, args=('world',))
p.start()
p.join()
# EOF
!python2.7 multihello.py
Explanation: Multiprocessing and multithreadin... |
14,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sampyl Examples
Here I will have some examples showing how to use Sampyl. This is for version 0.2.2. Let's import it and get started. Sampyl is a Python package used to sample from probabili... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import sampyl as smp
from sampyl import np
# Autograd throws some warnings that are useful, but this is
# a demonstration, so I'll squelch them.
import warnings
warnings.filterwarnings('ignore')
Explanation: S... |
14,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with Texts in Python
Below is my solution to the exercises posed in the notebook 01-WorkingWithTexts.
As a reminder, you were asked to
Step1: First, create variables that split the ... | Python Code:
austen_string = open('../Data/Austen_PrideAndPrejudice.txt', encoding='utf-8').read()
alcott_string = open('../Data/Alcott_GarlandForGirls.txt', encoding='utf-8').read()
Explanation: Working with Texts in Python
Below is my solution to the exercises posed in the notebook 01-WorkingWithTexts.
As a reminder,... |
14,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Styling
This document is written as a Jupyter Notebook, and can be viewed or downloaded here.
You can apply conditional formatting, the visual styling of a DataFrame
depending on the data wi... | Python Code:
import matplotlib.pyplot
# We have this here to trigger matplotlib's font cache stuff.
# This cell is hidden from the output
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE... |
14,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GPU accelerated tensorflow
Author
Step1: Part 02 -- Manually specifying devices for running Tensorflow code
Step2: Setting up Tensorflow to run on CPU
Step3: Setting up Tensorflow to run ... | Python Code:
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Explanation: GPU accelerated tensorflow
Author:
Dr. Rahul Remanan
This code notebook is an introduction to GPU accelerated tensorflow.
Part 01 -- Checking Tensorflow GPU visibility
End of explanation
import tensorflow as... |
14,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Artificial Intelligence Engineer Nanodegree - Probabilistic Models
Project
Step1: The frame represented by video 98, frame 1 is shown here
Step2: Try it!
Step3: Build the training set
Now... | Python Code:
import numpy as np
import pandas as pd
from asl_data import AslDb
asl = AslDb() # initializes the database
asl.df.head() # displays the first five rows of the asl database, indexed by video and frame
asl.df.ix[98,1] # look at the data available for an individual frame
Explanation: Artificial Intelligence ... |
14,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1A.algo - filtre de Sobel
Le filtre de Sobel est utilisé pour calculer des gradients dans une image. L'image ainsi filtrée révèle les forts contrastes.
Step1: Exercice 1
Step2: Mais avant... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 1A.algo - filtre de Sobel
Le filtre de Sobel est utilisé pour calculer des gradients dans une image. L'image ainsi filtrée révèle les forts contrastes.
End of explanation
from pyquickhelper.loghelper import noLOG
from pyensae.data... |
14,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'dwd', 'mpi-esm-1-2-hr', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: DWD
Source ID: MPI-ESM-1-2-HR
Topic: Aerosol
Sub-Topics: Transport, E... |
14,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression test suite
Step1: The IMF allows to calculate the number of stars $N_{12}$ in the mass interval [m1,m2] with
(I) $N_{12}$ = k_N $\int _{m1}^{m2} m^{-2.35} dm$
Where k_N is the n... | Python Code:
#from imp import *
#s=load_source('sygma','/home/nugrid/nugrid/SYGMA/SYGMA_online/SYGMA_dev/sygma.py')
%pylab nbagg
import sygma as s
reload(s)
s.__file__
from scipy.integrate import quad
from scipy.interpolate import UnivariateSpline
#import matplotlib.pyplot as plt
#%matplotlib inline
import numpy as np
... |
14,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n... |
14,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import Libraries
Step1: Read image and Check inspect values of image at different locations
Step2: RGB pixel intensity 0-255
Step3: RGB line intensity 0-255 | Python Code:
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Import Libraries
End of explanation
img_RGB = cv2.imread('demo1.jpg')
plt.imshow(cv2.cvtColor(img_RGB, cv2.COLOR_BGR2RGB))
print('Shape_RGB:', img_RGB.shape)
print('Type_RGB:', img_RGB.dtype)
Explanation: Read image and Check inspec... |
14,165 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook for cellpy batch processing
You can fill inn the MarkDown cells (the cells without "numbering") by double-clicking them. Also remember, press shift + enter to execute a cell.
A coup... | Python Code:
%load_ext autoreload
%autoreload 2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cellpy
from cellpy import prms
from cellpy import prmreader
from cellpy.utils import batch
import holoviews as hv
%matplotlib inline
hv.extension("bokeh")
#######################################... |
14,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 07b
Step1: Next, let's load the data. This week, we're going to load the Auto MPG data set, which is available online at the UC Irvine Machine Learning Repository. The dataset is in fix... | Python Code:
%matplotlib inline
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import GridSearchCV, KFold, cross_val_predict
Explanation: Lab 07b: Decision tree regression
... |
14,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Story
The data (Bondora's loan book) can be download from
Step1: Number of loans per year
Step2: From the initial analysis we can see that the number of loans is definitely growing ov... | Python Code:
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
import warnings
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
pd.options.display.max_rows = 125
import seaborn as sns
sns.set(color_codes=True)
sns.set(rc={"figure.figsize"... |
14,168 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
KFServing Pipeline samples
This notebook assumes your cluster has KFServing >= v0.5.0 installed which supports the v1beta1 API.
Install the necessary kfp library
Step1: TensorFlow example
S... | Python Code:
!pip3 install kfp --upgrade
import kfp.compiler as compiler
import kfp.dsl as dsl
import kfp
from kfp import components
# Create kfp client
# Note: Add the KubeFlow Pipeline endpoint below if the client is not running on the same cluster.
# Example: kfp.Client('http://192.168.1.27:31380/pipeline')
client =... |
14,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Embedding CPLEX in a ML Spark Pipeline
Spark ML provides a uniform set of high-level APIs that help users create and tune practical machine learning pipelines.
In this notebook, we show how ... | Python Code:
try:
import numpy as np
except ImportError:
raise RuntimError('This notebook requires numpy')
Explanation: Embedding CPLEX in a ML Spark Pipeline
Spark ML provides a uniform set of high-level APIs that help users create and tune practical machine learning pipelines.
In this notebook, we show how to... |
14,170 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 08 - Non linear Parabolic problem
Keywords
Step1: 3. Affine Decomposition
We set the variables $u
Step2: 4. Main program
4.1. Read the mesh for this problem
The mesh was generated... | Python Code:
from dolfin import *
from rbnics import *
from utils import *
Explanation: Tutorial 08 - Non linear Parabolic problem
Keywords: exact parametrized functions, POD-Galerkin
1. Introduction
In this tutorial, we consider the FitzHugh-Nagumo (F-N) system. The F-N system is used to describe neuron excitable syst... |
14,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1 Regularised Linear Regression
1.1 Data Extraction and Transformation
Step1: 1.2 Data Visualisation
Step2: 1.2.1 Training Set
Step3: 1.2.2 Validation Set
Step4: 1.2.3 Test Set
Step5: 1... | Python Code:
def get_data(file_path, xLabel, yLabel):
data = loadmat(file_path)
X = np.insert(data[xLabel], 0, 1, axis=1)
n_samples, n_variables = X.shape
y = data[yLabel]
return X.flatten(), y.flatten(), n_samples, n_variables
def get_β(n_variables):
β = np.zeros(n_variables)
return β
Expla... |
14,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training deep neural networks
@cesans
Step1: Loading data
Previously generated trajectories can be loaded with dc.data.load_trajectories
Step2: Training
From the trajectories we can genera... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import sys
sys.path.append('..')
import numpy as np
import deep_control as dc
Explanation: Training deep neural networks
@cesans
End of explanation
# The time column is automatically discarded
# For free landing we drop the 'x' column
col_names = ['t', 'm... |
14,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Alternative libraries
Before this, the two main libraries used for scraping a webpage were requests and BeautifulSoup. However, there ar ealso alternative libraries that can serve the same p... | Python Code:
import urllib2
from lxml import html
url = "https://careercenter.am/ccidxann.php"
response = urllib2.urlopen(url)
page = response.read()
tree = html.document_fromstring(page)
Explanation: Alternative libraries
Before this, the two main libraries used for scraping a webpage were requests and BeautifulSoup. ... |
14,174 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Programming Assignment
Step1: Составление корпуса
Step2: Наша коллекция небольшая, и целиком помещается в оперативную память. Gensim может работать с такими данными и не требует их сохране... | Python Code:
import json
with open("recipes.json") as f:
recipes = json.load(f)
print(recipes[0])
Explanation: Programming Assignment:
Готовим LDA по рецептам
Как вы уже знаете, в тематическом моделировании делается предположение о том, что для определения тематики порядок слов в документе не важен; об этом гласит ... |
14,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
WrightTools for Numpy Users
As scientists transitioned to the Python Scientific Library during its rise in popularity, new users needed translations to their familiar software, such as Matla... | Python Code:
import numpy as np
import WrightTools as wt
print(np.__version__) # tested on 1.18.1
print(wt.__version__) # tested on 3.3.1
x = np.linspace(0, 1, 5) # Hz
y = np.linspace(500, 700, 3) # nm
z = np.exp(-x[:, None]) * np.sqrt(y - 500)[None, :]
data = wt.Data()
data.create_channel(name="z", values=z)
# BE ... |
14,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Energy system optimisation with oemof - how to collect and store results
Import necessary modules
Step1: Specify solver
Step2: Create an energy system and optimize the dispatch at least co... | Python Code:
import os
import pandas as pd
from oemof.solph import (Sink, Source, Transformer, Bus, Flow, Model,
EnergySystem, processing, views)
import pickle
Explanation: Energy system optimisation with oemof - how to collect and store results
Import necessary modules
End of explanation
solve... |
14,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building your Deep Neural Network
Step2: 2 - Outline of the Assignment
To build your neural network, you will be implementing several "helper functions". These helper functions will be used... | Python Code:
import numpy as np
import h5py
import matplotlib.pyplot as plt
from testCases_v2 import *
from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rc... |
14,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parameter Estimation of RIG Roll Experiments
Setup and descriptions
Without ACM model
Turn on wind tunnel
Only 1DoF for RIG roll movement
Use small-amplitude aileron command of CMP as inputs... | Python Code:
%run matt_startup
%run -i matt_utils
button_qtconsole()
#import other needed modules in all used engines
#with dview.sync_imports():
# import os
Explanation: Parameter Estimation of RIG Roll Experiments
Setup and descriptions
Without ACM model
Turn on wind tunnel
Only 1DoF for RIG roll movement
Use small... |
14,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supplementary material for "Mesoscale to submesoscale wavenumber spectra in Drake Passage" (in prep. for JPO)
C. B. Rocha, T. K. Chereskin, S. T. Gille, and D. Menemenlis
This notebook showc... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# if you don't have pyspec installed comment this out
# and follow the instructions below
from pyspec import helmholtz as helm
# copy helmholts.py into your working directory and import it
# (just uncomment the line below)
# import h... |
14,180 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculating Annotation Coverage
This section shows how to calculate annotation coverage as described here
Step1: 2. Read associations
2a. You can read the associations one species at a time... | Python Code:
# Get ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2go.gz
from goatools.base import download_ncbi_associations
gene2go = download_ncbi_associations()
Explanation: Calculating Annotation Coverage
This section shows how to calculate annotation coverage as described here:
Annotation coverage of Gene Ontology ... |
14,181 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning
Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea... | Python Code:
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=... |
14,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 訓練後の整数量子化
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: MNIST モデルをビルドする
MNIST データセットから、数字... | 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... |
14,183 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have the following data frame: | Problem:
import pandas as pd
import io
import numpy as np
from scipy import stats
temp=u"""probegenes,sample1,sample2,sample3
1415777_at Pnliprp1,20,0.00,11
1415805_at Clps,17,0.00,55
1415884_at Cela3b,47,0.00,100"""
df = pd.read_csv(io.StringIO(temp),index_col='probegenes')
indices = [('1415777_at Pnliprp1', 'data'), ... |
14,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We covered a lot of information today and I'd like you to practice developing classification trees on your own. For each exercise, work through the problem, determine the result, and provide... | Python Code:
from sklearn import datasets, tree, metrics
from sklearn.cross_validation import train_test_split
import numpy as np
dt = tree.DecisionTreeClassifier()
iris = datasets.load_iris()
x = iris.data[:,2:]
y = iris.target
# 50% - 50%
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.5,train_siz... |
14,185 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Face Generation
In this project, you'll use generative adversarial networks to generate new images of faces.
Get the Data
You'll be using two datasets in this project
Step3: Explore ... | Python Code:
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'
DON'T MODIFY ANYTHING IN THIS CELL
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
Explanation: Face Generation
In this project, you'll use generative adversa... |
14,186 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, we'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, we'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... |
14,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning with H2O - Tutorial 4b
Step1: <br>
Step2: <br>
Define Search Criteria for Random Grid Search
Step3: <br>
Step 1
Step4: <br>
Step 2
Step5: <br>
Model Stacking
Step6: <b... | Python Code:
# Import all required modules
import h2o
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.estimators.stackedensemble import H2OStackedEnsembleEstimator
from... |
14,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statistically meaningful charts
Seaborn
The next module we will explore is Seaborn. Seaborn is a Python visualization library based on matplotlib. It is built on top of matplotlib and tightl... | Python Code:
%matplotlib inline
import matplotlib
import seaborn as sns
import pandas as pd
import numpy as np
import warnings
sns.set(color_codes=True)
warnings.filterwarnings("ignore")
Explanation: Statistically meaningful charts
Seaborn
The next module we will explore is Seaborn. Seaborn is a Python visualization li... |
14,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to construct a simple convo network
Step1: calculate the number of parameters of a convo layer
Step2: The output layer shape is
Step3: There are 756,560 total parameters. That's a HUG... | Python Code:
input = tf.placeholder(tf.float32, (None, 32, 32, 3))
filter_weights = tf.Variable(tf.truncated_normal((8, 8, 3, 20))) # (height, width, input_depth, output_depth)
filter_bias = tf.Variable(tf.zeros(20))
strides = [1, 2, 2, 1] # (batch, height, width, depth)
padding = 'VALID'
conv = tf.nn.conv2d(input, fil... |
14,190 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have fitted a k-means algorithm on 5000+ samples using the python scikit-learn library. I want to have the 50 samples closest (data, not just index) to a cluster center "p" (e.g. ... | Problem:
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
p, X = load_data()
assert type(X) == np.ndarray
km = KMeans()
km.fit(X)
d = km.transform(X)[:, p]
indexes = np.argsort(d)[::][:50]
closest_50_samples = X[indexes] |
14,191 | Given the following text description, write Python code to implement the functionality described.
Description:
Given a non-empty list of integers lst. add the even elements that are at odd indices..
Examples:
add([4, 2, 6, 7]) ==> 2
| Python Code:
def add(lst):
return sum([lst[i] for i in range(1, len(lst), 2) if lst[i]%2 == 0]) |
14,192 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gradient Checking
Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking.
You are part of a team working to make mobile paym... | Python Code:
# Packages
import numpy as np
from testCases import *
from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector
Explanation: Gradient Checking
Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking.
... |
14,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Traverse a Square - Part N - Functions
tricky because of scoping - need to think carefully about this....
In the previous notebook on this topic, we had described how to use a loop that coul... | Python Code:
import time
def myFunction():
print("Hello...")
#Pause awhile...
time.sleep(2)
print("...world!")
#call the function - note the brackets!
myFunction()
Explanation: Traverse a Square - Part N - Functions
tricky because of scoping - need to think carefully about this....
In the... |
14,194 | 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', 'test-institute-3', 'sandbox-2', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: TEST-INSTITUTE-3
Source ID: SANDBOX-2
Topic: Ocnbgchem
Su... |
14,195 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started with Application Programming Interfaces (APIs)
APIs make it easy to collect data for text mining and machine learning projects. In this workshop, we'll learn how to collect d... | Python Code:
import requests
url = 'https://api.datamuse.com/words?sp=t??k'
# get the content at the requested url
response = requests.get(url)
# get the JSON data in the response object
data = response.json()
print(data)
Explanation: Getting Started with Application Programming Interfaces (APIs)
APIs make it easy to c... |
14,196 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Silicon Forest Math Series<br/>Oregon Curriculum Network
Introduction to Public Key Cryptography
Here in the Silicon Forest, we do not expect everyone to become a career computer prog... | Python Code:
import pprint
def primes():
generate successive prime numbers (trial by division)
candidate = 1
_primes_so_far = [2] # first prime, only even prime
yield _primes_so_far[0] # share it!
while True:
candidate += 2 # check odds only from now on
for prev in _primes_so... |
14,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Convolutional Neural Networks
Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - s... | Python Code:
%matplotlib inline
Explanation: Using Convolutional Neural Networks
Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - something that is only possible thanks to deep learning.
Introduction to this week's t... |
14,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import modules
Step1: Load data
For this exercise, we will be using a dataset of housing prices in Boston during the 1970s. Python's super-awesome sklearn package already has the data we ne... | Python Code:
from sklearn.datasets import load_boston
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import scale
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_squared_error
from sklearn.cross_validation import KFold
import matplotlib.pyplot as plt
... |
14,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to Classification Lab 1
In this lab we will learn how to generate synthetic data and how to apply various built-in classifiers to classify the data. The goal of this lab is to introduc... | Python Code:
# Import base libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
Explanation: Intro to Classification Lab 1
In this lab we will learn how to generate synthetic data and how to apply various built-in classifiers to classify the data. The goal of this la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.