Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
5,000 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
XGBoost HP Tuning on AI Platform
This notebook trains a model on Ai Platform using Hyperparameter Tuning to predict a car's Miles Per Gallon. It uses Auto MPG Data Set from UCI Machine Learn... | Python Code:
# Replace <PROJECT_ID> and <BUCKET_ID> with proper Project and Bucket ID's:
%env PROJECT_ID <PROJECT_ID>
%env BUCKET_ID <BUCKET_ID>
%env JOB_DIR gs://<BUCKET_ID>/xgboost_job_dir
%env REGION us-central1
%env TRAINER_PACKAGE_PATH ./auto_mpg_hp_tuning
%env MAIN_TRAINER_MODULE auto_mpg_hp_tuning.train
%env RUN... |
5,001 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bay Area Bike Share Analysis
Introduction
Tip
Step1: Condensing the Trip Data
The first step is to look at the structure of the dataset to see if there's any data wrangling we should perfor... | Python Code:
# import all necessary packages and functions.
import csv
from datetime import datetime
import numpy as np
import pandas as pd
from babs_datacheck import question_3
from babs_visualizations import usage_stats, usage_plot
from IPython.display import display
import matplotlib.pyplot as plt
%matplotlib inline... |
5,002 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CIFAR10 是另外一個 dataset, 和 mnist 一樣,有十種類別(飛機、汽車、鳥、貓、鹿、狗、青蛙、馬、船、卡車)
https
Step1: 查看一下資料
Step2: Q
將之前的 logistic regression 套用過來看看
將之前的 cnn model 套用過來看看 (注意資料格式, channel x H x W 還是 H x W x chan... | Python Code:
import keras
from keras.models import Sequential
from PIL import Image
import numpy as np
import tarfile
# 下載 dataset
url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
import os
import urllib
from urllib.request import urlretrieve
def reporthook(a,b,c):
print("\rdownloading: %5.1f%%"%(a*b... |
5,003 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Oregon Curriculum Network <br />
Discovering Math with Python
FOCUSING ON THE S FACTOR
$\phi$ DOODLES Using $\LaTeX$
<a data-flickr-embed="true" href="https
Step1: In showing off the Decim... | Python Code:
from math import sqrt as rt2
from decimal import Decimal, getcontext
context = getcontext()
context.prec = 50
one = Decimal(1) # 28 digits of precision by default, more on tap
two = Decimal(2)
three = Decimal(3)
five = Decimal(5)
nine = Decimal(9)
eight = Decimal(8)
sqrt2 = two.sqrt()
sqrt5 = five.sqrt()
... |
5,004 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python
Goals
Step1: Everything is an Object
Everything in Python is considered an object.
A string, a list, a function and even a number is an object.
For example, you can d... | Python Code:
for x in list(range(5)):
print("One number per loop..")
print(x)
if x > 2:
print("The number is greater than 2")
print("----------------------------")
Explanation: Introduction to Python
Goals:
Learn basic Python operations
Understand differences in data structures
Get familiari... |
5,005 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting Matrices
At some point you may need to plot a matrix. This works a bit differently from regular plots.
Step1: In the plot above each cell of the matrix corresponds to one of the co... | Python Code:
def create_matrix(size):
mat = np.zeros((size, size))
for i in range(size):
for j in range (size):
mat[i, j] = i * j
return mat
create_matrix(4)
mat = create_matrix(20)
plt.imshow(mat)
plt.colorbar() # Adds a colorbar to the plot to aid in interpretation.
plt.xlabel("x")
plt... |
5,006 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FRETBursts - 8-spot smFRET burst analysis
This notebook is part of a tutorial series for the FRETBursts burst analysis software.
For a step-by-step introduction to FRETBursts usage please re... | Python Code:
from fretbursts import *
sns = init_notebook()
import lmfit; lmfit.__version__
import phconvert; phconvert.__version__
Explanation: FRETBursts - 8-spot smFRET burst analysis
This notebook is part of a tutorial series for the FRETBursts burst analysis software.
For a step-by-step introduction to FRETBursts ... |
5,007 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/logo.jpg" style="display
Step1: <p style="text-align
Step2: <p style="text-align
Step3: <p style="text-align
Step4: <p style="text-align
Step5: <p style="text-align
Ste... | Python Code:
class Animal:
pass
class Mammal(Animal):
pass
class Bat(Mammal):
pass
class Rabbit(Mammal):
pass
Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: ל... |
5,008 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
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', 'test-institute-2', 'sandbox-1', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: TEST-INSTITUTE-2
Source ID: SANDBOX-1
Topic: Landice
Sub-Topi... |
5,009 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 3
Functions
Step1: We can unpack a list or tuple into positional arguments using a star *
Step2: Similarly, we can use double star ** to unpack a dictionary into keyword arguments.
... | Python Code:
import math
def euclidean_distance(x1, y1, x2, y2):
return math.sqrt((x1 - x2) ** 2 + (y1-y2) ** 2)
euclidean_distance(0,0,1,1)
Explanation: Python 3
Functions
End of explanation
values_list = [0,0,1,1]
euclidean_distance(*values_list)
values_tuple = (0,0,1,1)
euclidean_distance(*values_tuple)
Explanat... |
5,010 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
[1-1] 動画作成用のモジュールをインポートして、動画を表示可能なモードにセットします。
Step1: [1-2] x軸上を一定速度で移動するボールの動画を描きます。
動画のGIFファイル「animation01.gif」も同時に作成します。
Step2: [1-3] 3個のランダムウォークの動画を描きます。
動画のGIFファイル「animation02.gif」も同時に... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy.random import randint
%matplotlib nbagg
Explanation: [1-1] 動画作成用のモジュールをインポートして、動画を表示可能なモードにセットします。
End of explanation
fig = plt.figure(figsize=(6,2))
subplot = fig.add_subplot(1,1,1)
subplot.set_xlim(0,50... |
5,011 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2> Finding specific text in a corpus of scanned documents </h2>
Step1: Here are a few of the images we are going to search.
<img src="https
Step2: <h2> Translating a large document in pa... | Python Code:
from googleapiclient.discovery import build
import subprocess
images = subprocess.check_output(["gsutil", "ls", "gs://{}/unstructured/photos".format(BUCKET)])
images = list(filter(None,images.split('\n')))
print(images)
Explanation: <h2> Finding specific text in a corpus of scanned documents </h2>
End of e... |
5,012 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
More API Examples
This notebook contains EVEN MORE API examples so you can get an idea of the types of services available. There's a world of API's out there for the taking, and we cannot te... | Python Code:
import requests
phone = input("Enter your phone number: ")
params = { 'phone' : phone }
headers={ "X-Mashape-Key": "sNi0LJs3rBmshZL7KQOrRWXZqIsBp1XUjhnjsnYUsE6iKo14Nc",
"Accept": "application/json" }
response = requests.get("https://cosmin-us-phone-number-lookup.p.mashape.com/get.php", params=params, h... |
5,013 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: High Order Taylor Maps I
(original by Dario Izzo - extended by Ekin Ozturk)
Building upon the notebook here, we show the use of desolver for numerically integrating the system of diff... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import os
import numpy as np
os.environ['DES_BACKEND'] = 'numpy'
import desolver as de
import desolver.backend as D
from desolver.backend import gdual_double as gdual
T = 1e-3
@de.rhs_prettifier(equ_repr="[vr, -1/r**2 + r*vt**2, vt, -2*vt*vr/r]", md_r... |
5,014 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to "Doing Science" in Python for REAL Beginners
Python is one of many languages you can use for research and HW purposes. In the next few days, we will work through many of the ... | Python Code:
#test cell
Explanation: Introduction to "Doing Science" in Python for REAL Beginners
Python is one of many languages you can use for research and HW purposes. In the next few days, we will work through many of the tool, tips, and tricks that we as graduate students (and PhD researchers) use on a daily basi... |
5,015 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Identify Fraud from Enron email
Machine Learning Project
Tools library
Step5: Tester module
Step6: Data exploration and cleaning
Step7: Basic statistics
Step8: This shows that the... | Python Code:
#!/usr/bin/python
A general tool for converting data from the
dictionary format to an (n x k) python list that's
ready for training an sklearn algorithm
n--no. of key-value pairs in dictonary
k--no. of features being extracted
dictionary keys are names of persons in dataset
d... |
5,016 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple Linear Regression
We need to read our data from a <tt>csv</tt> file. The module csv offers a number of functions for reading and writing a <tt>csv</tt> file.
Step1: The data we want... | Python Code:
import csv
Explanation: Simple Linear Regression
We need to read our data from a <tt>csv</tt> file. The module csv offers a number of functions for reading and writing a <tt>csv</tt> file.
End of explanation
!cat cars.csv || type cars.csv
Explanation: The data we want to read is contained in the <tt>csv</... |
5,017 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Topic Modeling wiht Latent Semantic Analysis
Latent Semantic Analysis (LSA) is a method for reducing the dimnesionality of documents treated as a bag of words. It is used for document classi... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy.linalg as la
import scipy.stats as st
Explanation: Topic Modeling wiht Latent Semantic Analysis
Latent Semantic Analysis (LSA) is a method for reducing the dimnesionality of documents treated as a bag of ... |
5,018 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This problem originated from a blog post I wrote for DataCamp on graph optimization here. The algorithm I sketched out there for solving the Chinese Problem on the Sleeping Giant state park... | Python Code:
import mplleaflet
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
# can be found in https://github.com/brooksandrew/postman_problems_examples
from osm2nx import read_osm, haversine
from graph import contract_edges, create_rpp_edgelist
from postman_p... |
5,019 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration of distribution reweighting
hep_ml.reweight contains methods to reweight distributions.
Typically we use reweighting of monte-carlo to fight drawbacks of simulation, though th... | Python Code:
%pylab inline
figsize(16, 8)
import root_numpy
import pandas
from hep_ml import reweight
Explanation: Demonstration of distribution reweighting
hep_ml.reweight contains methods to reweight distributions.
Typically we use reweighting of monte-carlo to fight drawbacks of simulation, though there are many ap... |
5,020 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Discerning Haggis 2016-ml-contest submission
Author
Step1: Convenience functions
Step2: Load, treat and color data
We try smoothing the data using several windows.
Step3: Retrain and pred... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
import seaborn as sns
sns.set(style='whitegrid',
rc={'lines.linewidth': 2.5,
'fig... |
5,021 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bienvenid@s a Jupyter
Los cuadernos de Jupyter son una herramienta interactiva que te permite preparar documentos con código ejecutable, ecuaciones, texto, imágenes, videos, entre otros, que... | Python Code:
# Lo primero que ejecutarás será 'Hola Jupyter'
print('Hola Jupyter')
Explanation: Bienvenid@s a Jupyter
Los cuadernos de Jupyter son una herramienta interactiva que te permite preparar documentos con código ejecutable, ecuaciones, texto, imágenes, videos, entre otros, que te ayuda a enriquecer o explicar ... |
5,022 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2018/9/15-16 WNixalo
https
Step1: the torch.Tensor.sum(dim) call takes an integer argument as the axis along which to sum. This applies to NumPy arrays as well.
In this case xb.sum(-1) will... | Python Code:
from pathlib import Path
import requests
data_path = Path('data')
path = data_path/'mnist'
path.mkdir(parents=True, exist_ok=True)
url = 'http://deeplearning.net/data/mnist/'
filename = 'mnist.pkl.gz'
(path/filename)
if not (path/filename).exists():
content = requests.get(url+filename).content
(pat... |
5,023 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
write a function encode_output() to one-hot encode English output sequences.
| Python Code::
# one hot encode target sequence
def encode_output(sequences, vocab_size):
ylist = list()
for sequence in sequences:
encoded = to_categorical(sequence, num_classes=vocab_size)
ylist.append(encoded)
y = array(ylist)
y = y.reshape(sequences.shape[0], sequences.shape[1], vocab_size)
return y
|
5,024 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Some questions
1. Change coints
Problem
Step3: 2. Plant flowers
Problem
Step5: 3. Jumping rabit!
Problems | Python Code:
# change coins
# TODO: find all the combination instead of just number of combination?
# TODO: find the min number coint used?
def change_coins(coins: list, n: int, m: int):
:param m: the amount of money
:param n: the type of coins
dp = [0 for i in range(m+1)]
dp[0] = 1 # base ca... |
5,025 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collections Module
The collections module is a built-in module that implements specialized container data types providing alternatives to Python’s general purpose built-in containers. We've ... | Python Code:
from collections import Counter
Explanation: Collections Module
The collections module is a built-in module that implements specialized container data types providing alternatives to Python’s general purpose built-in containers. We've already gone over the basics: dict, list, set, and tuple.
Now we'll lear... |
5,026 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running EnergyPlus from Eppy
It would be great if we could run EnergyPlus directly from our IDF wouldn’t it?
Well here’s how we can.
Step1: if you are in a terminal, you will see something ... | Python Code:
# you would normaly install eppy by doing
# python setup.py install
# or
# pip install eppy
# or
# easy_install eppy
# if you have not done so, uncomment the following three lines
import sys
# pathnameto_eppy = 'c:/eppy'
pathnameto_eppy = '../'
sys.path.append(pathnameto_eppy)
from eppy.modeleditor import ... |
5,027 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tensor Network Random Unitary Evolution
This example demonstrates some features of TensorNetwork manipulation as well as the use of MatrixProductState.gate, based on 'evolving' an intitial M... | Python Code:
%matplotlib inline
from quimb.tensor import *
from quimb import *
import numpy as np
Explanation: Tensor Network Random Unitary Evolution
This example demonstrates some features of TensorNetwork manipulation as well as the use of MatrixProductState.gate, based on 'evolving' an intitial MPS with many random... |
5,028 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computational model for group analysis
Demo code for Ito et al., 2017. Generates exact figures from Supplementary Fig. 3, and several comparable figures to Fig. 4.
Author
Step1: ESSENTIAL p... | Python Code:
import numpy as np
import sys
sys.path.append('utils/')
import os
os.environ['OMP_NUM_THREADS'] = str(1)
import matplotlib.pyplot as plt
% matplotlib inline
import scipy.stats as stats
import statsmodels.api as sm
import multiprocessing as mp
import sklearn.preprocessing as preprocessing
import sklearn.svm... |
5,029 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RNN 기본 구조와 Keras를 사용한 RNN 구현
신경망을 사용하여 문장(sentence)이나 시계열(time series) 데이터와 같은 순서열(sequence)를 예측하는 문제를 푸는 경우, 예측하고자 하는 값이 더 오랜 과거의 데이터에 의존하게 하려면 시퀀스를 나타내는 벡터의 크기를 증가시켜야 한다. 예를 들어 10,000개의 단어... | Python Code:
s = np.sin(2 * np.pi * 0.125 * np.arange(20))
plt.plot(s, 'ro-')
plt.xlim(-0.5, 20.5)
plt.ylim(-1.1, 1.1)
plt.show()
Explanation: RNN 기본 구조와 Keras를 사용한 RNN 구현
신경망을 사용하여 문장(sentence)이나 시계열(time series) 데이터와 같은 순서열(sequence)를 예측하는 문제를 푸는 경우, 예측하고자 하는 값이 더 오랜 과거의 데이터에 의존하게 하려면 시퀀스를 나타내는 벡터의 크기를 증가시켜야 한다. 예를 들... |
5,030 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulation with the Shyft API
Introduction
In Part I of the simulation tutorials, we covered conducting a very simple simulation of an example catchment using configuration files. This is a ... | Python Code:
# Pure python modules and jupyter notebook functionality
# first you should import the third-party python modules which you'll use later on
# the first line enables that figures are shown inline, directly in the notebook
%matplotlib inline
import os
import datetime as dt
import pandas as pd
from netCDF4 im... |
5,031 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this example we will begin to cover some of the extraction utilities in sisl allowing one to really go in-depth on analysis of calculations.
We will begin by creating a large graphene fla... | Python Code:
graphene = sisl.geom.graphene(orthogonal=True)
elec = graphene.tile(25, axis=0)
H = sisl.Hamiltonian(elec)
H.construct(([0.1, 1.43], [0., -2.7]))
H.write('ELEC.nc')
device = elec.tile(15, axis=1)
device = device.remove(
device.close(
device.center(what='cell'), R=10.)
)
Explanation: In this exa... |
5,032 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Code Optimization and Multi Threading
Writing Python code is one thing - writing efficient code is a much different thing. Optimizing your code may take a while; if it takes longer to... | Python Code:
import time
def square(x):
return x**2
def quadrature(func, a, b, n=10000000):
use the quadrature rule to determine the integral over the function from a to b
# calculate individual elements
integral_elements = [func(a)/2.]
for k in range(1, n):
integral_elements.append(func(a+... |
5,033 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
================================================================
Demonstration of how to use ClickableImage / generate_2d_layout.
============================================================... | Python Code:
# Authors: Christopher Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)
from scipy.ndimage import imread
import numpy as np
from matplotlib import pyplot as plt
from os import path as op
import mne
from mne.viz import ClickableImage, add_background_image # noqa
from mne.channels import genera... |
5,034 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plot QNM Frequencies under different scenarios to demonstrate Conventions and Properties.
Summary
Step1: Plot Single QNM Frequency on jf = [-1,1] using tabulated data
Step2: Plot the singl... | Python Code:
# Define which base QNM to use. Note that the same QNM with m --> -m may be used at some point.
l,m,n = 2,1,0
# Useful to development: turn module reloading
%load_ext autoreload
# Inline plotting
%matplotlib inline
# Force module recompile
%autoreload 2
# Import kerr and numpy
from kerr import leaver
from ... |
5,035 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing various MNE solutions
This example shows example fixed- and free-orientation source localizations
produced by MNE, dSPM, sLORETA, and eLORETA.
Step1: Fixed orientation
First let's... | Python Code:
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
# Read data
fname_evoked = data_path ... |
5,036 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2>Vorbereitung numerischer Daten</h2>
<h3>Normalisierung</h3>
Step1: <h3>Standardisierung</h3>
Step2: Wann wird Normalisierung und wann wird Standardisierung verwendet ?
Standardisierung... | Python Code:
# import pandas as pd
# Zum Arbeiten mit Series
# Für die Normalisierung von Daten verwenden wir den MinMaxScaler
# Definieren einer Panda Series
# data=[11.0,201.0,301.0,41.0,501.0,601.0,701.0,81.0,901.0,1001.0]
# Worin besteht hier das Problem ?
data=[11.0,201.0,301.0,41.0,501.0,601.0,701.0,81.0,901.0,10... |
5,037 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
regular expressions
Step1: metacharacters
special characters that you can use in regular expressions that have a
special meaning
Step2: define your own character classes
inside your regul... | Python Code:
input_str = "Yes, my zip code is 12345. I heard that Gary's zip code is 23456. But 212 is not a zip code."
import re
zips= re.findall(r"\d{5}", input_str)
zips
from urllib.request import urlretrieve
urlretrieve("https://raw.githubusercontent.com/ledeprogram/courses/master/databases/data/enronsubjects.txt",... |
5,038 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Preparation
Step1: Set up for hour of day plots
Step2: Set up for Day of Week and Weekend vs Weekday plots
Step3: Plots
Motivation Weekday vs Weekend
Step4: The proportion of respo... | Python Code:
df = load_responses_with_traces()
df['click_dt_local'] = df.apply(lambda x: utc_to_local(x['click_dt_utc'], x['geo_data']['timezone']), axis = 1)
df = df[df['click_dt_local'].notnull()].copy()
print('Num Responses with a timezone', df.shape[0])
Explanation: Data Preparation
End of explanation
df['local_hou... |
5,039 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hypothesis Testing
Copyright 2016 Allen Downey
License
Step1: Part One
Suppose you observe an apparent difference between two groups and you want to check whether it might be due to chance.... | Python Code:
%matplotlib inline
import numpy
import scipy.stats
import matplotlib.pyplot as plt
import first
Explanation: Hypothesis Testing
Copyright 2016 Allen Downey
License: Creative Commons Attribution 4.0 International
End of explanation
live, firsts, others = first.MakeFrames()
Explanation: Part One
Suppose you ... |
5,040 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploratory Data Analysis Using Python and BigQuery
Learning Objectives
Analyze a Pandas Dataframe
Create Seaborn plots for Exploratory Data Analysis in Python
Write a SQL query to pick up ... | Python Code:
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Seaborn is a Python data visualization library based on matplotlib.
import seaborn as sns
from google.cloud import bigquery
%matplotlib inline
Explanation: Exploratory Data Analysis Using Python and BigQuery
Learning Objecti... |
5,041 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This demonstration shows how CCMC/FCIQMC [1,2] calculations with complex wavefunctions and replica tricks
can be analysed.
For clarity, the extractor, preparator and analyser are defined exp... | Python Code:
from pyhande.data_preparing.hande_ccmc_fciqmc import PrepHandeCcmcFciqmc
from pyhande.extracting.extractor import Extractor
from pyhande.error_analysing.blocker import Blocker
from pyhande.results_viewer.get_results import analyse_data
extra = Extractor() # Keep the defaults, merge using UUIDs.
prep = Pre... |
5,042 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statistical Moments - Skewness and Kurtosis
By Evgenia "Jenny" Nitishinskaya, Maxwell Margenot, and Delaney Granizo-Mackenzie.
Part of the Quantopian Lecture Series
Step1: Sometimes mean an... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
Explanation: Statistical Moments - Skewness and Kurtosis
By Evgenia "Jenny" Nitishinskaya, Maxwell Margenot, and Delaney Granizo-Mackenzie.
Part of the Quantopian Lecture Series:
www.quantopian.com/lectures
github.com/quantopian... |
5,043 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
Note
Step1: Listing 13.1
Step2: Listing 13.2
Step3: Listing 13.3
Step4:... | Python Code:
!curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2
!mkdir samples
!tar xvfj samples.tar.bz2 -C samples
import re
mo = re.search('hello', 'Hello world, hello Python!')
mo.group()
mo.span()
'Hello world, hello Python!'.index('hello')
import re
mo = re.sea... |
5,044 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook contains a resumed table of the q-learners results. The results are the ones evaluated on the test set, with the learned actions (without learning on the test set)
Step1: Pred... | Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sys
from time import time
import pickle
%matplotlib inline
%pylab inline
pylab.rcParams['figure.figsize'] = (20.0, 10.0)
%load_ext autoreload
%autoreload 2
sys.path.append('../../')
Explanation: This not... |
5,045 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building database
I have 6 SS WPS2 genomes, so I'll concatenate sequences into a single combined fasta file
Version 1.3
Step1: OK - verified
Running Blast query
Step2: Optimizing number of... | Python Code:
from Bio import SeqIO
import time
import os
import shutil
import pandas
#parameters
version = 'v1.4'
project_name = 'wps2_bl_metagenome'
e_value = 1e-20
iden = 95.0
metric = 50.0
!cat ../ss_genomes/AP_WPS-2_bacterium* > ../ss_genomes/all_AP_WPS-2_bacterium.fna
!makeblastdb -in ../ss_genomes/all_AP_WPS-2_ba... |
5,046 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
K-Means
Step1: Some of the parameters were don't change in these results, so we can delete them (natural number of clusters, dimensionality and number of iterations). Furthermore, We can de... | Python Code:
# necessary imports
%pylab inline
import seaborn as sns
import pandas as pd
# locations of the results
results_filename="/home/chiroptera/workspace/QCThesis/CUDA/tests/test1v2/results.csv" #local
#results_filename="https://raw.githubusercontent.com/Chiroptera/QCThesis/master/CUDA/tests/test1v2/results.csv"... |
5,047 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IST256 Lesson 07
Files
Zybook Ch7
P4E Ch7
Links
Participation
Step1: A. erry
B. berr
C. berry
D. bey
Vote Now
Step2: A. iic
B. ike
C. mic
D. iso
Vote Now
Step3: A. tony
B. tiny
C... | Python Code:
x = input()
if x.find("rr")!= -1:
y = x[1:]
else:
y = x[:-1]
print(y)
Explanation: IST256 Lesson 07
Files
Zybook Ch7
P4E Ch7
Links
Participation: https://poll.ist256.com
Zoom Chat!
Agenda
Go Over Homework H06
New Stuff
The importance of a persistence layer in programming.
How to read and write fro... |
5,048 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting a line chart in matplotlib
Step1: Plotting a line chart from a Pandas object
Step2: Creating bar charts
Step3: Creating a pie chart
Step4: Defining elements of a plot
Defining a... | Python Code:
x=range(1,10)
y=[1,2,3,4,0,4,3,2,1]
plt.plot(x,y)
Explanation: Plotting a line chart in matplotlib
End of explanation
# address = some data set
# cars = pd.read_csv(address)
# cars.columns = ['car_names','mpg','cyl','disp','hp','drat','wt','qsec','vs','am',gear',carb']
#mpg = cars['mpg']
#mpg.plot()
Expla... |
5,049 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'snu', 'sam0-unicon', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: SNU
Source ID: SAM0-UNICON
Topic: Atmos
Sub-Topics: Dynamical Core, Radiatio... |
5,050 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Author
Step1: Now that we already have general idea of Data Set. Let's work with features
Features 'pixel0' to 'pixel783'
Step2: First let's try to plot digit from first 5 data point
Step... | Python Code:
import pandas as pd
train_data=pd.read_csv('/train.csv')
train_data.head()
train_data.tail()
train_data.dtypes
train_data.info()
Explanation: Author : Vu Tran. Other info is on github
Kaggle Competition: Digit Recognizer
Info from Competition Site
Description
Evaluation
Data Set
First attempt:
Working wit... |
5,051 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Author
Step1: Yeah! Here are the percentages!
Dataset Sanity
We will check for data discrepancies.
Some variables (FAP, Application type) are expressed as codes and name. So we will check f... | Python Code:
import os
from os import path
import pandas as pd
import seaborn as _
DATA_FOLDER = os.getenv('DATA_FOLDER')
modes = pd.read_csv(path.join(DATA_FOLDER, 'imt/application_modes.csv'))
modes.head()
Explanation: Author: Marie Laure, marielaure@bayesimpact.org
Application modes (IMT) Dataset retrieved from empl... |
5,052 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DiscreteDP Example
Step4: Optimal solution
We skip the description of the model, just writing down the Bellman equation
Step6: For comparison, let us also consider the implementation with ... | Python Code:
%matplotlib inline
from __future__ import division, print_function
import numpy as np
import scipy.stats
import scipy.optimize
import scipy.sparse
from numba import jit
import matplotlib.pyplot as plt
from quantecon.markov import DiscreteDP
Explanation: DiscreteDP Example: Job Search
Daisuke Oyama
Faculty ... |
5,053 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This Colab demonstrates how to use the FuzzBench analysis library to show experiment results that might not be included in the default report.
Get the data
Each report contains a link to th... | Python Code:
!wget https://www.fuzzbench.com/reports/sample/data.csv.gz
Explanation: This Colab demonstrates how to use the FuzzBench analysis library to show experiment results that might not be included in the default report.
Get the data
Each report contains a link to the raw data, e.g., see the bottom of our samp... |
5,054 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Instalación
Para el correcto funcionamiento del código realizado para este proyecto es necesario seguir las siguientes indicaciones
Step1: Para la extracción y manejo de datos se creó una m... | Python Code:
%%bash
python descarga.py
Explanation: Instalación
Para el correcto funcionamiento del código realizado para este proyecto es necesario seguir las siguientes indicaciones:
1. Instalar los paquetes beautifulsoup4 y Requests en Python:
+ pip install beautifulsoup4 Requests.
2. Instalar Numpy.
+ sudo pip ... |
5,055 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using FastText via Gensim
This tutorial is about using fastText model in Gensim. There are two ways you can use fastText in Gensim - Gensim's native implementation of fastText and Gensim wra... | Python Code:
import gensim
import os
from gensim.models.word2vec import LineSentence
from gensim.models.fasttext import FastText as FT_gensim
# Set file names for train and test data
data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) + os.sep
lee_train_file = data_dir + 'lee_background.cor'
... |
5,056 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detailed A/B Test Experiment
Problem
There are 2 options for the landing page
Step1: Data Overview
Each pgeview is a unique cookie
Control group
Step2: Step 1 - Choose Metrics
Invariate Me... | Python Code:
import pandas as pd
import math
import numpy as np
from scipy.stats import norm
Explanation: Detailed A/B Test Experiment
Problem
There are 2 options for the landing page:
"start free trial"
If the visitor clicks this option, will be asked for credit card info, and after 14 days they will be charged automa... |
5,057 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Name
Data preparation by using a template to submit a job to Cloud Dataflow
Labels
GCP, Cloud Dataflow, Kubeflow, Pipeline
Summary
A Kubeflow Pipeline component to prepare data by using a te... | Python Code:
%%capture --no-stderr
KFP_PACKAGE = 'https://storage.googleapis.com/ml-pipeline/release/0.1.14/kfp.tar.gz'
!pip3 install $KFP_PACKAGE --upgrade
Explanation: Name
Data preparation by using a template to submit a job to Cloud Dataflow
Labels
GCP, Cloud Dataflow, Kubeflow, Pipeline
Summary
A Kubeflow Pipeline... |
5,058 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
20 newsgroups classification
Here we use the 20 newsgroups text dataset by Ken Lang, which is a dataset of 20,000 messages from 20 different newsgroups. One thousand messages from each newsg... | Python Code:
%autosave 120
import numpy as np
np.random.seed(1337)
from IPython.display import SVG
from keras.models import Model
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import (
Concatenate,
Conv1D,
Dense,
Dropout,
Embe... |
5,059 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithms Exercise 2
Imports
Step2: Peak finding
Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should
Step3: Here is a st... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
Explanation: Algorithms Exercise 2
Imports
End of explanation
def find_peaks(a):
Find the indices of the local maxima in a sequence.
peaks = []
data = np.array(a)
deriv = np.diff(data)
if de... |
5,060 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing initial point generation methods
Holger Nahrstaedt 2020
.. currentmodule
Step1: Toy model
We will use the
Step2: Objective
The objective of this example is to find one of these ... | Python Code:
print(__doc__)
import numpy as np
np.random.seed(123)
import matplotlib.pyplot as plt
Explanation: Comparing initial point generation methods
Holger Nahrstaedt 2020
.. currentmodule:: skopt
Bayesian optimization or sequential model-based optimization uses a surrogate
model to model the expensive to evaluat... |
5,061 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploration of Prudential Life Insurance Data
Data retrieved from
Step1: Seperation of columns into categorical, continous and discrete
Step2: Importing life insurance data set
Step3: Pre... | Python Code:
# Importing libraries
%pylab inline
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from sklearn import preprocessing
import numpy as np
# Convert variable data into categorical, continuous, discrete,
# and dummy variable lists the following in... |
5,062 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
7. Observing Systems
Previous
Step1: Import section specific modules
Step2: TODO
Step3: Figure 7.5.1
Step4: Figure 7.5.2
Step5: Figure 7.5.3
Step6: Figure 7.5.4
Step... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
Explanation: Outline
Glossary
7. Observing Systems
Previous: 7.4 Digital Correlators
Next: 7.6 Polarization and Antenna Feeds
Import standard modules:
End... |
5,063 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using marigoso to Post a Comment to a Blogger Post
A simple tutorial demonstrating how to use marigoso to automatically launch a browser and post a comment to a blog post.
Install marigoso
... | Python Code:
pip install -U marigoso
Explanation: Using marigoso to Post a Comment to a Blogger Post
A simple tutorial demonstrating how to use marigoso to automatically launch a browser and post a comment to a blog post.
Install marigoso
Execute the command below to install marigoso.
End of explanation
from marigoso ... |
5,064 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PS Clock Control
This notebook demonstrates how to use Clocks class to control the PL clocks.
By default, there are at most 4 PL clocks enabled in the system. They all can be reprogrammed to... | Python Code:
import os, warnings
from pynq import PL
from pynq import Overlay
if not os.path.exists(PL.bitfile_name):
warnings.warn('There is no overlay loaded after boot.', UserWarning)
Explanation: PS Clock Control
This notebook demonstrates how to use Clocks class to control the PL clocks.
By default, there are ... |
5,065 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-am4', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: GFDL-AM4
Topic: Atmos
Sub-Topics: Dynamical Core, Ra... |
5,066 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Q3
This question will focusing on indexing lists and dictionaries directly, no loops needed.
A
Reassign index to be the middle index of the list list_of_numbers. DO NOT hard-code a number (h... | Python Code:
import numpy as np
np.random.seed(8948394)
list_of_numbers = np.random.randint(10, size = 100000).tolist()
index = -1
### BEGIN SOLUTION
### END SOLUTION
Explanation: Q3
This question will focusing on indexing lists and dictionaries directly, no loops needed.
A
Reassign index to be the middle index of the ... |
5,067 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this post, we'll look at a couple of statistics functions in Python. These statistics functions are part of the Python Standard Library in the statistics module. The four functions we'll ... | Python Code:
from statistics import mean, median, mode, stdev
test_scores = [60 , 83, 83, 91, 100]
Explanation: In this post, we'll look at a couple of statistics functions in Python. These statistics functions are part of the Python Standard Library in the statistics module. The four functions we'll use in this post a... |
5,068 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
(OTBALN)=
2.1 Operaciones y transformaciones básicas del Álgebra Lineal Numérica
```{admonition} Notas para contenedor de docker
Step1: a)Para hacer ceros por debajo del pivote $a_1 = -2$
S... | Python Code:
import numpy as np
import math
np.set_printoptions(precision=3, suppress=True)
Explanation: (OTBALN)=
2.1 Operaciones y transformaciones básicas del Álgebra Lineal Numérica
```{admonition} Notas para contenedor de docker:
Comando de docker para ejecución de la nota de forma local:
nota: cambiar <ruta a ... |
5,069 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 27
Step1: They can be used in combination
Step2: The . character matches any character.
Step3: The .* is therefore used to match anything, any number of any character
Step4: .* is... | Python Code:
import re
beginsWithTheHelloRegex = re.compile(r'^Hello') # String must start exactly with 'Hello'
print(beginsWithTheHelloRegex.findall('Hello there'))
print(beginsWithTheHelloRegex.findall('Wait, did he say Hello just now?'))
print(beginsWithTheHelloRegex.findall('He said Hello'))
endsWithTheHelloRegex =... |
5,070 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have the following DF | Problem:
import pandas as pd
df = pd.DataFrame({'Date':['2019-01-01','2019-02-08','2019-02-08', '2019-03-08']})
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df['Date'].dt.strftime('%b-%Y') |
5,071 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Toy (counter-)example for anomaly decomposition
This is a carefully crafted example to demonstrate two possibly counter-intuitive results in anomaly decomposition study
Step1: Introducing 3... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('ggplot')
Explanation: Toy (counter-)example for anomaly decomposition
This is a carefully crafted example to demonstrate two possibly counter-intuitive results in anomaly decomposition study:
- ROC AUC < 0.5
- AUC for 'all... |
5,072 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tools for Game Theory
Daisuke Oyama
Faculty of Economics, University of Tokyo
This notebook demonstrates the functionalities of the game_theory module.
Step1: Normal Form Games
An $N$-playe... | Python Code:
from __future__ import division, print_function
import numpy as np
from normal_form_game import NormalFormGame, Player
Explanation: Tools for Game Theory
Daisuke Oyama
Faculty of Economics, University of Tokyo
This notebook demonstrates the functionalities of the game_theory module.
End of explanation
matc... |
5,073 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fibonacci Numbers
A Fibonacci number F(n) is computed as the sum of the two numbers preceeding it in a Fibonacci sequence
(0), 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...,
for example, F(10) = 55.... | Python Code:
def fibo_recurse(n):
if n <= 1:
return n
else:
return fibo_recurse(n-1) + fibo_recurse(n-2)
print(fibo_recurse(0))
print(fibo_recurse(1))
print(fibo_recurse(10))
Explanation: Fibonacci Numbers
A Fibonacci number F(n) is computed as the sum of the two numbers preceeding it in a ... |
5,074 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Non supervised learning
Autoencoders
Suppose we have only a set of unlabeled training examples $x_1,x_2,x_3, \dots $, where $x_i \in \Re^n$.
An autoencoder neural network is an unsupervised... | Python Code:
# Source: Adapted from https://blog.keras.io/building-autoencoders-in-keras.html
from keras.layers import Input, Dense
from keras.models import Model
# this is the size of our encoded representations
encoding_dim = 32 # 32 floats -> compression of factor 24.5,
# assuming the inp... |
5,075 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas and SQL
Pandas is a widely used python package for data analysis. We will mainly focus on pandas.DataFrame. Informally, you can think of a dataframe as an advanced relational table (o... | Python Code:
import pandas as pd
import numpy as np
import plotly.plotly as py
import plotly.graph_objs as go
Explanation: Pandas and SQL
Pandas is a widely used python package for data analysis. We will mainly focus on pandas.DataFrame. Informally, you can think of a dataframe as an advanced relational table (or a spr... |
5,076 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data science with IBM Planning Analytics
Cubike example - Part 2 and 3
Welcome to the second part of the Data Science with TM1/Planning Analytics.
In Part 1 , we uploaded in our TM1 cubes t... | Python Code:
import configparser
config = configparser.ConfigParser()
config.read(r'..\..\config.ini')
Explanation: Data science with IBM Planning Analytics
Cubike example - Part 2 and 3
Welcome to the second part of the Data Science with TM1/Planning Analytics.
In Part 1 , we uploaded in our TM1 cubes the weather dat... |
5,077 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
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', 'inpe', 'sandbox-1', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: INPE
Source ID: SANDBOX-1
Topic: Landice
Sub-Topics: Glaciers, Ice.
Prop... |
5,078 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Modular neural nets
In the previous exercise, we computed the loss and gradient for a two-layer neural network in a single monolithic function. This isn't very difficult for a small t... | Python Code:
# As usual, a bit of setup
import numpy as np
import matplotlib.pyplot as plt
from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient
from cs231n.layers import *
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.... |
5,079 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hello, TensorFlow
A beginner-level, getting started, basic introduction to TensorFlow
TensorFlow is a general-purpose system for graph-based computation. A typical use is machine learning. I... | Python Code:
from __future__ import print_function
import tensorflow as tf
with tf.Session():
input1 = tf.constant([1.0, 1.0, 1.0, 1.0])
input2 = tf.constant([2.0, 2.0, 2.0, 2.0])
output = tf.add(input1, input2)
result = output.eval()
print("result: ", result)
Explanation: Hello, TensorFlow
A beginn... |
5,080 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is based on this TensorFlow tutorial. It's been modified to use a SummaryWriter so we can track the training process using TensorBoard. For a nice getting started with TensorBo... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import math
import os
import random
import time
imp... |
5,081 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow实战Titanic解析
一、数据读入及预处理
1. 使用pandas读入csv文件,读入为pands.DataFrame对象
Step1: 2. 预处理
剔除空数据
将'Sex'字段转换为int类型
选取数值类型的字段,抛弃字符串类型字段
Step2: 3. 将训练数据切分为训练集(training set)和验证集(validation set)
St... | Python Code:
import os
import numpy as np
import pandas as pd
import tensorflow as tf
# read data from file
data = pd.read_csv('data/train.csv')
print(data.info())
Explanation: TensorFlow实战Titanic解析
一、数据读入及预处理
1. 使用pandas读入csv文件,读入为pands.DataFrame对象
End of explanation
# fill nan values with 0
data = data.fillna(0)
# co... |
5,082 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VAEs on sparse data
The following notebook provides an example of how to load a dataset, setup parameters for it, create the model
and train it for a few epochs.
In the notebook, we will use... | Python Code:
import sys,os,glob
from collections import OrderedDict
import numpy as np
from utils.misc import readPickle, createIfAbsent
sys.path.append('../')
from optvaedatasets.load import loadDataset as loadDataset_OVAE
from sklearn.feature_extraction.text import TfidfTransformer
Explanation: VAEs on sparse data
Th... |
5,083 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<img align="left" style="padding-right
Step1: Once this submodule is imported, a three-dimensional axes can be created by passing the keyword projection='3d' to any ... | Python Code:
from mpl_toolkits import mplot3d
Explanation: <!--BOOK_INFORMATION-->
<img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png">
This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the content is available on GitHub.
The text is released under ... |
5,084 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Corrections et révisions
Nom de variables et type
Step1: Donc attention aux nom donné aux paramêtres formels, il peut être aussi utile de se premunir contre des fautes, en utilisant la comm... | Python Code:
def tronquer_1( l ):
return l[1:]
l=[1,2,3]
tronquer_1(l)
Explanation: Corrections et révisions
Nom de variables et type
End of explanation
def tronquer_liste( ma_liste ):
try:
return ma_liste[1:]
except TypeError:
print("Cette fonction n'accepte que des listes ou des chaînes de... |
5,085 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multimodal entailment
Author
Step1: Imports
Step2: Define a label map
Step3: Collect the dataset
The original dataset is available
here.
It comes with URLs of images which are hosted on T... | Python Code:
!pip install -q tensorflow_text
Explanation: Multimodal entailment
Author: Sayak Paul<br>
Date created: 2021/08/08<br>
Last modified: 2021/08/15<br>
Description: Training a multimodal model for predicting entailment.
Introduction
In this example, we will build and train a model for predicting multimodal en... |
5,086 | 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... |
5,087 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook can be used to test the basic features of a Catalog object, which is defined in by the class definition in skyofstars/catalogs.py. This will only work if you have installed sky... | Python Code:
# import everything from skyofstars
from skyofstars.examples import *
example = create_test_catalog()
Explanation: This notebook can be used to test the basic features of a Catalog object, which is defined in by the class definition in skyofstars/catalogs.py. This will only work if you have installed sky-o... |
5,088 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This work was done by Harsh Gupta as part of his internship at The Center for Internet & Society India
Step2: Encrypted Media Extension Diversity Analysis
Encrypted Media Extension (EME) is... | Python Code:
import bigbang.mailman as mailman
import bigbang.process as process
from bigbang.archive import Archive
import pandas as pd
import datetime
from commonregex import CommonRegex
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: This work was done by Harsh Gupta as part of his internship at The ... |
5,089 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LAB 2b
Step1: Set environment variables so that we can use them throughout the entire lab. We will be using our project ID for our bucket.
Step2: The source dataset
Our dataset is hosted i... | Python Code:
import os
from google.cloud import bigquery
Explanation: LAB 2b: Prepare babyweight dataset.
Learning Objectives
Setup up the environment
Preprocess natality dataset
Augment natality dataset
Create the train and eval tables in BigQuery
Export data from BigQuery to GCS in CSV format
Introduction
In this no... |
5,090 | 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="#"Living-in-a-noisy-world...",-using-James-Powell's-(dutc)-rwatch-module" data-toc-modified-id=""Living-in-a-noisy-wor... | Python Code:
import numpy as np
np.random.seed(1234)
np.random.normal()
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#"Living-in-a-noisy-world...",-using-James-Powell's-(dutc)-rwatch-module" data-toc-modified-id=""Living-in-a-noisy-world...",-using-James-Powell's-(dutc)-rwat... |
5,091 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
確率分布と乱数の取得
Step1: 練習問題
(1) 2個のサイコロを振った結果をシュミレーションします。次の例のように、1〜6の整数のペアを含むarrayを乱数で生成してください。
Step2: (2) 2個のサイコロを振った結果を10回分用意します。次の例のように、1〜6の整数のペア(リスト)を10組含むarrayを生成して、変数 dice に保存してください。
Ste... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import Series, DataFrame
Explanation: 確率分布と乱数の取得
End of explanation
from numpy.random import randint
randint(1,7,2)
Explanation: 練習問題
(1) 2個のサイコロを振った結果をシュミレーションします。次の例のように、1〜6の整数のペアを含むarrayを乱数で生成してください。
End of explanation
di... |
5,092 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 1 - Observe the Real Data
The Data below is the real observations.
We can see 2 peaks in the data, one with the center around 120 and the other with the center around 200.
Felt like bin... | Python Code:
figsize(12.5, 4)
data = np.loadtxt("../data/mixture_data.csv", delimiter=",")
plt.hist(data, bins=20, color="g", histtype="stepfilled", alpha=0.8)
plt.title("The Distribution of Mixture_Data Dataset")
plt.ylim([0, None]);
print(data[:10], "...")
Explanation: Step 1 - Observe the Real Data
The Data below is... |
5,093 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random Sampling
Credits
Step1: Part One
Suppose we want to estimate the average weight of men and women in the U.S.
And we want to quantify the uncertainty of the estimate.
One approach is ... | Python Code:
from __future__ import print_function, division
import numpy
import scipy.stats
import matplotlib.pyplot as pyplot
from IPython.html.widgets import interact, fixed
from IPython.html import widgets
# seed the random number generator so we all get the same results
numpy.random.seed(18)
# some nicer colors fr... |
5,094 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Theoretical Efficiency of Read Until Enrichment
The "Read Until" feature of the Oxford Nanopore sequencing technology means a program can see the data coming in at each pore and, dependend o... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
def sim_ru(ham_frequency, ham_duration, accuracy):
# Monte-Carlo Style
n = 1000000
ham = np.random.random(size=n)<ham_frequency
durations = np.ones(n)
accurate = np.random.random(size=n)<accuracy
durations[ham & a... |
5,095 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Can I use string as input for a DecisionTreeClassifier? | Problem:
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
X = [['asdf', '1'], ['asdf', '0']]
clf = DecisionTreeClassifier()
from sklearn.feature_extraction import DictVectorizer
X = [dict(enumerate(x)) for x in X]
vect = DictVectorizer(sparse=False)
new_X = vect.fit_transform(X) |
5,096 | 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', 'csir-csiro', 'sandbox-3', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: CSIR-CSIRO
Source ID: SANDBOX-3
Sub-Topics: Radiative Forcings.
... |
5,097 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Terminal Velocity
by Paulo Marques, 2013/09/23
This notebook discusses the <a href="http
Step1: We now define the initial conditions and constants of the problem.
Step2: As said, let's def... | Python Code:
%pylab inline
from scipy.integrate import odeint
from math import sqrt, atan
Explanation: Terminal Velocity
by Paulo Marques, 2013/09/23
This notebook discusses the <a href="http://en.wikipedia.org/wiki/Drag_(physics)">drag forces</a> exerted on a body when traveling through air.
A falling body is su... |
5,098 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gapfillling
GrowMatch and SMILEY are gap-filling algorithms, which try to to make the minimal number of changes to a model and allow it to simulate growth. For more information, see Kumar et... | Python Code:
import cobra.test
model = cobra.test.create_test_model("salmonella")
Explanation: Gapfillling
GrowMatch and SMILEY are gap-filling algorithms, which try to to make the minimal number of changes to a model and allow it to simulate growth. For more information, see Kumar et al.. Please note that these algori... |
5,099 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Flux Noise Mask Design
General Notes
Step1: CPW
We want to use the same cpw dimensions for resonator and feedline/purcell filter cpw's so the kinetic inductance correction is the same for e... | Python Code:
qubits = []
for i in range(3):
q = qubit.Qubit('Transmon')
q.C_g = 3.87e-15
q.C_q = 75.1e-15
q.C_resToGnd = 79.1e-15
qubits.append(q)
q = qubit.Qubit('OCSQubit')
q.C_g = 2.94e-15
q.C_q = 48.5e-15
q.C_resToGnd = 51.5e-15
qubits.append(q)
Explanation: Flux Noise Mask Design
General Notes:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.