markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We have sets of foregrounds and backgrounds along with the variables
$\alpha$: parameters in the concentration function (which is a function of $z_i,M_i$)
$\theta$: prior distribution of halo masses
$z_i$: foreground galaxy redshift
$x_i$: foreground galaxy angular coordinates
$z_j$: background galaxy redshift
$x_j$:... | from pandas import read_table
from pangloss import GUO_FILE
m_h = 'M_Subhalo[M_sol/h]'
m_s = 'M_Stellar[M_sol/h]'
guo_data = read_table(GUO_FILE)
nonzero_guo_data= guo_data[guo_data[m_h] > 0]
import matplotlib.pyplot as plt
stellar_mass_threshold = 5.883920e+10
plt.scatter(nonzero_guo_data[m_h], nonzero_guo_data[m_... | GroupMeeting_11_16.ipynb | davidthomas5412/PanglossNotebooks | mit |
Results | from pandas import read_csv
res = read_csv('data3.csv')
tru = read_csv('true3.csv')
start = min([res[res[c] > 0][c].min() for c in res.columns[1:-1]])
stop = res.max().max()
base = 10
start = log(start, base)
end = log(stop, base)
res_logspace = np.logspace(start, end, num=10, base=base)
plt.rcParams['figure.figsiz... | GroupMeeting_11_16.ipynb | davidthomas5412/PanglossNotebooks | mit |
3. Enter DV360 Report To Storage Recipe Parameters
Specify either report name or report id to move a report.
The most recent valid file will be moved to the bucket.
Modify the values below for your use case, can be done multiple times, then click play. | FIELDS = {
'auth_read':'user', # Credentials used for reading data.
'dbm_report_id':'', # DV360 report ID given in UI, not needed if name used.
'auth_write':'service', # Credentials used for writing data.
'dbm_report_name':'', # Name of report, not needed if ID used.
'dbm_bucket':'', # Google cloud bucke... | colabs/dbm_to_storage.ipynb | google/starthinker | apache-2.0 |
4. Execute DV360 Report To Storage
This does NOT need to be modified unless you are changing the recipe, click play. | from starthinker.util.configuration import execute
from starthinker.util.recipe import json_set_fields
TASKS = [
{
'dbm':{
'auth':{'field':{'name':'auth_read','kind':'authentication','order':1,'default':'user','description':'Credentials used for reading data.'}},
'report':{
'report_id':{'fiel... | colabs/dbm_to_storage.ipynb | google/starthinker | apache-2.0 |
Characterizing sample data | variant_annotations = [{
'va':va,
'n_te': len(list(va.transcriptEffects)),
'n_ef': len(list(ef for te in va.transcriptEffects for ef in te.effects)),
'sos': ";".join(sorted(set("{ef.id}:{ef.term}".format(ef=ef)
for te in va.transcriptEffects
... | nb/Exploring SO terms.ipynb | reece/ga4gh-examples | apache-2.0 |
The following is an inline graphic image. See instructions below it for reproducing it.
To regenerate this data:
Eval the next cell
Select Bar Chart from Table menu
Drag-drop "sos" to left column under Count pulldown
Drag-drop n_te, then n_ef to row to right of Count pulldown | pivot_ui(variant_annotations_df) | nb/Exploring SO terms.ipynb | reece/ga4gh-examples | apache-2.0 |
The searches
Using the data above, we can search for single and multiple terms and compare to expectations.
We'll be using this function:
Signature: gc.searchVariantAnnotations(variantAnnotationSetId, referenceName=None, referenceId=None,
start=None, end=None, featureIds=[], effe... | def _mk_effect_filter(so_ids=[]):
"""return list of so_id effect filters for the given list of so_ids
>>> print(_mk_effect_filter(so_ids="SO:1 SO:2 SO:3".split()))
['{"id":"SO:1"}', '{"id":"SO:2"}', '{"id":"SO:3"}']
"""
return [{"id": so_id} for so_id in so_ids]
def _fetch_variant_annotations(gc, ... | nb/Exploring SO terms.ipynb | reece/ga4gh-examples | apache-2.0 |
However, this ceases to be true when two sinusoids of equal frequency and phase are multiplied together. In this case, instead of averaging out to zero, the product of the two waves have a nonzero mean value. | df['sin_mixed'] = np.multiply(df.sine, df.sine)
df['mean_mixed'] = np.mean(df.sin_mixed)
df[['sin_mixed','mean_mixed']][:1000].plot() | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
This DC voltage produced by the product of the two waves is very sensitive to changes in frequency. The plots below show that a 101Hz signal has a mean value of zero when multiplied by a 100Hz signal. | df['sin_mixed_101'] = np.multiply(df.sine, sine_wave(101))
df['mean_mixed_101'] = np.mean(df.sin_mixed_101)
df[['sin_mixed_101','mean_mixed_101']].plot() | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
This is really useful in situations where you have a signal of a known frequency. With the proper equipment, you can "lock in" to your known-frequency signal, and track changes to the amplitude and phase of that signal - even in the presence of overwhelming noise.
You can show this pretty easily by just scaling down o... | noise_fl = np.array([(2 * np.random.random() - 1) for a in range(10000)])
df['sine_noisy'] = np.add(noise_fl, 0.1*df['sine'])
df['sin_noisy_mixed'] = np.multiply(df.sine_noisy, df.sine)
df['mean_noisy_mixed'] = df['sin_noisy_mixed'].mean()
fig, axes = plt.subplots(nrows=1, ncols=2)
fig.set_size_inches(12,4)
... | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
It doesn't look like much at the prior altitude, but it's definitely the signal we're looking for. That's because the lock-in output scales with the amplitude of both the input signal and the reference waveform:
$$U_{out}=\frac{1}{2}V_{sig}V_{ref}cos(\theta)$$
As a result, the lock-in amp has a small (but meaningful) a... | df['mean_noisy_mixed'].plot() | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
Great! We can pull really weak signals out of seemingly endless noise. So, why haven't we used this technology to revolutionize all communications with infite signal-to-noise ratio?
Like all real systems, there's a tradeoff, and for a lock-in amplifier, that tradeoff is time. Lock-in amps rely on a persistent periodic... | def lowpass(x, alpha=0.001):
data = [x[0]]
for a in x[1:]:
data.append(data[-1] + (alpha*(a-data[-1])))
return np.array(data)
df['sin_mixed_lp'] = lowpass(df.sin_mixed)
df['sin_mixed_lp'].plot() | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
...but it starts to break down when you filter the noisy signals, which can contain large fluctuations that aren't necessarily real: | df['sin_noisy_mixed_lp'] = lowpass(df.sin_noisy_mixed)
df['sin_noisy_mixed_lp'].plot() | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
We can clean get rid of some of that statistical noise junk by rerunning the filter, of course, but that takes time, and also robs the lock-in of a bit of responsiveness. | df['sin_noisy_mixed_lp2'] = lowpass(df.sin_noisy_mixed_lp)
df['sin_noisy_mixed_lp2'].plot() | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
On top of all this, lock-in amps are highly sensitive to phase differences between reference and signal tones. Take a look at the plots below, where our noisy signal is mixed with waves 45 and 90 degrees offset from it. | df['sin_phase45_mixed'] = np.multiply(df.sine_noisy, sine_wave(100, phase=45))
df['sin_phase90_mixed'] = np.multiply(df.sine_noisy, sine_wave(100, phase=90))
df['sin_phase45_mixed_lp'] = lowpass(df['sin_phase45_mixed'])
df['sin_phase90_mixed_lp'] = lowpass(df['sin_phase90_mixed'])
fig, axes = plt.subplots(nrows=1,... | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
These plots illustrate that there's a component of phase sensitivity. As the phase of signal moves farther and farther out of phase with the reference, the lock-in output starts to trend downwards, closer to zero. You can see, too, why lock-ins require time to settle out to a final value - the left plot shows how signa... | def cosine_wave(freq, phase=0, Fs=10000):
ph_rad = (phase/360.0)*(2.0*np.pi)
return np.array([np.cos(((2 * np.pi * freq * a) / Fs) + ph_rad) for a in range(Fs)])
df['cos_noisy_mixed'] = np.multiply(df.sine_noisy, cosine_wave(100))
df['cos_noisy_mixed_lp'] = lowpass(df['cos_noisy_mixed'])
df['noisy_quad_mag... | assets/lockin_amp_simulation.ipynb | Cushychicken/cushychicken.github.io | mit |
We can use Scikit-Learn's LinearRegression estimator to fit this data and construct the best-fit line: | from sklearn.linear_model import LinearRegression
model = LinearRegression(fit_intercept=True)
model.fit(x[:, np.newaxis], y)
xfit = np.linspace(0, 10, 1000)
yfit = model.predict(xfit[:, np.newaxis])
plt.scatter(x, y)
plt.plot(xfit, yfit); | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
We see that the results are very close to the inputs, as we might hope.
The LinearRegression estimator is much more capable than this, however—in addition to simple straight-line fits, it can also handle multidimensional linear models of the form
$$
y = a_0 + a_1 x_1 + a_2 x_2 + \cdots
$$
where there are multiple $x$ v... | rng = np.random.RandomState(1)
X = 10 * rng.rand(100, 3)
y = 0.5 + np.dot(X, [1.5, -2., 1.])
model.fit(X, y)
print(model.intercept_)
print(model.coef_) | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
Here the $y$ data is constructed from three random $x$ values, and the linear regression recovers the coefficients used to construct the data.
In this way, we can use the single LinearRegression estimator to fit lines, planes, or hyperplanes to our data.
It still appears that this approach would be limited to strictly ... | from sklearn.preprocessing import PolynomialFeatures
x = np.array([2, 3, 4])
poly = PolynomialFeatures(3, include_bias=False)
poly.fit_transform(x[:, None]) | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
We see here that the transformer has converted our one-dimensional array into a three-dimensional array by taking the exponent of each value.
This new, higher-dimensional data representation can then be plugged into a linear regression.
As we saw in Feature Engineering, the cleanest way to accomplish this is to use a p... | from sklearn.pipeline import make_pipeline
poly_model = make_pipeline(PolynomialFeatures(7),
LinearRegression()) | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
With this transform in place, we can use the linear model to fit much more complicated relationships between $x$ and $y$.
For example, here is a sine wave with noise: | rng = np.random.RandomState(1)
x = 10 * rng.rand(50)
y = np.sin(x) + 0.1 * rng.randn(50)
poly_model.fit(x[:, np.newaxis], y)
yfit = poly_model.predict(xfit[:, np.newaxis])
plt.scatter(x, y)
plt.plot(xfit, yfit); | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
Our linear model, through the use of 7th-order polynomial basis functions, can provide an excellent fit to this non-linear data!
Gaussian basis functions
Of course, other basis functions are possible.
For example, one useful pattern is to fit a model that is not a sum of polynomial bases, but a sum of Gaussian bases.
T... | from sklearn.base import BaseEstimator, TransformerMixin
class GaussianFeatures(BaseEstimator, TransformerMixin):
"""Uniformly spaced Gaussian features for one-dimensional input"""
def __init__(self, N, width_factor=2.0):
self.N = N
self.width_factor = width_factor
@staticmethod
... | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
We put this example here just to make clear that there is nothing magic about polynomial basis functions: if you have some sort of intuition into the generating process of your data that makes you think one basis or another might be appropriate, you can use them as well.
Regularization
The introduction of basis functio... | model = make_pipeline(GaussianFeatures(30),
LinearRegression())
model.fit(x[:, np.newaxis], y)
plt.scatter(x, y)
plt.plot(xfit, model.predict(xfit[:, np.newaxis]))
plt.xlim(0, 10)
plt.ylim(-1.5, 1.5); | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
With the data projected to the 30-dimensional basis, the model has far too much flexibility and goes to extreme values between locations where it is constrained by data.
We can see the reason for this if we plot the coefficients of the Gaussian bases with respect to their locations: | def basis_plot(model, title=None):
fig, ax = plt.subplots(2, sharex=True)
model.fit(x[:, np.newaxis], y)
ax[0].scatter(x, y)
ax[0].plot(xfit, model.predict(xfit[:, np.newaxis]))
ax[0].set(xlabel='x', ylabel='y', ylim=(-1.5, 1.5))
if title:
ax[0].set_title(title)
ax[1].plot(mode... | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
The lower panel of this figure shows the amplitude of the basis function at each location.
This is typical over-fitting behavior when basis functions overlap: the coefficients of adjacent basis functions blow up and cancel each other out.
We know that such behavior is problematic, and it would be nice if we could limit... | from sklearn.linear_model import Ridge
model = make_pipeline(GaussianFeatures(30), Ridge(alpha=0.1))
basis_plot(model, title='Ridge Regression') | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
The $\alpha$ parameter is essentially a knob controlling the complexity of the resulting model.
In the limit $\alpha \to 0$, we recover the standard linear regression result; in the limit $\alpha \to \infty$, all model responses will be suppressed.
One advantage of ridge regression in particular is that it can be compu... | from sklearn.linear_model import Lasso
model = make_pipeline(GaussianFeatures(30), Lasso(alpha=0.001))
basis_plot(model, title='Lasso Regression') | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
With the lasso regression penalty, the majority of the coefficients are exactly zero, with the functional behavior being modeled by a small subset of the available basis functions.
As with ridge regularization, the $\alpha$ parameter tunes the strength of the penalty, and should be determined via, for example, cross-va... | !sudo apt-get update
!apt-get -y install curl
!curl -o FremontBridge.csv https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD
# !wget -o FremontBridge.csv "https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD"
import pandas as pd
counts = pd.read_csv('FremontBridge.csv', ind... | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
We also might suspect that the hours of daylight would affect how many people ride; let's use the standard astronomical calculation to add this information: | from datetime import datetime
def hours_of_daylight(date, axis=23.44, latitude=47.61):
"""Compute the hours of daylight for the given date"""
days = (date - datetime(2000, 12, 21)).days
m = (1. - np.tan(np.radians(latitude))
* np.tan(np.radians(axis) * np.cos(days * 2 * np.pi / 365.25)))
retur... | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
We can also add the average temperature and total precipitation to the data.
In addition to the inches of precipitation, let's add a flag that indicates whether a day is dry (has zero precipitation): | # temperatures are in 1/10 deg C; convert to C
weather['TMIN'] /= 10
weather['TMAX'] /= 10
weather['Temp (C)'] = 0.5 * (weather['TMIN'] + weather['TMAX'])
# precip is in 1/10 mm; convert to inches
weather['PRCP'] /= 254
weather['dry day'] = (weather['PRCP'] == 0).astype(int)
daily = daily.join(weather[['PRCP', 'Temp ... | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
It is evident that we have missed some key features, especially during the summer time.
Either our features are not complete (i.e., people decide whether to ride to work based on more than just these) or there are some nonlinear relationships that we have failed to take into account (e.g., perhaps people ride less at b... | params = pd.Series(model.coef_, index=X.columns)
params | present/mcc2/PythonDataScienceHandbook/05.06-Linear-Regression.ipynb | csaladenes/csaladenes.github.io | mit |
Partial Differential Equations
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r1/tutorials/non-ml/pdes.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
<... | #Import libraries for simulation
import tensorflow.compat.v1 as tf
import numpy as np
#Imports for visualization
import PIL.Image
from io import BytesIO
from IPython.display import clear_output, Image, display
| site/en/r1/tutorials/non-ml/pdes.ipynb | tensorflow/docs | apache-2.0 |
A function for displaying the state of the pond's surface as an image. | def DisplayArray(a, fmt='jpeg', rng=[0,1]):
"""Display an array as a picture."""
a = (a - rng[0])/float(rng[1] - rng[0])*255
a = np.uint8(np.clip(a, 0, 255))
f = BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
clear_output(wait = True)
display(Image(data=f.getvalue())) | site/en/r1/tutorials/non-ml/pdes.ipynb | tensorflow/docs | apache-2.0 |
Here you start an interactive TensorFlow session for convenience in playing around. A regular session would work as well if you were doing this in an executable .py file. | sess = tf.InteractiveSession() | site/en/r1/tutorials/non-ml/pdes.ipynb | tensorflow/docs | apache-2.0 |
Computational convenience functions | def make_kernel(a):
"""Transform a 2D array into a convolution kernel"""
a = np.asarray(a)
a = a.reshape(list(a.shape) + [1,1])
return tf.constant(a, dtype=1)
def simple_conv(x, k):
"""A simplified 2D convolution operation"""
x = tf.expand_dims(tf.expand_dims(x, 0), -1)
y = tf.nn.depthwise_conv2d(x, k, [... | site/en/r1/tutorials/non-ml/pdes.ipynb | tensorflow/docs | apache-2.0 |
Define the PDE
Our pond is a perfect 500 x 500 square, as is the case for most ponds found in nature. | N = 500 | site/en/r1/tutorials/non-ml/pdes.ipynb | tensorflow/docs | apache-2.0 |
Here you create a pond and hit it with some rain drops. | # Initial Conditions -- some rain drops hit a pond
# Set everything to zero
u_init = np.zeros([N, N], dtype=np.float32)
ut_init = np.zeros([N, N], dtype=np.float32)
# Some rain drops hit a pond at random points
for n in range(40):
a,b = np.random.randint(0, N, 2)
u_init[a,b] = np.random.uniform()
DisplayArray(u_... | site/en/r1/tutorials/non-ml/pdes.ipynb | tensorflow/docs | apache-2.0 |
Now you specify the details of the differential equation. | # Parameters:
# eps -- time resolution
# damping -- wave damping
eps = tf.placeholder(tf.float32, shape=())
damping = tf.placeholder(tf.float32, shape=())
# Create variables for simulation state
U = tf.Variable(u_init)
Ut = tf.Variable(ut_init)
# Discretized PDE update rules
U_ = U + eps * Ut
Ut_ = Ut + eps * (lapla... | site/en/r1/tutorials/non-ml/pdes.ipynb | tensorflow/docs | apache-2.0 |
Run the simulation
This is where it gets fun -- running time forward with a simple for loop. | # Initialize state to initial conditions
tf.global_variables_initializer().run()
# Run 1000 steps of PDE
for i in range(1000):
# Step simulation
step.run({eps: 0.03, damping: 0.04})
# Show final image
DisplayArray(U.eval(), rng=[-0.1, 0.1]) | site/en/r1/tutorials/non-ml/pdes.ipynb | tensorflow/docs | apache-2.0 |
Wait so.. the rows of a matrix $A$ are orthogonal iff $AA^T$ is diagonal? Hmm. Math.StackEx Link | np.isclose(np.eye(len(U)), U @ U.T)
np.isclose(np.eye(len(V)), V.T @ V) | FACLA/SVD-NMF-review.ipynb | WNoxchi/Kaukasos | mit |
Wait but that also gives True for $VV^T$. Hmmm.
2. Truncated SVD
Okay, so SVD is an exact decomposition of a matrix and allows us to pull out distinct topics from data (due to their orthonormality (orthogonality?)).
But doing so for a large data corpus is ... bad. Especially if most of the data's meaning / information ... | from sklearn import decomposition
# ofc this is just dummy data to test it works
datavectors = np.random.randint(-1000,1000,size=(10,50))
U,S,V = decomposition.randomized_svd(datavectors, n_components=5)
U.shape, S.shape, V.shape | FACLA/SVD-NMF-review.ipynb | WNoxchi/Kaukasos | mit |
The idea of T-SVD is that we want to compute an approximation to the range of $A$. The range of $A$ is the space covered by the column basis.
ie: Range(A) = {y: Ax = y}
that is: all $y$ you can achieve by multiplying $x$ with $A$.
Depending on your space, the bases are vectors that you can take linear combinations of t... | # workflow w NMF is something like this
V = np.random.randint(0, 20, size=(10,10))
m,n = V.shape
d = 5 # num_topics
clsf = decomposition.NMF(n_components=d, random_state=1)
W1 = clsf.fit_transform(V)
H1 = clsf.components_ | FACLA/SVD-NMF-review.ipynb | WNoxchi/Kaukasos | mit |
We can see the essential features of Python used:
Python does not declare the type of the variables;
There is nothing special about lists or arrays as variables when passed as arguments;
To define functions the keyword is def;
To define the start of a block (the body of a function, or a loop, or a conditional) a colo... | unsorted = [2, 4, 6, 0, 1, 3, 5]
print(sorted(unsorted)) | examples.ipynb | IanHawke/msc-or-week0 | mit |
This gets rid of the need for a temporary variable.
Exercise
Here is a pseudo-code for the counting sort algorithm:
Start with an unsorted list list of length n.
Find the minimum value min_value and maximum value max_value of the list.
Create a list counts that will count the number of entries in the list with value b... | def countingsort(unsorted):
"""
Sorts an array using counting sort algorithm
Paramters
---------
unsorted : list
The unsorted list
Returns
sorted : list
The sorted list (in place)
"""
# Allocate the counts array
min_value = min(unsorted)
ma... | examples.ipynb | IanHawke/msc-or-week0 | mit |
Simplex Method
For the linear programming problem
$$
\begin{aligned}
\max x_1 + x_2 &= z \
2 x_1 + x_2 & \le 4 \
x_1 + 2 x_2 & \le 3
\end{aligned}
$$
where $x_1, x_2 \ge 0$, one standard approach is the simplex method.
Introducing slack variables $s_1, s_2 \ge 0$ the standard tableau form becomes
$$
\begin{pmatri... | import numpy
tableau = numpy.array([ [1, -1, -1, 0, 0, 0],
[0, 2, 1, 1, 0, 4],
[0, 1, 2, 0, 1, 3] ], dtype=numpy.float64)
print(tableau) | examples.ipynb | IanHawke/msc-or-week0 | mit |
Lets now view the first few lines of the data table. The rows of the data table are each of the Nobel prizes awarded and the columns are the information about who won the prize.
We have put the data into a pandas DataFrame we can now use all the functions associated with DataFrames. A useful function is .head(), thi... | data.head(5) # Displaying some of the data so you can see what form it takes in the DataFrame | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Plotting a histogram
Lets learn how to plot histograms. We will plot the number of prizes awarded per year. Nobel prizes can be awarded for up to three people per category. As each winner is recorded as an individual entry the histogram will tell us if there has been a trend of increasing or decreasing multiple prize w... | # print the earliest year in the data
print(data.Year.min())
# print the latest year in the data
print(data.Year.max()) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
The data set also contains entries for economics. Economics was not one of the original Nobel prizes and has only been given out since 1969. If we want to do a proper comparison we will need to filter this data out. We can do this with a pandas query.
We can then check there are no economics prizes left by finding the ... | # filter out the Economics prizes from the data
data_without_economics = data.query("Category != 'economics'")
print('Number of economics prizes in "data_without_economics":')
print(len(data_without_economics.query("Category == 'economics'"))) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
We can now plot the histogram over a sensible range using the hist function from matplotlib. You will use this throughout the main analysis. | # plot the histogram of number of winners against year
H_WinnersPerYear = data_without_economics.Year.hist(bins=11, range=[1900, 2010])
xlabel('Year')
ylabel('Number of Winners') | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
From the histogram we can see that there has been a recent trend of more multiple prize winners in the same year. However there is a drop in the range 1940 - 1950, this was due to prizes being awarded intermittently during World War II. To isolate this gap we can change the bin size (by changing the number of bins vari... | def plot_hist(bins):
changingBins = data_without_economics.Year.hist(bins=bins, range=[1900,2010])
xlabel('Year')
ylabel('Number of People Given Prizes')
BinSize = round(60/bins, 2)
print(BinSize)
interact(plot_hist, bins=[2, 50, 1]) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
As you can see by varying the slider - changing the bin size really does change how the data looks! There is discussion on what is the appropiate bin size to use in the main notebook.
Preselections
We now want to select our data. This is the same process as with filtering out economics prizes before but we'll go into m... | modernPhysics = "(Category == 'physics' && Year > 2005)" # Integer values don't go inside quotes
physicsOnly = "(Category == 'physics')"
# apply the physicsOnly query
physicsOnlyDataFrame = data.query(physicsOnly) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Lets check the new DataFrames to see if this has worked! | physicsOnlyDataFrame.head(5) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Brilliant! You will find this technique useful to select kaons in the main analysis. Lets now plot the number of winners per year just for physics. | H_PhysicsWinnersPerYear = physicsOnlyDataFrame.Year.hist(bins=15, range=[1920,2010])
xlabel('Year') #Plot an x label
ylabel('Number of Winners in Physics') #Plot a y label | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
We have now successfully plotted the histogram of just the physics prizes after applying our pre-selection.
Calculations, Scatter Plots and 2D Histogram
Adding New Data to a Data Frame
You will find this section useful for when it comes to creating a Dalitz plot in the particle physics analysis.
We want to see what age... | # Create new variable in the dataframe
physicsOnlyDataFrame['AgeAwarded'] = physicsOnlyDataFrame.Year - physicsOnlyDataFrame.BirthYear
physicsOnlyDataFrame.head(5) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Lets make a plot of the age of the winners at the time they were awarded the prize | # plot a histogram of the laureates ages
H_AgeAwarded = physicsOnlyDataFrame.AgeAwarded.hist(bins=15) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Making Calculations
Lets calculate a measure of the spread in ages of the laureates. We will calculate the standard deviation of the distribution. | # count number of entries
NumEntries = len(physicsOnlyDataFrame)
# calculate square of ages
physicsOnlyDataFrame['AgeAwardedSquared'] = physicsOnlyDataFrame.AgeAwarded**2
# calculate sum of square of ages, and sum of ages
AgeSqSum = physicsOnlyDataFrame['AgeAwardedSquared'].sum()
AgeSum = physicsOnlyDataFrame['AgeAward... | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
There is actually a function that would calculate the rms for you, but we wanted to teach you how to manipulate data to make calculations! | # calculate standard deviation (rms) of distribution
print(physicsOnlyDataFrame['AgeAwarded'].std()) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Scatter Plot
Now lets plot a scatter plot of Age vs Date awarded | scatter(physicsOnlyDataFrame['Year'], physicsOnlyDataFrame['AgeAwarded'])
plt.xlim(1900, 2010) # change the x axis range
plt.ylim(20, 100) # change the y axis range
xlabel('Year Awarded')
ylabel('Age Awarded') | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
2D Histogram
We can also plot a 2D histogram and bin the results. The number of entries in the data set is relatively low so we will need to use reasonably large bins to have acceptable statistics in each bin. We have given you the ability to change the number of bins so you can see how the plot changes. Note that the ... | hist2d(physicsOnlyDataFrame.Year, physicsOnlyDataFrame.AgeAwarded, bins=10)
colorbar() # Add a colour legend
xlabel('Year Awarded')
ylabel('Age Awarded') | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Alternatively you can use interact to add a slider to vary the number of bins | def plot_histogram(bins):
hist2d(physicsOnlyDataFrame['Year'].values,physicsOnlyDataFrame['AgeAwarded'].values, bins=bins)
colorbar() #Set a colour legend
xlabel('Year Awarded')
ylabel('Age Awarded')
interact(plot_histogram, bins=[1, 20, 1]) # Creates the slider | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Playing with the slider will show you the effect of changing bthe in size in a 2D histogram. The darker bins in the top right corner show that there does appear to be a trend of Nobel prizes being won at an older age in more recent years.
Manipulating 2D histograms
This section is advanced and only required for the fin... | physics_counts, xedges, yedges, Image = hist2d(
physicsOnlyDataFrame.Year, physicsOnlyDataFrame.AgeAwarded,
bins=10, range=[(1900, 2010), (20, 100)]
)
colorbar() # Add a colour legend
xlabel('Year Awarded')
ylabel('Age Awarded') | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Repeat the procedure used for physics to get the 2D histgram of age against year awarded for chemistry nobel prizes. | # Make the "chemistryOnlyDataFrame" dataset
chemistryOnlyDataFrame = data.query("(Category == 'chemistry')")
chemistryOnlyDataFrame['AgeAwarded'] = chemistryOnlyDataFrame.Year - chemistryOnlyDataFrame.BirthYear
# Plot the histogram
chemistry_counts, xedges, yedges, Image = hist2d(
chemistryOnlyDataFrame.Year, chem... | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Subtract the chemistry_counts from the physics_counts and normalise by their sum. This is known as an asymmetry. | counts = (physics_counts - chemistry_counts) / (physics_counts + chemistry_counts) | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Where there are no nobel prize winners for either subject counts will contain an error value (nan) as the number was divided by zero. Here we replace these error values with 0. | counts[np.isnan(counts)] = 0 | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Finally plot the asymmetry using the pcolor function. As positive and negative values each have a different meaning we use the seismic colormap, see here for a full list of all available colormaps. | pcolor(xedges, yedges, counts, cmap='seismic')
colorbar() | Example-Analysis.ipynb | lhcb/opendata-project | gpl-2.0 |
Now, this program can be executed as follows: | DataStructureVisualization(BinarySearchTree).run()
import io
import base64
from IPython.display import HTML
video = io.open('../res/bst.mp4', 'r+b').read()
encoded = base64.b64encode(video)
HTML(data='''<video alt="test" width="500" height="350" controls>
<source src="data:video/mp4;base64,{0}" type="... | doc/OpenAnalysis/05 - Data Structures.ipynb | OpenWeavers/openanalysis | gpl-3.0 |
Reading Data | #Names of all of the columns
names = [
'sep_length'
, 'sep_width'
, 'petal_length'
, 'petal_width'
, 'species'
]
#Import dataset
data = pd.read_csv('iris.data', sep = ',', header = None, names = names)
data.head(10)
data.shape | Clustering/Iris/Iris.ipynb | neeasthana/ML-SQL | gpl-3.0 |
Separate Data | #Select Predictor columns
X = data.ix[:,:-1]
#Scale X so that all columns have the same mean and variance
X_scaled = preprocessing.scale(X)
#Select target column
y = data['species']
y.value_counts() | Clustering/Iris/Iris.ipynb | neeasthana/ML-SQL | gpl-3.0 |
Scatter Plot Matrix | # Visualize dataset with scatterplot matrix
%matplotlib inline
g = sns.PairGrid(data, hue="species")
g.map_diag(plt.hist)
g.map_offdiag(plt.scatter) | Clustering/Iris/Iris.ipynb | neeasthana/ML-SQL | gpl-3.0 |
K Means (3 clusters) | #train a k-nearest neighbor algorithm
fit = KMeans(n_clusters=3).fit(X_scaled)
fit.labels_
#remake labels so that they properly matchup with the classes
labels = fit.labels_[:]
for index,val in enumerate(labels):
if val == 1:
labels[index] = 1
elif val == 2:
labels[index] = 3
else:
... | Clustering/Iris/Iris.ipynb | neeasthana/ML-SQL | gpl-3.0 |
Having the data in a proper dataframe, we are now in a position to create the features and response values. | # Calculate log-returns and label responses:
# 'direction' equals 1 if stock closed above
# previous day and 0 if it fell.
today = np.log(shsPr / shsPr.shift(1))
direction = np.where(today >= 0, 1, 0)
# Convert 'direction' to dataframe
direction = pd.DataFrame(direction, index=today.index, columns=today.columns)
# ... | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
KNN Algorithm Applied
Now comes the difficult part. What we want to achieve is to run the KNN algorithm for every stock and for different hyperparameter $k$ and see how it performs. For this we do the following steps:
Create a feature matrix X containing Lag1, Lag2 and SMI data for share i
Create a response vector y w... | # Import relevant functions
from sklearn import neighbors
# k = {1, 3, ..., 200}
k = np.arange(1, 200, 2)
# Array to store results in. Dimension is [k x m]
# with m=20 for the 20 companies (excl. SMI)
scr = np.empty(shape=(len(k), len(shsPr.columns)-1))
for i in range(len(shsPr.columns)-1):
# 1) Create mat... | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
Results & Analysis
Now let's see the results in an overview. | scr.describe()
scr.max().nlargest(5) | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
Following finance theory, returns should be distributed symmetrically. Thus the simplest guess would be to expect a share price to increase on 50% of the days and to decrease on the remaining 50%. Similar to guessing a coin flip, if we would guess an 'up' movement for every day, we obviously would - in the long run - b... | nms = ['ABBN', 'ZURN', 'NOVN', 'SIK']
plt.figure(figsize=(12, 8))
for col in nms:
scr[col].plot(legend=True)
plt.axhline(0.50, c='k', ls='--'); | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
For Zurich the peak is early (max. score around $k=60$) while the others peak later, i.e. with higher values of $k$. Furthermore, it seems interesting that for $k > 40$ test scores remained (barely) above 50%. If this is indeed a pattern we would have found a trading strategy, wouldn't we?
To further assess our result... | # 1) Create matrix with feature values of stock i
X = pd.concat([Lag1['ABBN'], Lag2['ABBN'], smi], axis=1)
X = X[3:] # Drop first three rows with NaN (due to lag)
# 2) Remove first three rows of response dataframe
# to have equal no. of rows for features and response
y = direction['ABBN']
y = y[3:]
# 3) Split dat... | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
For GIVN the maximum score is reached where $k=145$. You can check this with the scr['ABBN'].idxmax() command, which provides the index of the maximum value of the selected column. In our case, the index is equivalent to the value of $k$. Thus we run KNN with $k=145$. | scr['ABBN'].idxmax()
# 4) Run KNN
# Instantiate KNN class for GIVN with k=145
knn = neighbors.KNeighborsClassifier(n_neighbors=145)
# Fit KNN classifier using training set
knn = knn.fit(X_train, y_train)
# 5) Extract test score for ABB
scr_ABBN = knn.score(X_test, y_test)
scr_ABBN | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
The score of 59.68% is the very same as what we have seen in above summary statistic. Nothing new so far. (Recall that the score is the total of correctly predicted outcomes.)
However, the alert reader should by now raise some questions regarding our assumption that 50% of the returns should have been positive. In the ... | # Percentage of 'up' days in training set
y_train.sum() / y_train.size | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
Therefore, if we would guess 'up' for every day of our test set and given the distribution of classes in the test set is exactly as in our training set, then we would predict the correct movement in 52.51% of the cases. So in that light, the predictive power of our KNN algorithm has to be put in perspective to the 52.5... | # Predict 'up' (=1) or 'down' (=0) for test set
pred = knn.predict(X_test)
# Store data in DataFrame
cfm = pd.DataFrame({'True direction': y_test,
'Predicted direction': pred})
cfm.replace(to_replace={0:'Down', 1:'Up'}, inplace=True)
# Arrange data to confusion matrix
print(cfm.groupby(['Predicted... | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
As mentioned before, rows represent the true outcome and columns show what class KNN predicted. In 31 cases, the test set's true response was 'down' (in our case represented by 0) and KNN correctly predicted 'down'. 120 times KNN was correct in predicting an 'up' (=1) movement. 19 returns in the test set were positive ... | from sklearn.metrics import confusion_matrix
# Confusion matrix
confusion_matrix(y_test, pred) | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
In general it is tremendously helpful to visualize results. At the time of writing in February 2022, Anaconda shipped with Sklearn version 0.24.2. This Sklearn version uses a confusion matrix-plotting function that is deprecated in versioun 1.0. Therefore, be aware that below plotting function only works for versions <... | from sklearn.metrics import plot_confusion_matrix
# To plot the normalized figures, add normalize = 'true', 'pred', or 'all'
plot_confusion_matrix(estimator = knn,
X = X_test, y_true = y_test,
display_labels = ['Down', 'Up'],
values_format = '.0f');
#... | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
Further Ressources
In writing this notebook, many ressources were consulted. For internet ressources the links are provided within the textflow above and will therefore not be listed again. Beyond these links, the following ressources were consulted and are recommended as further reading on the discussed topics:
Batis... | import sklearn
sklearn.show_versions() | 0207_kNN.ipynb | bMzi/ML_in_Finance | mit |
Part 2 | import matplotlib.pyplot as plt
%matplotlib inline | BikeShareStep2.ipynb | HeyIamJames/bikeshare | mit |
Plot the daily temperature over the course of the year. (This should probably be a line chart.) Create a bar chart that shows the average temperature and humidity by month. | plt.plot(weather['months'], weather['temp'])
plt.xlabel("This is just an x-axis")
plt.ylabel("This is just a y-axis")
plt.show()
x = weather.groupby('months').agg({"humidity":np.mean})
plt.bar([n for n in range(1, 13)], x['humidity'])
plt.title("weather and humidity by months")
plt.show() | BikeShareStep2.ipynb | HeyIamJames/bikeshare | mit |
Use a scatterplot to show how the daily rental volume varies with temperature. Use a different series (with different colors) for each season. | xs = range(10)
plt.scatter(xs, 5 * np.random.rand(10) + xs, color='r', marker='*', label='series1')
plt.scatter(xs, 5 * np.random.rand(10) + xs, color='g', marker='o', label='series2')
plt.title("A scatterplot with two series")
plt.legend(loc=9)
plt.show()
w = weather[['season_desc', 'temp', 'total_riders']]
fall = w.... | BikeShareStep2.ipynb | HeyIamJames/bikeshare | mit |
Create another scatterplot to show how daily rental volume varies with windspeed. As above, use a different series for each season. | w = weather[['season_desc', 'windspeed', 'total_riders']]
fall = w.loc[w['season_desc'] == 'Fall']
winter = w.loc[w['season_desc'] == 'Winter']
spring = w.loc[w['season_desc'] == 'Spring']
summer = w.loc[w['season_desc'] == 'Summer']
plt.scatter(fall['windspeed'], fall['total_riders'], color='orange', marker='^', labe... | BikeShareStep2.ipynb | HeyIamJames/bikeshare | mit |
How do the rental volumes vary with geography? Compute the average daily rentals for each station and use this as the radius for a scatterplot of each station's latitude and longitude. | usage = pd.read_table('usage_2012.tsv')
stations = pd.read_table('stations.tsv')
stations.head()
c = DataFrame(counts.index, columns=['station'])
c['counts'] = counts.values
s = stations[['station','lat','long']]
u = pd.concat([usage['station_start']], axis=1, keys=['station'])
counts = u['station'].value_counts()
m... | BikeShareStep2.ipynb | HeyIamJames/bikeshare | mit |
上面的测试准确率可以看出,不同的训练集、测试集分割的方法导致其准确率不同,而交叉验证的基本思想是:将数据集进行一系列分割,生成一组不同的训练测试集,然后分别训练模型并计算测试准确率,最后对结果进行平均处理。这样来有效降低测试准确率的差异。
2. K折交叉验证
将数据集平均分割成K个等份
使用1份数据作为测试数据,其余作为训练数据
计算测试准确率
使用不同的测试集,重复2、3步骤
对测试准确率做平均,作为对未知数据预测准确率的估计 | # 下面代码演示了K-fold交叉验证是如何进行数据分割的
# simulate splitting a dataset of 25 observations into 5 folds
from sklearn.cross_validation import KFold
kf = KFold(25, n_folds=5, shuffle=False)
# print the contents of each training and testing set
print '{} {:^61} {}'.format('Iteration', 'Training set observations', 'Testing set obser... | Scikit-learn/.ipynb_checkpoints/(4)cross_validation-checkpoint.ipynb | jasonding1354/pyDataScienceToolkits_Base | mit |
3. 使用交叉验证的建议
K=10是一个一般的建议
如果对于分类问题,应该使用分层抽样(stratified sampling)来生成数据,保证正负例的比例在训练集和测试集中的比例相同
4. 交叉验证的例子
4.1 用于调节参数
交叉验证的方法可以帮助我们进行调参,最终得到一组最佳的模型参数。下面的例子我们依然使用iris数据和KNN模型,通过调节参数,得到一组最佳的参数使得测试数据的准确率和泛化能力最佳。 | from sklearn.cross_validation import cross_val_score
knn = KNeighborsClassifier(n_neighbors=5)
# 这里的cross_val_score将交叉验证的整个过程连接起来,不用再进行手动的分割数据
# cv参数用于规定将原始数据分成多少份
scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy')
print scores
# use average accuracy as an estimate of out-of-sample accuracy
# 对十次迭代计算平均的测试... | Scikit-learn/.ipynb_checkpoints/(4)cross_validation-checkpoint.ipynb | jasonding1354/pyDataScienceToolkits_Base | mit |
上面的例子显示了偏置-方差的折中,K较小的情况时偏置较低,方差较高;K较高的情况时,偏置较高,方差较低;最佳的模型参数取在中间位置,该情况下,使得偏置和方差得以平衡,模型针对于非样本数据的泛化能力是最佳的。
4.2 用于模型选择
交叉验证也可以帮助我们进行模型选择,以下是一组例子,分别使用iris数据,KNN和logistic回归模型进行模型的比较和选择。 | # 10-fold cross-validation with the best KNN model
knn = KNeighborsClassifier(n_neighbors=20)
print cross_val_score(knn, X, y, cv=10, scoring='accuracy').mean()
# 10-fold cross-validation with logistic regression
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
print cross_val_score(lo... | Scikit-learn/.ipynb_checkpoints/(4)cross_validation-checkpoint.ipynb | jasonding1354/pyDataScienceToolkits_Base | mit |
4.3 用于特征选择
下面我们使用advertising数据,通过交叉验证来进行特征的选择,对比不同的特征组合对于模型的预测效果。 | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
# read in the advertising dataset
data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
# create a Python list of three feature names
feature_cols = ['TV', 'Radio', 'Newspaper']
# use the list to ... | Scikit-learn/.ipynb_checkpoints/(4)cross_validation-checkpoint.ipynb | jasonding1354/pyDataScienceToolkits_Base | mit |
这里要注意的是,上面的scores都是负数,为什么均方误差会出现负数的情况呢?因为这里的mean_squared_error是一种损失函数,优化的目标的使其最小化,而分类准确率是一种奖励函数,优化的目标是使其最大化。 | # fix the sign of MSE scores
mse_scores = -scores
print mse_scores
# convert from MSE to RMSE
rmse_scores = np.sqrt(mse_scores)
print rmse_scores
# calculate the average RMSE
print rmse_scores.mean()
# 10-fold cross-validation with two features (excluding Newspaper)
feature_cols = ['TV', 'Radio']
X = data[feature_co... | Scikit-learn/.ipynb_checkpoints/(4)cross_validation-checkpoint.ipynb | jasonding1354/pyDataScienceToolkits_Base | mit |
Para ver un ejemplo de su uso, realiza lo siguiente:
* Se define las regiones x e y.
* Se define un polinomio para probar la definición de la región.
* Se utiliza la función region_estabilidad y se grafica el resultado. | #Se define la región
x = np.linspace(-3.0, 1.5)
y = np.linspace(-3.0, 3.0)
X, Y = np.meshgrid(x, y)
#Se define el polinomio
def p(w):
return [1, -1 - w - w ** 2 / 2 - w ** 3 / 6 - w ** 4 / 24]
Z = region_estabilidad(p, X, Y)
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize']=(20,... | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
El ejemplo anterior muestra el uso de Numpy como una biblioteca o módulo que permite hacer manipulación de matrices y como la calidad del procesamiento numérico perminte considarar su uso en problemas de métodos numéricos.
Problema del laberito con Numpy
El problema tiene el mismo nombre que un ejemplo del uso del algo... | #Definición de la matriz
import numpy as np
M=np.matrix([[1.0/3.0,1.0/3.0,0,1.0/3.0,0,0],[1.0/3.0,1.0/3.0,1.0/3.0,0,0,0],[0,1.0/3.0,1.0/3.0,0,0,1.0/3.0],
[1.0/2.0,0,0,1.0/2.0,0,0],[0,0,0,0,1.0/2.0,1.0/2.0],[0,0,1.0/3.0,0,1.0/3.0,1.0/3.0]])
M
#Definición del vector de estados iniciales
v=np.array([1.0/3.... | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
Si se procede ha seguir incrementando los estados o cambios se "estabiliza"; es decir, el cambio en la probabilidad de estar en la caja 1 después de tercer movimiento es 37.53%, lo cual tiende a quedarse en 37.5% al incrementar los movimientos.
Ejemplo de PageRank de manera rupestre, calcuado con Numpy
El algoritmo p... | import numpy as np
M=np.matrix([[.33,.5,1],[.33,0,0],[.33,.5,0]])
lambda1,v=np.linalg.eig(M)
lambda1,v | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
El ejemplo anterior tiene 3 vectores propios y 3 valores propios, pero no refleja el problema en general de la relación entre las páginas web, ya que podría suceder que una página no tienen referencias a ninguan otra salvo a si misma o tienen solo referencias a ella y ella a ninguna, ni a si misma. Entonces un caso más... | from __future__ import division
import numpy as np
#Se definen los calores de las constantes de control y las matrices requeridas
beta=0.85
#Matriz adyacente
M=np.matrix([[0.33,0.25,0.5,0,0],[.33,0,0,0,0],[0.33,0.25,0,0,0],[0,.25,.5,1,0],[0,.25,0,0,1]])
#Cantidad de nodos
n=M.shape[1]
#Matriz del modelo de PageRank... | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
Se tienen como resultado que en 17 iteraciones el algoritmo indica que el PageRank no es totalmente dominado por el nodo E y D, pese a que son las "páginas" que tienen mayor valor, pero las otras 3 resultan muy cercanas en importancia. Se aprecia como se va ajustando el valor conforme avanzan las etapas de los cálculos... | #Se carga el módulo
import pandas as pd
from pandas import Series, DataFrame
#Se construye una Serie, se agregan primero la lista de datos y después la lista de índices
datos_series=Series([1,2,3,4,5,6],index=['a','b','c','d','e','f'])
#Se muestra como carga los datos Pandas en la estrutura definida
datos_series
#Se... | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
Los ejemplos anteriores muestras que es muy sencillo manipular los datos con Pandas, ya sea con Series o con DataFrame. Para mayor detalle de las funciones lo recomendable es consultar las referencias mencionadas anteriormente.
Cargar datos desde diversos archivos y estadísticas sencillas. | #Se agraga a la consola de ipython la salida de matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize']=(30,8)
#Se cargan los datos desde un directorio, se toma como headers los registros de la fila 0
datos=pd.read_csv('~/Documentos/Tutorial-Python/Datos/Mujeres_ingeniería_y_tecn... | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
Viendo los datos que se tienen, es natural preguntarse algo al respecto. Lo sencillo es, ¿cuál es el estado que presenta mayor cantidad de inscripciones de mujeres a ingeniería?, pero también se puede agregar a la pregunta anterior el preguntar en qué año o cíclo ocurrió eso.
Algo sencillo para abordar las anteriores p... | #Se construye una tabla pivot para ordenar los datos y conocer como se comportó el total de mujeres
#inscritas a ingenierías
datos.pivot('ENTIDAD','CICLO','MUJERES_INSC_ING')
#Se revisa cual son los 3 estados con mayor cantidad de inscripciones en el cíclo 2012/2013
datos.pivot('ENTIDAD','CICLO','MUJERES_INSC_ING').s... | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
Observación: se vuelve evidente que las entidades federales o Estados donde se inscriben más mujeres a ingenierías son el Distrito Federal(Ciudad de México), Estado de México, Veracruz, Puebla, Guanajuato, Jalisco y Nuevo León. También se observa que en todos los estados en el periódo 2010/2011 la cantidad de mujeres q... | #Se grafica el boxplot para cada periodo
datos.pivot('ENTIDAD','CICLO','MUJERES_INSC_ING').plot(kind='box', title='Boxplot') | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
Nota: para estre breve análisis se hace uso de la construcción de tablas pivot en pandas. Esto facilidad analizar como se comportan las variables categóricas de los datos. En este ejemplo se muestra que el periódo 2010/2011 tuvo una media mayor de mujeres inscritas en ingeniarías, pero también se ve que la relación ent... | #Se construye la tabla
#Tabla1=datos.pivot('ENTIDAD','CICLO','MUJERES_INSC_ING')
datos.head()
#Se carga la librería seaborn
import seaborn as sns
#sns.set(style="ticks")
#sns.boxplot(x="CICLO",y="MUJERES_INSC_ING",data=datos,palette="PRGn",hue="CICLO") | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
Como cargar un json y analizarlo.
En la siguiente se da una ejemplo de como cargar datos desde algún servicio web que regresa un arvhivo de tipo JSON. | sns.factorplot(x="ENTIDAD",y="MUJERES_INSC_ING",hue="CICLO",data=datos,palette="muted", size=15,kind="bar")
#Otra gráfica, se muestra el cruce entre las mujeres que se inscriben en ingeniería y el total de mujeres
with sns.axes_style('white'):
sns.jointplot('MUJERES_INSC_ING','MAT_TOTAL_SUP',data=datos,kind='hex... | Code/Capítulo_1-Carga_Pandas.ipynb | dlegor/Tutorial-Pandas-Python | cc0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.