markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
对象检测
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://tensorflow.google.cn/hub/tutorials/object_detection"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png">View 在 TensorFlow.org 上查看</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/te... | #@title Imports and function definitions
# For running inference on the TF-Hub module.
import tensorflow as tf
import tensorflow_hub as hub
# For downloading the image.
import matplotlib.pyplot as plt
import tempfile
from six.moves.urllib.request import urlopen
from six import BytesIO
# For drawing onto the image.
... | site/zh-cn/hub/tutorials/object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
使用示例
用于下载图像和可视化的辅助函数。
为了实现最简单的必需功能,根据 TF 对象检测 API 改编了可视化代码。 | def display_image(image):
fig = plt.figure(figsize=(20, 15))
plt.grid(False)
plt.imshow(image)
def download_and_resize_image(url, new_width=256, new_height=256,
display=False):
_, filename = tempfile.mkstemp(suffix=".jpg")
response = urlopen(url)
image_data = response.read()
... | site/zh-cn/hub/tutorials/object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
应用模块
从 Open Images v4 加载公共图像,并在本地保存和显示。 | # By Heiko Gorski, Source: https://commons.wikimedia.org/wiki/File:Naxos_Taverna.jpg
image_url = "https://upload.wikimedia.org/wikipedia/commons/6/60/Naxos_Taverna.jpg" #@param
downloaded_image_path = download_and_resize_image(image_url, 1280, 856, True) | site/zh-cn/hub/tutorials/object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
选择对象检测模块并应用于下载的图像。模块包括:
FasterRCNN+InceptionResNet V2:高准确率。
ssd+mobilenet V2:小而快。 | module_handle = "https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1" #@param ["https://tfhub.dev/google/openimages_v4/ssd/mobilenet_v2/1", "https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1"]
detector = hub.load(module_handle).signatures['default']
def load_img(path):
im... | site/zh-cn/hub/tutorials/object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
更多图像
使用时间跟踪对部分其他图像进行推理。 | image_urls = [
# Source: https://commons.wikimedia.org/wiki/File:The_Coleoptera_of_the_British_islands_(Plate_125)_(8592917784).jpg
"https://upload.wikimedia.org/wikipedia/commons/1/1b/The_Coleoptera_of_the_British_islands_%28Plate_125%29_%288592917784%29.jpg",
# By Américo Toledano, Source: https://commons.wikim... | site/zh-cn/hub/tutorials/object_detection.ipynb | tensorflow/docs-l10n | apache-2.0 |
2. Different ways of learning from data
Now let's say we want to predict the type of flower for a new given data point. There are multiple ways to solve this problem. We will consider these two ways in some detail:
We could find a function which can directly map an input value to it's class label.
We can find the p... | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# Adding a little bit of noise so that it's easier to visualize
data_with_noise = data.iloc[:, :2] + np.random.normal(loc=0, scale=0.1, size=(150, 2))
plt.scatter(data_with_noise.length, data_with_noise.width, c=[ "bgr"[k] for k in data.iloc[:,2] ],... | notebooks/1. Introduction to Probabilistic Graphical Models.ipynb | pgmpy/pgmpy_notebook | mit |
In the plot we can easily see that the blue points are concentrated on the top-left corner, green ones in bottom left and red ones in top right.
Now let's try to train a Decision Tree on this data. | from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(data[['length', 'width']].values, data.type.values, test_size=0.2)
classifier = DecisionTreeClassifier(max_depth=4)
classifier.fit(X_train, y_train)
classifier.predi... | notebooks/1. Introduction to Probabilistic Graphical Models.ipynb | pgmpy/pgmpy_notebook | mit |
So, in this case we got a classification accuracy of 60 %.
Now moving on to our second approach using a probabilistic model.
The most obvious way to do this classification task would be to compute a Joint Probability Distribution over all these variables and then marginalize and reduce over these according to our new d... | X_train, X_test = data[:120], data[120:]
X_train
# Computing the joint probability distribution over the training data
joint_prob = X_train.groupby(['length', 'width', 'type']).size() / 120
joint_prob
# Predicting values
# Selecting just the feature variables.
X_test_features = X_test.iloc[:, :2].values
X_test_actu... | notebooks/1. Introduction to Probabilistic Graphical Models.ipynb | pgmpy/pgmpy_notebook | mit |
Basic Concepts I
What is "learning from data"?
In general Learning from Data is a scientific discipline that is concerned with the design and development of algorithms that allow computers to infer (from data) a model that allows compact representation (unsupervised learning) and/or good generalization (supervised le... | # numerical derivative at a point x
def f(x):
return x**2
def fin_dif(x, f, h = 0.00001):
'''
This method returns the derivative of f at x
by using the finite difference method
'''
return (f(x+h) - f(x))/h
x = 2.0
print "{:2.4f}".format(fin_dif(x,f)) | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
The limit as $h$ approaches zero, if it exists, should represent the slope of the tangent line to $(x, f(x))$.
For values that are not zero it is only an approximation. | for h in np.linspace(0.0, 1.0 , 5):
print "{:3.6f}".format(f(5+h)), "{:3.6f}".format(f(5)+h*fin_dif(5,f))
x = np.linspace(-1.5,-0.5, 100)
f = [i**2 for i in x]
plt.plot(x,f, 'r-')
plt.plot([-1.5, -0.5], [2, 0.0], 'k-', lw=2)
plt.plot([-1.4, -1.0], [1.96, 1.0], 'b-', lw=2)
plt.plot([-1],[1],'o')
plt.plot([-1.4],[1.... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
It can be shown that the “centered difference formula" is better when computing numerical derivatives:
$$ \lim_{h \rightarrow 0} \frac{f(x + h) - f(x - h)}{2h} $$
The error in the "finite difference" approximation can be derived from Taylor's theorem and, assuming that $f$ is differentiable, is $O(h)$. In the case of “... | W = 400
H = 250
bp.output_notebook()
x = np.linspace(-15,15,100)
y = x**2
TOOLS = [WheelZoomTool(), ResetTool(), PanTool()]
s1 = bp.figure(width=W, plot_height=H,
title='Local minimum of function',
tools=TOOLS)
s1.line(x, y, color="navy", alpha=0.5, line_width=3)
s1.circle(0, 0, size... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
There are two problems with numerical derivatives:
+ It is approximate.
+ It is very slow to evaluate (two function evaluations: $f(x + h) , f(x - h)$ ).
Our knowledge from Calculus could help!
We know that we can get an analytical expression of the derivative for some functions.
For example, let's suppose we have a s... | x = np.linspace(-10,20,100)
y = x**2 - 6*x + 5
TOOLS = [WheelZoomTool(), ResetTool(), PanTool()]
s1 = bp.figure(width=W, plot_height=H,
tools=TOOLS)
s1.line(x, y, color="navy", alpha=0.5, line_width=3)
s1.circle(3, 3**2 - 6*3 + 5, size =10, color="orange")
s1.title_text_font_size = '12pt'
s1.yaxis.a... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Second approach
To find the local minimum using gradient descend: you start at a random point, and move into the direction of steepest descent relative to the derivative:
Start from a random $x$ value.
Compute the derivative $f'(x)$ analitically.
Walk a small step in the opposite direction of the derivative.
In this... | x = np.linspace(-10,20,100)
y = x**2 - 6*x + 5
start = 15
TOOLS = [WheelZoomTool(), ResetTool(), PanTool()]
s1 = bp.figure(width=W, plot_height=H,
tools=TOOLS)
s1.line(x, y, color="navy", alpha=0.5, line_width=3)
s1.circle(start, start**2 - 6*start + 5, size =10, color="orange")
d = 2 * start - 6
en... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
To fix this, we multiply the gradient by a step size. This step size (often called alpha) has to be chosen carefully, as a value too small will result in a long computation time, while a value too large will not give you the right result (by overshooting) or even fail to converge.
In this example, we'll set the step s... | old_min = 0
temp_min = 15
step_size = 0.01
precision = 0.0001
def f_derivative(x):
import math
return 2*x -6
mins = []
cost = []
while abs(temp_min - old_min) > precision:
old_min = temp_min
gradient = f_derivative(old_min)
move = gradient * step_size
temp_min = old_min - move
cost.app... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
An important feature of gradient descent is that there should be a visible improvement over time: In this example, we simply plotted the squared distance from the local minima calculated by gradient descent and the true local minimum, cost, against the iteration during which it was calculated. As we can see, the dista... | TOOLS = [WheelZoomTool(), ResetTool(), PanTool()]
x, y = (zip(*enumerate(cost)))
s1 = bp.figure(width=W,
height=H,
title='Squared distance to true local minimum',
# title_text_font_size='14pt',
tools=TOOLS,
x_axis_label = 'Iteration',
... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
From derivatives to gradient: $n$-dimensional function minimization.
Let's consider a $n$-dimensional function $f: \Re^n \rightarrow \Re$. For example:
$$f(\mathbf{x}) = \sum_{n} x_n^2$$
Our objective is to find the argument $\mathbf{x}$ that minimizes this function.
The gradient of $f$ is the vector whose components... | def f(x):
return sum(x_i**2 for x_i in x)
def fin_dif_partial_centered(x, f, i, h=1e-6):
w1 = [x_j + (h if j==i else 0) for j, x_j in enumerate(x)]
w2 = [x_j - (h if j==i else 0) for j, x_j in enumerate(x)]
return (f(w1) - f(w2))/(2*h)
def fin_dif_partial_old(x, f, i, h=1e-6):
w1 = [x_j + (h if j=... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Let's start by choosing a random vector and then walking a step in the opposite direction of the gradient vector. We will stop when the difference between the new solution and the old solution is less than a tolerance value. | # choosing a random vector
import random
import numpy as np
x = [random.randint(-10,10) for i in range(3)]
x
def step(x,grad,alpha):
return [x_i - alpha * grad_i for x_i, grad_i in zip(x,grad)]
tol = 1e-15
alpha = 0.01
while True:
grad = gradient_centered(x,f)
next_x = step(x,grad,alpha)
if euc_dist... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Learning from data
In general, we have:
A dataset $(\mathbf{x},y)$.
A target function $f_\mathbf{w}$, that we want to minimize, representing the discrepancy between our data and the model we want to fit. The model is represented by a set of parameters $\mathbf{w}$.
The gradient of the target function, $g_f$.
In th... | # f = 2x
x = range(100)
y = [2*i for i in x]
# f_target = Sum (y - wx)**2
def target_f(x,y,w):
import numpy as np
return np.sum((np.array(y) - np.array(x) * w)**2.0)
# gradient_f = Sum 2wx**2 - 2xy
def gradient_f(x,y,w):
import numpy as np
return np.sum(2*w*(np.array(x)**2) - 2*np.array(x)*np.array(y)... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Stochastic Gradient Descend
The last function evals the whole dataset $(\mathbf{x}_i,y_i)$ at every step.
If the dataset is large, this strategy is too costly. In this case we will use a strategy called SGD (Stochastic Gradient Descend).
When learning from data, the cost function is additive: it is computed by adding ... | import numpy as np
x = range(10)
y = [2*i for i in x]
data = zip(x,y)
def in_random_order(data):
import random
indexes = [i for i,_ in enumerate(data)]
random.shuffle(indexes)
for i in indexes:
yield data[i]
for (x_i,y_i) in in_random_order(data):
print x_i,y_i
def gradient_f_SGD... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Exercise: Gradient Descent and Linear Regression
The linear regression model assumes a linear relationship between data:
$$ y_i = w_1 x_i + w_0 $$
Let's generate a more realistic dataset (with noise), where $w_1 = 2$ and $w_0 = 0$: | import numpy as np
x = np.random.uniform(0,1,20)
def f(x): return x*2
noise_variance =0.2
noise = np.random.randn(x.shape[0])*noise_variance
y = f(x) + noise
plt.plot(x, y, 'o', label='y')
plt.plot([0, 1], [f(0), f(1)], 'b-', label='f(x)')
plt.xlabel('$x$', fontsize=15)
plt.ylabel('$t$', fontsize=15)
plt.ylim([0,2])... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Complete the following code and look at the plot of the first gradient descent updates. Explore the behavior of the proposed learning rates. | def gradient(w, x, y):
return 2 * x * (nn(x, w) - y)
def step(w_k, x, y, learning_rate):
return learning_rate * gradient(w_k, x, y).sum()
w = 0.01
# define a learning_rate
learning_rate = 0.1
nb_of_iterations = 20
w_cost = [(w, cost(nn(x, w), y))]
for i in range(nb_of_iterations):
# Here your code ... | 1. Basic Concepts I.ipynb | jvitria/DeepLearningBBVA2016 | mit |
Macierz kolumnowa w NumPy.
$$X =
\begin{pmatrix}
3 \
4 \
5 \
6
\end{pmatrix}$$ | x = np.array([[3,4,5,6]]).T
x | Cwiczenia/01/Uczenie Maszynowe - Ćwiczenia 1.3 - NumPy, algebra liniowa.ipynb | emjotde/UMZ | cc0-1.0 |
A macierz wierszowa w NumPy.
$$ X =
\begin{pmatrix}
3 & 4 & 5 & 6
\end{pmatrix}$$ | x = np.array([[3,4,5,6]])
x | Cwiczenia/01/Uczenie Maszynowe - Ćwiczenia 1.3 - NumPy, algebra liniowa.ipynb | emjotde/UMZ | cc0-1.0 |
Obiekty typu matrix
Macierze ogólne omówiliśmy już w poprzednich dokumentach:
$$A_{m,n} =
\begin{pmatrix}
a_{1,1} & a_{1,2} & \cdots & a_{1,n} \
a_{2,1} & a_{2,2} & \cdots & a_{2,n} \
\vdots & \vdots & \ddots & \vdots \
a_{m,1} & a_{m,2} & \cdots & a_{m,n}
\end{pmatrix}$$
Oprócz obiektów ... | x = np.array([1,2,3,4,5,6,7,8,9]).reshape(3,3)
x
X = np.matrix(x)
X | Cwiczenia/01/Uczenie Maszynowe - Ćwiczenia 1.3 - NumPy, algebra liniowa.ipynb | emjotde/UMZ | cc0-1.0 |
Operacje na macierzach
Wyznacznik | a = np.array([[3,-9],[2,5]])
np.linalg.det(a) | Cwiczenia/01/Uczenie Maszynowe - Ćwiczenia 1.3 - NumPy, algebra liniowa.ipynb | emjotde/UMZ | cc0-1.0 |
Macierz odwrotna | A = np.array([[-4,-2],[5,5]])
A
invA = np.linalg.inv(A)
invA
np.round(np.dot(A,invA)) | Cwiczenia/01/Uczenie Maszynowe - Ćwiczenia 1.3 - NumPy, algebra liniowa.ipynb | emjotde/UMZ | cc0-1.0 |
Ponieważ $AA^{-1} = A^{-1}A = I$.
Wartości i wektory własne | a = np.diag((1, 2, 3))
a
w,v = np.linalg.eig(a)
w
v | Cwiczenia/01/Uczenie Maszynowe - Ćwiczenia 1.3 - NumPy, algebra liniowa.ipynb | emjotde/UMZ | cc0-1.0 |
The resulting dictionary accepted_papers contains a list of the accepted papers for each conference. | for conference, papers in sorted(accepted_papers.items()):
print('{conference} includes {papers} accepted papers.'.format(
conference=conference, papers=len(papers))) | paper_selection.ipynb | aaai2018-paperid-62/aaai2018-paperid-62 | mit |
Selection
A sample population of 100 papers is selected from each conference using Python's pseudo-random number module. As per the documentation on random.sample "The resulting list is in selection order so that all sub-slices will also be valid random samples." The seed is set to the unix timestamp for Jan 10 14:46:4... | import random
random.seed(1484059600)
k = 100
samples = {}
# The order is set explicitly due to originally not sorting
# accepted_papers.items().
conferences = ['aaai-16', 'aaai-14', 'ijcai-13', 'ijcai-16']
for conference in conferences:
samples[conference] = random.sample(accepted_papers[conference], k) | paper_selection.ipynb | aaai2018-paperid-62/aaai2018-paperid-62 | mit |
Note that when originally generating the samples, the dictionary was iterated by the use of Python 3's dict.items() view. The order is not guaranteed. Due to the original generation not being sorted, the iteration needs to be set explicitly so future runs generate the same original sample populations.
The generated ran... | for conference, papers in samples.items():
outputfile = 'data/sampled_{conference}'.format(conference=conference)
with open(outputfile, 'w') as f:
for line in papers:
f.write(line) | paper_selection.ipynb | aaai2018-paperid-62/aaai2018-paperid-62 | mit |
Versions
Here's a generated output to keep track of software versions used to run this Jupyter notebook. | import IPython
import platform
print('Python version: {}'.format(platform.python_version()))
print('IPython version: {}'.format(IPython.__version__)) | paper_selection.ipynb | aaai2018-paperid-62/aaai2018-paperid-62 | mit |
Set where to write Lya ensemble dflux. | outdir = '/global/homes/m/mjwilson/sandbox/lya-signal/desimodel/0.14.0/data/tsnr' | doc/nb/Lya-tsnr-signal.ipynb | desihub/desispec | bsd-3-clause |
Load a set of Vi'd Lya QSOs. | dat = fits.open('/project/projectdirs/desi/spectro/redux/cascades/tiles/80609/deep/coadd-0-80609-deep.fits')
dat.info()
vi = pandas.read_csv('/project/projectdirs/desi/sv/vi/TruthTables/Blanc/QSO/desi-vi_QSO_tile80609_nightdeep_merged_all_210210_ADDING_object_info.csv')
vi
isin = (vi['best_spectype'] == 'QSO') & (v... | doc/nb/Lya-tsnr-signal.ipynb | desihub/desispec | bsd-3-clause |
Our QSOs | fig, axes = plt.subplots(nin, 1, figsize=(5, 5 * nin))
for band in ['B','R','Z']:
for i, x in enumerate(dat['{}_FLUX'.format(band)].data[isin]):
axes[i].plot(dat['{}_WAVELENGTH'.format(band)].data, convolve(x, gauss_kernel), lw=0.5)
axes[i].set_ylim(bottom=-0.5) | doc/nb/Lya-tsnr-signal.ipynb | desihub/desispec | bsd-3-clause |
Take closest to g=22 to be our reference. | idx = np.where(np.abs(gmags - 22.) == np.abs(gmags - 22.).min())[0][0]
# Force 7
idx = 7
# Closest to 22.
master_fluxes = {'gmag': gmags[idx], 'tid': fmap_ids[idx]}
for band in ['B', 'R', 'Z']:
master_fluxes[band] = {'wave': dat['{}_WAVELENGTH'.format(band)].data,
'smo... | doc/nb/Lya-tsnr-signal.ipynb | desihub/desispec | bsd-3-clause |
Later we use this (by eye) 'continuum' as our asymptotic 'signal' normalization at the blue end.
Get a QSO n(z) | # https://desi.lbl.gov/svn/code/desimodel/tags/0.14.0/data/targets/nz_qso.dat;
# Number per sq. deg. per dz=0.1
# Note: Cascades
zlo, zhi, Nz = np.loadtxt('/global/common/software/desi/cori/desiconda/20200801-1.4.0-spec/code/desimodel/0.14.0/data/targets/nz_qso.dat', unpack=True)
zmid = 0.5 * (zlo + zhi)
Nz /= Nz.ma... | doc/nb/Lya-tsnr-signal.ipynb | desihub/desispec | bsd-3-clause |
Here we've drawn an ensemble of zs from this distribution. | pl.plot(zmid, 5000. * Nz, c='k', lw=0.5)
pl.hist(qso_zs, bins=np.arange(0.0, 5.0, 0.05), alpha=0.5)
pl.xlabel('z')
lya_zs = qso_zs[qso_zs > 2.1]
lya_zs
# lya_zs = lya_zs[:2]
# 1216. * (1. + lya_zs)
nlya = len(lya_zs) | doc/nb/Lya-tsnr-signal.ipynb | desihub/desispec | bsd-3-clause |
Our 'signal' will be unity bluer than Lya for a given redshift (zero otherwise). We then stack across the ensemble. | tracer = 'LYA'
hdr = fits.Header()
hdr['NMODEL'] = nlya
hdr['TRACER'] = tracer
hdr['FILTER'] = 'decam2014-g'
hdr['ZLO'] = 2.1
hdu_list = [fits.PrimaryHDU(header=hdr)]
for band in ['b', 'r', 'z']:
wave = dat['{}_WAVELENGTH'.format(band)].data
nwave = wave[:,None] * np.ones(... | doc/nb/Lya-tsnr-signal.ipynb | desihub/desispec | bsd-3-clause |
Finally, here we've used our reference continuum from above as the blue end normalization and write to disk at outdir.
Check against QSO tsnr. | ens = fits.open('/global/common/software/desi/cori/desiconda/20200801-1.4.0-spec/code/desimodel/0.14.0/data/tsnr/tsnr-ensemble-qso.fits')
ens.info()
ens['DFLUX_B'].shape | doc/nb/Lya-tsnr-signal.ipynb | desihub/desispec | bsd-3-clause |
Non-rigid surface deformation
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/graphics/blob/master/tensorflow_graphics/notebooks/non_rigid_deformation.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run i... | !pip install tensorflow_graphics | tensorflow_graphics/notebooks/non_rigid_deformation.ipynb | tensorflow/graphics | apache-2.0 |
Now that Tensorflow Graphics is installed, let's import everything needed to run the demo contained in this notebook. | import numpy as np
import tensorflow as tf
from tensorflow_graphics.geometry.deformation_energy import as_conformal_as_possible
from tensorflow_graphics.geometry.representation.mesh import utils as mesh_utils
from tensorflow_graphics.geometry.transformation import quaternion
from tensorflow_graphics.math.optimizer imp... | tensorflow_graphics/notebooks/non_rigid_deformation.ipynb | tensorflow/graphics | apache-2.0 |
In this example, we build a mesh that corresponds to a flat and rectangular surface. Using the sliders, you can control the position of the deformation constraints applied to that surface, which respectively correspond to all the points along the left boundary, center, and right boundary of the mesh. | mesh_rest_pose = triangulated_stripe.mesh
connectivity = mesh_utils.extract_unique_edges_from_triangular_mesh(triangulated_stripe.mesh['faces'])
camera = threejs_visualization.build_perspective_camera(
field_of_view=40.0, position=(0.0, -5.0, 5.0))
width = 500
height = 500
_ = threejs_visualization.triangular_mesh_... | tensorflow_graphics/notebooks/non_rigid_deformation.ipynb | tensorflow/graphics | apache-2.0 |
Applying to Test Dataset | Org_blind_data = pd.read_csv('../data/nofacies_data.csv')
blind_data = Org_blind_data[Org_blind_data["NM_M"]==1]
X_blind = blind_data.drop(['Formation', 'Well Name', 'Depth'], axis=1).values
well_blind = blind_data['Well Name'].values
depth_blind = blind_data['Depth'].values
X_blind, padded_rows = augment_features(X_... | PA_Team/PA_Team_Submission_4-revised.ipynb | seg/2016-ml-contest | apache-2.0 |
Instead of writing s = s + i we could have written s += i (read this as "s is whatever it was before plus the value of i"). So we could rewrite that for loop as: | x = [2,4,6,8,10]
s = 0
for i in x:
s += i
print("The sum of x is:", s) | Mathematical-Notation-Sums-and-Products.ipynb | Bio204-class/bio204-notebooks | cc0-1.0 |
Now what if we wanted to calculate the sum of the reciprocals of each element of x? A simple change to our code give us: | x = [2,4,6,8,10]
s = 0
for i in x:
s += (1/i)
print("The sum of the reciprocals of x is:", s) | Mathematical-Notation-Sums-and-Products.ipynb | Bio204-class/bio204-notebooks | cc0-1.0 |
To bring things full circle, the equivalent mathematical notation to represent the operation of summing the reciprocals of all the elements of $\mathbf{x}$ would be:
$$
\sum_{i=1}^n \frac{1}{\mathbf{x}_i}
$$
The code above is somewhat fragile in that it's not easily re-usable. What if we wanted to sum the reciprocals o... | def sum_of_reciprocals(x):
s = 0
for i in x:
s += (1.0/i)
return s
# test our function with different inputs
x = [2,4,6,8,10]
y = [1,3,5,7,9]
z = [-1,1,-1,1]
print("The sum of the reciprocals of x is:", sum_of_reciprocals(x))
print("The sum of the reciprocals of y is:", sum_of_reciprocals(y))
prin... | Mathematical-Notation-Sums-and-Products.ipynb | Bio204-class/bio204-notebooks | cc0-1.0 |
A even more compact way of writing our sum of reciprocals operation, that still used the built in sum function would be to use a list comprehension as shown below: | sum_recip_x = sum([(1.0/i) for i in x])
print("The sum of the reciprocals of x is: ", sum_recip_x) | Mathematical-Notation-Sums-and-Products.ipynb | Bio204-class/bio204-notebooks | cc0-1.0 |
Note that our sum_of_reciprocals function (or our solution using list comprehensions) doesn't deal with all possible cases we might use as input. If one of the elements of x was zero what would happen (go ahead and try it)? What if we passed a list of strings to the function instead of numbers?
Product notation
Now t... | def product(x):
p = 1
for i in x:
p *= i # same as p = p * i
return p
x = [2,4,6,8,10]
product(x)
product([(1.0/i) for i in x]) # use list comprehension to get reciprocals of x | Mathematical-Notation-Sums-and-Products.ipynb | Bio204-class/bio204-notebooks | cc0-1.0 |
Label some/all states
In our structure of the code, the states should be a dictionary, the key is the index in the sequence (e.g. 0, 5) and the value is a one-out-of-n code of array where the kth value is 1 if the hidden state is k. n is the number of states in total.
In the following example, we assume that the "corr"... | states = {}
corr = np.array(speed['corr'])
for i in range(len(corr)):
state = np.zeros((2,))
if corr[i] == 'cor':
states[i] = np.array([0,1])
else:
states[i] = np.array([1,0]) | examples/notebooks/SupervisedIOHMM.ipynb | Mogeng/IO-HMM | mit |
Set up a simple model manully | # we choose 2 hidden states in this model
SHMM = SupervisedIOHMM(num_states=2)
# we set only one output 'rt' modeled by a linear regression model
SHMM.set_models(model_emissions = [OLS()],
model_transition=CrossEntropyMNL(solver='lbfgs'),
model_initial=CrossEntropyMNL(solver='lbfgs'))
... | examples/notebooks/SupervisedIOHMM.ipynb | Mogeng/IO-HMM | mit |
See the training results | # the coefficients of the output model for each states
print(SHMM.model_emissions[0][0].coef)
print(SHMM.model_emissions[1][0].coef)
# the scale/dispersion of the output model of each states
print(np.sqrt(SHMM.model_emissions[0][0].dispersion))
print(np.sqrt(SHMM.model_emissions[1][0].dispersion))
# the transition pr... | examples/notebooks/SupervisedIOHMM.ipynb | Mogeng/IO-HMM | mit |
Save the trained model | json_dict = SHMM.to_json('../models/SupervisedIOHMM/')
json_dict
with open('../models/SupervisedIOHMM/model.json', 'w') as outfile:
json.dump(json_dict, outfile, indent=4, sort_keys=True) | examples/notebooks/SupervisedIOHMM.ipynb | Mogeng/IO-HMM | mit |
Load back the trained model | SHMM_from_json = SupervisedIOHMM.from_json(json_dict) | examples/notebooks/SupervisedIOHMM.ipynb | Mogeng/IO-HMM | mit |
See if the coefficients are any different | # the coefficients of the output model for each states
print(SHMM.model_emissions[0][0].coef)
print(SHMM.model_emissions[1][0].coef) | examples/notebooks/SupervisedIOHMM.ipynb | Mogeng/IO-HMM | mit |
Set up the model using a config file, instead of doing it manully | with open('../models/SupervisedIOHMM/config.json') as json_data:
json_dict = json.load(json_data)
SHMM_from_config = SupervisedIOHMM.from_config(json_dict) | examples/notebooks/SupervisedIOHMM.ipynb | Mogeng/IO-HMM | mit |
See if the training results are any different? | # the coefficients of the output model for each states
print(SHMM_from_config.model_emissions[0][0].coef)
print(SHMM_from_config.model_emissions[1][0].coef) | examples/notebooks/SupervisedIOHMM.ipynb | Mogeng/IO-HMM | mit |
iter()
The iter() method returns an iterator for the given object.
Syntax:
python
iter(object[, sentinel])
Where object is an object based on which the iterator needs to be constructed. The behavior of iterator is dependent on the value of sentinel, if sentinel is not provided then object should be an interator and the... | class MyDummy(object):
def __init__(self):
self.lst = [1, 2, 3, 4, 5, 6]
self.i = 0
def __call__(self):
ret = self.lst[self.i]
self.i += 1
return ret
d = MyDummy()
for a in iter(d, 3):
print(a, end=" ")
m = MyIter([1, 2, 3, 4, 5, 6])
for a in iter(m):
... | Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_03_iter.ipynb | mayankjohri/LetsExplorePython | gpl-3.0 |
lets try another example, this time lets take a string | st = "Welcome to the city of lakes"
for a in iter(st):
print(a, end=" ") | Section 2 - Advance Python/Chapter S2.01 - Functional Programming/02_03_iter.ipynb | mayankjohri/LetsExplorePython | gpl-3.0 |
A non-$2^n$ FFT (10 points)
Now that we have implemented a fast radix-2 algorithm for vectors of length $2^n$, we can write a generic algorithm which can take any length input. This algorithm will check if the length of the input is divisible by 2, if so then it will use the FFT, otherwise it will default to the slower... | def generalFFT(x):
"""radix-2 DIT FFT
x: list or array of N values to perform FFT on, can be real or imaginary
"""
ox = np.asarray(x, dtype='complex') # assure the input is an array of complex values
# INSERT: assign a value to N, the size of the FFT
N = #??? 1 point
if N==1: return ox ... | 2_Mathematical_Groundwork/fft_implementation_assignment.ipynb | griffinfoster/fundamentals_of_interferometry | gpl-2.0 |
Create the test table | with oracledb.connect(user=db_user, password=db_pass, dsn=db_connect_string) as ora_conn:
cursor = ora_conn.cursor()
# use this drop statement if you need to recreate the table
# cursor.execute("drop table data")
cursor.execute("begin dbms_random.seed(4242); end;")
cursor.execute("""
... | Oracle_Jupyter/Oracle_histograms.ipynb | LucaCanali/Miscellaneous | apache-2.0 |
Define the query to compute the histogram | table_name = "data" # table or temporary view containing the data
value_col = "random_value" # column name on which to compute the histogram
min = -20 # min: minimum value in the histogram
max = 90 # maximum value in the histogram
bins = 11 # number of histogram buckets to compute
step = (max - min) / bins
... | Oracle_Jupyter/Oracle_histograms.ipynb | LucaCanali/Miscellaneous | apache-2.0 |
Fetch the histogram data into a pandas dataframe | import pandas as pd
# query Oracle using ora_conn and put the result into a pandas Dataframe
with oracledb.connect(user=db_user, password=db_pass, dsn=db_connect_string) as ora_conn:
hist_pandasDF = pd.read_sql(query, con=ora_conn)
# Decription
#
# BUCKET: the bucket number, range from 1 to bins (included)
# ... | Oracle_Jupyter/Oracle_histograms.ipynb | LucaCanali/Miscellaneous | apache-2.0 |
Histogram plotting
The first plot is a histogram with the event counts (number of events per bin).
The second plot is a histogram of the events frequencies (number of events per bin normalized by the sum of the events). | import matplotlib.pyplot as plt
plt.style.use('seaborn-darkgrid')
plt.rcParams.update({'font.size': 20, 'figure.figsize': [14,10]})
f, ax = plt.subplots()
# histogram data
x = hist_pandasDF["VALUE"]
y = hist_pandasDF["COUNT"]
# bar plot
ax.bar(x, y, width = 3.0, color='red')
ax.set_xlabel("Bucket values")
ax.set_y... | Oracle_Jupyter/Oracle_histograms.ipynb | LucaCanali/Miscellaneous | apache-2.0 |
이전 제출물 | senten = input("What's going on? ")
senten = ".".join(senten)
senten = senten.split('.')
print(senten)
for dot, capi in morse.items():
if capi in senten:
print(dot,end=" ")
#dotted = sorted(morse.get(dot))
#print(sorted(morse.get(dot),reverse=True), end=" ")
print(morse.get(... | midterm/kookmin_midterm_조재환_2.ipynb | initialkommit/kookmin | mit |
이전에 제출한 것은 출력하면 알파벳과 모스부호가 정렬되지 않았습니다. 입력한 문장대로 모스부호를 나타내고 싶었었는데 조금 더 공부하다보니 코드를 만들 수 있어서 다시 한번 제출합니다.
수정 | senten = input("What's going on? ") # 모스부호로 나타낼 문장을 입력
senten = ".".join(senten) # 모스부호의 형태가 '알파벳' : '모스부호'로 되어있어서 입력받은 문장을
# 알파벳 단위로 끊어주기 위해 "."join으로 각 단어 사이에 .을 넣습니다.
senten = senten.split('.') # .을 기준으로 단어들을 모두 끊어 줍니다.
print(senten)
for word in senten: ... | midterm/kookmin_midterm_조재환_2.ipynb | initialkommit/kookmin | mit |
Examine a single patient | patientunitstayid = 141168
query = query_schema + """
select *
from pasthistory
where patientunitstayid = {}
order by pasthistoryoffset
""".format(patientunitstayid)
df = pd.read_sql_query(query, con)
df.head() | notebooks/pasthistory.ipynb | mit-eicu/eicu-code | mit |
We can make a few observations:
pasthistorypath is a slash delimited (/) hierarchical categorization of the past history recorded
pasthistoryvalue and pasthistoryvaluetext are often identical
pasthistoryoffset is the time of the condition, while pasthistoryenteredoffset is when it was documented, though from above it ... | dx = 'COPD'
query = query_schema + """
select
pasthistoryvalue, count(*) as n
from pasthistory
where pasthistoryvalue ilike '%{}%'
group by pasthistoryvalue
""".format(dx)
df_copd = pd.read_sql_query(query, con)
df_copd
dx = 'COPD'
query = query_schema + """
select
patientunitstayid, count(*) as n
from pasthist... | notebooks/pasthistory.ipynb | mit-eicu/eicu-code | mit |
Hospitals with data available | query = query_schema + """
with t as
(
select distinct patientunitstayid
from pasthistory
)
select
pt.hospitalid
, count(distinct pt.patientunitstayid) as number_of_patients
, count(distinct t.patientunitstayid) as number_of_patients_with_tbl
from patient pt
left join t
on pt.patientunitstayid = t.patientunits... | notebooks/pasthistory.ipynb | mit-eicu/eicu-code | mit |
The output then needs to be flattened so it can be used in fully-connected (aka. dense) layers. | net = tf.contrib.layers.flatten(net)
# This should eventually be replaced by:
# net = tf.layers.flatten(net) | 13B_Visual_Analysis_MNIST.ipynb | newworldnewlife/TensorFlow-Tutorials | mit |
Loss-Function to be Optimized
To make the model better at classifying the input images, we must somehow change the variables of the neural network.
The cross-entropy is a performance measure used in classification. The cross-entropy is a continuous function that is always positive and if the predicted output of the mod... | cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=logits) | 13B_Visual_Analysis_MNIST.ipynb | newworldnewlife/TensorFlow-Tutorials | mit |
With these parameters, the model creates wide AP waveforms that are more reminiscent of muscle cells than neurons.
We now set up a simple optimisation problem with the model. | # First add some noise
sigma = 0.5
noisy = values + np.random.normal(0, sigma, values.shape)
# Plot the results
plt.figure()
plt.xlabel('Time')
plt.ylabel('Noisy values')
plt.plot(times, noisy)
plt.show() | examples/toy/model-fitzhugh-nagumo.ipynb | martinjrobins/hobo | bsd-3-clause |
Next, we set up a problem. Because this model has multiple outputs (2), we use a MultiOutputProblem. | problem = pints.MultiOutputProblem(model, times, noisy)
score = pints.SumOfSquaresError(problem) | examples/toy/model-fitzhugh-nagumo.ipynb | martinjrobins/hobo | bsd-3-clause |
Finally, we choose a wide set of boundaries and run! | # Select boundaries
boundaries = pints.RectangularBoundaries([0., 0., 0.], [10., 10., 10.])
# Select a starting point
x0 = [1, 1, 1]
# Perform an optimization
found_parameters, found_value = pints.optimise(score, x0, boundaries=boundaries)
print('Score at true solution:')
print(score(parameters))
print('Found solut... | examples/toy/model-fitzhugh-nagumo.ipynb | martinjrobins/hobo | bsd-3-clause |
This shows the parameters are not retrieved entirely correctly, but the traces still strongly overlap.
Sampling with Monomial-gamma HMC
The Fitzhugh-Nagumo model has sensitivities calculated by the forward sensitivities approach, so we can use samplers that use gradients (although they will be slower per iteration; alt... | problem = pints.MultiOutputProblem(model, times, noisy)
# Create a log-likelihood function (adds an extra parameter!)
log_likelihood = pints.GaussianLogLikelihood(problem)
# Create a uniform prior over both the parameters and the new noise variable
log_prior = pints.UniformLogPrior(
[0, 0, 0, 0, 0],
[10, 10, ... | examples/toy/model-fitzhugh-nagumo.ipynb | martinjrobins/hobo | bsd-3-clause |
Print results. | results = pints.MCMCSummary(
chains=chains,
time=mcmc.time(),
parameter_names=['a', 'b', 'c', 'sigma_V', 'sigma_R'],
)
print(results) | examples/toy/model-fitzhugh-nagumo.ipynb | martinjrobins/hobo | bsd-3-clause |
Plot the few posterior predictive simulations versus data. | import pints.plot
pints.plot.series(np.vstack(chains), problem)
plt.show() | examples/toy/model-fitzhugh-nagumo.ipynb | martinjrobins/hobo | bsd-3-clause |
Nous allons initialiser les differentes valeurs : | E=1.3 #en MPa
h=7.5 #en mm
b=20. #en mm
Lx=55. #en mm
Lyh=60. #en mm
Lyb=45 #en mm
I=b*(h**3)/12 #en mm^4
S=b*h #en mm^2
eps=10**(-3)
g=9.81 | Exercice 2.ipynb | qgoisnard/Exercice-update | mit |
Nous allons maintenant créer les noeuds et les éléments de la structure : | nodes= np.array([[0.,0.],[0.,Lyb],[0.,Lyh+Lyb],[Lx/2,Lyh+Lyb],[Lx,Lyh+Lyb],[Lx,Lyb],[Lx,0.]])
elements=np.array([[0,1],[1,5],[1,2],[2,3],[3,4],[4,5],[5,6]])
frame=LinearFrame(nodes,elements)
frame.plot_with_label()
ne = frame.nelements
ndof = frame.ndof
EI = np.ones(ne)*E*I
ES = np.ones(ne)*E*S
f_x = 0*np.ones(7)
f_y... | Exercice 2.ipynb | qgoisnard/Exercice-update | mit |
La masse accrochée serait d'environ 320g
Exercice 3
Dans cette exercice, on doit créer des fonctions à l'intérieur de notre classe frame afin de récupérer l'effort normal(N), l'effort tangentielle (T) et le moment sur z (M). | def find_N(self,element):
"""
Returns the normal force of an element.
"""
F = self.assemble_F()
N = F[3*element]
return N
def find_T(self,element):
"""
Returns the tangential force of an element.
"""
F = self.assemble_F()
T = F... | Exercice 2.ipynb | qgoisnard/Exercice-update | mit |
Next, let's specify the measurements. Notice that we only measure the positions of the particle. | # Measurements
measurements = []
mean = torch.zeros(2)
# no correlations
cov = 1e-5 * torch.eye(2)
with torch.no_grad():
# sample independent measurement noise
dzs = pyro.sample('dzs', dist.MultivariateNormal(mean, cov).expand((num_frames,)))
# compute measurement means
zs = xs_truth[:, :2] + dzs | tutorial/source/ekf.ipynb | uber/pyro | apache-2.0 |
We'll use a Delta autoguide to learn MAP estimates of the position and measurement covariances. The EKFDistribution computes the joint log density of all of the EKF states given a tensor of sequential measurements. | def model(data):
# a HalfNormal can be used here as well
R = pyro.sample('pv_cov', dist.HalfCauchy(2e-6)) * torch.eye(4)
Q = pyro.sample('measurement_cov', dist.HalfCauchy(1e-6)) * torch.eye(2)
# observe the measurements
pyro.sample('track_{}'.format(i), EKFDistribution(xs_truth[0], R, ncv,
... | tutorial/source/ekf.ipynb | uber/pyro | apache-2.0 |
Initialize the tool (e.g., ddRAD)
You can generate single or paired-end data, and you will likely want to restrict the size of selected fragments to be within an expected size selection window, as is typically done in empirical data sets. Here I select all fragments occuring between two restriction enzymes where the in... | digest = ipa.digest_genome(
fasta=genome,
name="amaranthus-digest",
workdir="digested_genomes",
re1="CTGCAG",
re2="AATTC",
ncopies=10,
readlen=150,
min_size=300,
max_size=500,
nscaffolds=12,
)
digest.run() | testdocs/analysis/cookbook-digest_genomes.ipynb | dereneaton/ipyrad | gpl-3.0 |
Check results | ! ls -l digested_genomes/ | testdocs/analysis/cookbook-digest_genomes.ipynb | dereneaton/ipyrad | gpl-3.0 |
Example 2 (original RAD data)
The original RAD method uses sonication rather than a second restriction digestion to cut all of the fragments down to an appropriate size for sequencing. Thus you only need to provide a single cut site and a selection window. | digest = ipa.digest_genome(
fasta=genome,
name="amaranthus-digest-RAD",
workdir="digested_genomes",
re1="CTGCAG",
re2=None,
paired=False,
ncopies=10,
readlen=100,
min_size=300,
max_size=500,
nscaffolds=12,
)
digest.run() | testdocs/analysis/cookbook-digest_genomes.ipynb | dereneaton/ipyrad | gpl-3.0 |
Data Structures
There are three fundamental data structures supported by Pandas:<br>
* Series: a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). For those coming from an R background, Series is much like a Vector.
* DataFrame: a 2-dimensi... | import pandas as pd
# From Scalar Values
series_1 = pd.Series([1,2,3,4,5])
series_1 | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Notice the 0,1,2,3... on the left side? That's called the Index. It starts from 0, but you can rename it. | series_1 = pd.Series([1,2,3,4,5], index = ['Mon','Tue','Wed','Thu','Fri'])
series_1
series_2 = pd.Series(1.0, index = ['a','b','c','d','e'])
series_2
import pandas as pd
import numpy as np
# From an array
# Just copy this for now, we'll cover the 'seed' in DataFrames
np.random.seed(42)
series_3 = pd.Series(np.ran... | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
We can subset and get values from the series. | series_4['a'] == series_4[0]
series_4[series_4>3]
series_4[series_4%2==0]
series_5 = pd.Series([1,2,3,4,5], index = ['HP', 'GS', 'IBM', 'AA', 'FB'])
series_5
series_5['IBM']
tech_pf1 = series_5[['HP', 'IBM', 'FB']]
tech_pf1
# From a Dictionary
dict_01 = {'Gavin' : 50, 'Russ' : 100, 'Erlich' : 150}
series_6 = pd.S... | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Notice the NaN, which stands for Not a Number. We will be dealing with it extensively when working with DataFrames. It is an indicator for missing or corrupted data. Here's how we test for it. | pd.isnull(series_7) | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
And here's a nice discussion on the topic from our friends at StackOverflow. | # Pandas is very smart, and aligns the series for mathematical operations
series_6 + series_7
# Renaming an Index
series_7.index.name = "Names"
series_7
# Naming a Series
series_7.name = "SV"
series_7 | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Mini-Project | goals = pd.Series([20,19,21,24,1], index = ["Messi", "Neymar", "Zlatan", "Ronaldo", "N’Gog"])
goals
# Who scored less than 20 goals?
goals[goals<20]
# What is the average number of goals scored?
goals.mean()
# What is the median number of goals scored?
goals.median()
# What is the range of goals scored? (Range = Ma... | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Read more about these here.
DataFrames
DataFrames is in many respects, the real Pandas. Usually, if you're using Pandas, it will be to use DataFrames.<br>
We will begin with creating DataFrames, and the usual indexing and selection mechanisms. In reality, you will probably never have to 'create' a DataFrame, but pract... | import pandas as pd
import numpy as np
# Let's start with a standard array
arr1 = np.array([[40,40,75,95],[80,85,120,130],
[155,160,165,170],[200,245,250,260]])
print(arr1.shape)
print(arr1.size)
print(arr1)
# It is quite common to assign a dataframe the name 'df', although you can
# use a relevant n... | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Indexing and Selection
Selecting Columns | df = pd.DataFrame(arr1, index = "Peter,Clarke,Bruce,Tony".split(","),
columns = "Jan,Feb,Mar,Apr".split(","))
df
# Selecting columns
df[['Jan']]
df[['Jan','Feb']]
df[['Mar','Jan']] | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
It's interesting to note that the offical Pandas documentation refers to DataFrames as:
Can be thought of as a dict-like container for Series objects.
You can access it as a Series as below: | df['Jan']
print('Series:', type(df['Jan']))
print('DataFrame:',type(df[['Jan']])) | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Using loc and iloc | df = pd.DataFrame(arr1, index = "Peter,Clarke,Bruce,Tony".split(","),
columns = "Jan,Feb,Mar,Apr".split(","))
df
# For selecting by Label
df.loc[['Tony']]
df.loc[['Peter','Bruce']]
df.loc[['Peter','Bruce'],['Jan','Feb']]
# All of Peter's data
df.loc[["Peter"]][:]
df.loc["Peter"][:]
df
# Intege... | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
There's another function named ix. I have rarely used it, and both loc and iloc take care of all my selection needs. You can read about it here.
Also, check out the similarity of outputs below: | df.ix[0:3]
df.iloc[0:3] | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Conditional Selection
While exploring data sets, one often has to use conditional selection. Or this could be true for creating subsets to work. | df
df[df%2 == 0]
df%2 == 0
df < 100
df[df<100]
df
df[df['Jan']>100][['Apr']]
df[df['Jan']<100][['Feb','Apr']]
# Using multiple conditions
df[(df['Jan'] >= 80) & (df['Mar']>100)] | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Did you notice that we used & instead of and? When using Pandas, we have to use the symbol, not the word. Here's a StackOverflow discussion on this.
Creating New Columns | df = pd.DataFrame(arr1, index = "Peter,Clarke,Bruce,Tony".split(","), columns = "Jan,Feb,Mar,Apr".split(","))
df
df["Dec"] = df["Jan"] + df["Mar"]
df | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Removing Columns
While fundamentally adding and removing columns ought to be similar operations, there are a few differences. Let's see if you can figure it out. | df
df.drop('Dec', axis = 1) | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
First, we had to mention the axis. 0 is for rows, 1 is for columns. | df | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Why is 'Dec' still there? Here lies the difference - while removing columns, we have to specify that the operation should be inplace. Read about it in the official documentation. | df.drop('Dec', axis = 1, inplace = True)
df | 12.Introduction_to_Pandas.ipynb | prasants/pyds | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.