markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Filtering (cutting) events and particles with advanced selectionsNumPy has a versatile selection mechanism:The same expressions apply to Awkward Arrays, and more. | # First particle momentum in the first 5 events
events.prt.p[:5, 0]
# First two particles in all events
events.prt.pdg[:, :2]
# First direction of the last event
events.prt.dir[-1, 0] | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
NumPy also lets you filter (cut) using an array of booleans. | events.prt_count > 100
np.count_nonzero(events.prt_count > 100)
events[events.prt_count > 100] | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
One dimension can be selected with an array while another is selected with a slice. | # Select events with at least two particles, then select the first two particles
events.prt[events.prt_count >= 2, :2] | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
This can be a good way to avoid errors from trying to select what isn't there. | try:
events.prt[:, 0]
except Exception as err:
print(type(err).__name__, str(err))
events.prt[events.prt_count > 0, 0] | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
See also [awkward-array.readthedocs.io](https://awkward-array.readthedocs.io/) for a list of operations like [ak.num](https://awkward-array.readthedocs.io/en/latest/_auto/ak.num.html): | ?ak.num
ak.num(events.prt), events.prt_count | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
You can even use an array of integers to select a set of indexes at once. | # First and last particle in each event that has at least two
events.prt.pdg[ak.num(events.prt) >= 2][:, [0, -1]] | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
But beyond NumPy, we can also use arrays of nested lists as boolean or integer selectors. | # Array of lists of True and False
abs(events.prt.vtx) > 0.10
# Particles that have vtx > 0.10 for all events (notice that there's still 10000)
events.prt[abs(events.prt.vtx) > 0.10] | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
See [awkward-array.readthedocs.io](https://awkward-array.readthedocs.io/) for more, but there are functions like [ak.max](https://awkward-array.readthedocs.io/en/latest/_auto/ak.max.html), which picks the maximum in a groups. * With `axis=0`, the group is the set of all events. * With `axis=1`, the groups are parti... | ?ak.max
ak.max(abs(events.prt.vtx), axis=1)
# Selects *events* that have a maximum *particle vertex* greater than 100
events[ak.max(abs(events.prt.vtx), axis=1) > 100] | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
The difference between "select particles" and "select events" is the number of jagged dimensions in the array; "reducers" like ak.max reduce the dimensionality by one.There are other reducers like ak.any, ak.all, ak.sum... | ?ak.sum
# Is this particle an antineutron?
events.prt.pdg == Particle.from_string("n~").pdgid
# Are any particles in the event antineutrons?
ak.any(events.prt.pdg == Particle.from_string("n~").pdgid, axis=1)
# Select events that contain an antineutron
events[ak.any(events.prt.pdg == Particle.from_string("n~").pdgid, ax... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
We can use these techniques to make subcollections for specific particle types and attach them to the same `events` array for easy access. | events.prt[abs(events.prt.pdg) == abs(Particle.from_string("p").pdgid)]
# Assignments have to be through __setitem__ (brackets), not __setattr__ (as an attribute).
# Is that a problem? (Assigning as an attribute would have to be implemented with care, if at all.)
events["pions"] = events.prt[abs(events.prt.pdg) == abs... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Flattening for plots and regularizing to NumPy for machine learningAll of this structure is great, but eventually, we need to plot the data or ship it to some statistical process, such as machine learning.Most of these tools know about NumPy arrays and rectilinear data, but not Awkward Arrays. As a design choice, Awkw... | ?ak.flatten
# Turn particles-grouped-by-event into one big array of particles
ak.flatten(events.prt, axis=1)
# Eliminate structure at all levels; produce one numerical array
ak.flatten(events.prt, axis=None) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
For plotting, you probably want to pick one field and flatten it. Flattening with `axis=1` (the default) works for one level of structure and is safer than `axis=None`.The flattening is explicit as a reminder that a histogram whose entries are particles is different from a histogram whose entries are events. | # Directly through Matplotlib
plt.hist(ak.flatten(events.kaons.p), bins=100, range=(0, 10))
# Through mplhep and boost-histgram, which are more HEP-friendly
hep.histplot(bh.Histogram(bh.axis.Regular(100, 0, 10)).fill(
ak.flatten(events.kaons.p)
)) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
If the particles are sorted (`ak.sort`/`ak.argsort` is [in development](https://github.com/scikit-hep/awkward-1.0/pull/168)), you might want to pick the first kaon from every event that has them (i.e. *use* the event structure).This is an analysis choice: *you* have to decide you want this.The `ak.num(events.kaons) > 0... | hep.histplot(bh.Histogram(bh.axis.Regular(100, 0, 10)).fill(
events.kaons.p[ak.num(events.kaons) > 0, 0]
)) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Or perhaps the maximum pion momentum in each event. This one must be flattened (with `axis=0`) to remove `None` values.This flattening is explicit as a reminder that empty events are not counted in the histogram. | ak.max(events.kaons.p, axis=1)
ak.flatten(ak.max(events.kaons.p, axis=1), axis=0)
hep.histplot(bh.Histogram(bh.axis.Regular(100, 0, 10)).fill(
ak.flatten(ak.max(events.kaons.p, axis=1), axis=0)
)) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Or perhaps the momentum of the kaon with the farthest vertex. [ak.argmax](https://awkward-array.readthedocs.io/en/latest/_auto/ak.argmax.html) creates an array of integers selecting from each event. | ?ak.argmax
ak.argmax(abs(events.kaons.vtx), axis=1)
?ak.singletons
# Get a length-1 list containing the index of the biggest vertex when there is one
# And a length-0 list when there isn't one
ak.singletons(ak.argmax(abs(events.kaons.vtx), axis=1))
# A nested integer array like this is what we need to select kaons with... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
If you're sending the data to a library that expects rectilinear structure, you might need to pad and clip the variable length lists.[ak.pad_none](https://awkward-array.readthedocs.io/en/latest/_auto/ak.pad_none.html) puts `None` values at the end of each list to reach a minimum length. | ?ak.pad_none
# pad them look at the first 30
ak.pad_none(events.kaons.id, 3)[:30].tolist() | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
The lengths are still irregular, so you can also `clip=True` them. | # pad them look at the first 30
ak.pad_none(events.kaons.id, 3, clip=True)[:30].tolist() | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
The library we're sending this to might not be able to deal with missing values, so choose a replacement to fill them with. | ?ak.fill_none
# fill with -1 <- pad them look at the first 30
ak.fill_none(ak.pad_none(events.kaons.id, 3, clip=True), -1)[:30].tolist() | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
These are still Awkward-brand arrays; the downstream library might complain if they're not NumPy-brand, so use [ak.to_numpy](https://awkward-array.readthedocs.io/en/latest/_auto/ak.to_numpy.html) or simply cast it with NumPy's `np.asarray`. | ?ak.to_numpy
np.asarray(ak.fill_none(ak.pad_none(events.kaons.id, 3, clip=True), -1)) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
If you try to convert an Awkward Array as NumPy and structure would be lost, you get an error. (You won't accidentally eliminate structure.) | try:
np.asarray(events.kaons.id)
except Exception as err:
print(type(err), str(err)) | <class 'ValueError'> in ListOffsetArray64, cannot convert to RegularArray because subarray lengths are not regular
| BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Broadcasting flat arrays and jagged arraysNumPy lets you combine arrays and scalars in a mathematical expression by first "broadcasting" the scalar to an array of the same length. | print(np.array([1, 2, 3, 4, 5]) + 100) | [101 102 103 104 105]
| BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Awkward Array does the same thing, except that each element of a flat array can be broadcasted to each nested list of a jagged array. | print(ak.Array([[1, 2, 3], [], [4, 5], [6]]) + np.array([100, 200, 300, 400])) | [[101, 102, 103], [], [304, 305], [406]]
| BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
This is useful for emulating```pythonall_vertices = []for event in events: vertices = [] for kaon in events.kaons: all_vertices.append((kaon.vtx.x - event.true.x, kaon.vtx.y - event.true.y)) all_vertices.append(vertices)```where `event.true.x` and `y` have only one value per ... | # one value per kaon one per event
ak.zip([events.kaons.vtx.x - events.true.x,
events.kaons.vtx.y - events.true.y]) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
You don't have to do anything special for this: broadcasting is a common feature of all functions that apply to more than one array.You can get it explicitly with [ak.broadcast_arrays](https://awkward-array.readthedocs.io/en/latest/_auto/ak.broadcast_arrays.html). | ?ak.broadcast_arrays
ak.broadcast_arrays(events.true.x, events.kaons.vtx.x) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Combinatorics: cartesian and combinationsAt all levels of a physics analysis, we need to compare objects drawn from different collections. * **Gen-reco matching:** to associate a reconstructed particle with its generator-level parameters. * **Cleaning:** assocating soft photons with a reconstructed electron or lep... | ?ak.cartesian
?ak.combinations
ak.to_list(ak.cartesian(([[1, 2, 3], [], [4]],
[["a", "b"], ["c"], ["d", "e"]])))
ak.to_list(ak.combinations([["a", "b", "c", "d"], [], [1, 2]], 2)) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
To search for $\Lambda^0 \to \pi p$, we need to compute the mass of pairs drawn from these two collections. | pairs = ak.cartesian([events.pions, events.protons])
pairs
?ak.unzip
def mass(pairs, left_mass, right_mass):
left, right = ak.unzip(pairs)
left_energy = np.sqrt(left.p**2 + left_mass**2)
right_energy = np.sqrt(right.p**2 + right_mass**2)
return np.sqrt((left_energy + right_energy)**2 -
... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
We can improve the peak by selecting for opposite charges and large vertexes. | def opposite(pairs):
left, right = ak.unzip(pairs)
return pairs[left.charge != right.charge]
def distant(pairs):
left, right = ak.unzip(pairs)
return pairs[np.logical_and(abs(left.vtx) > 0.10, abs(right.vtx) > 0.10)]
hep.histplot(bh.Histogram(bh.axis.Regular(100, 1.115683 - 0.01, 1.115683 + 0.01)).fill... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Alternatively, all of these functions could have been methods on the pair objects for reuse.(This is to make the point that any kind of object can have methods, not just particles.) | class ParticlePairArray(ak.Array):
__name__ = "Pairs"
def mass(self, left_mass, right_mass):
left, right = self.slot0, self.slot1
left_energy = np.sqrt(left.p**2 + left_mass**2)
right_energy = np.sqrt(right.p**2 + right_mass**2)
return np.sqrt((left_energy + right_energy)**2... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
**Self-study question:** why does the call to `mass` have to be last? An example for `ak.combinations`: $K_S \to \pi\pi$. | pairs = ak.combinations(events.pions, 2, with_name="pair")
pairs
hep.histplot(bh.Histogram(bh.axis.Regular(100, 0.497611 - 0.015, 0.497611 + 0.015)).fill(
ak.flatten(pairs.opposite().distant(0.10).mass(0.139570, 0.139570))
)) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
**Bonus problem:** $D^0 \to K^- \pi^+ \pi^0$ | pizero_candidates = ak.combinations(events.prt[events.prt.pdg == Particle.from_string("gamma").pdgid], 2, with_name="pair")
pizero = pizero_candidates[pizero_candidates.mass(0, 0) - 0.13498 < 0.000001]
pizero["px"] = pizero.slot0.px + pizero.slot1.px
pizero["py"] = pizero.slot0.py + pizero.slot1.py
pizero["pz"] = pizer... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
This Dalitz plot doesn't look right (doesn't cut off at kinematic limits), but I'm going to leave it as an exercise for the reader. | dalitz = bh.Histogram(bh.axis.Regular(50, 0, 3), bh.axis.Regular(50, 0, 2))
dalitz.fill(ak.flatten(mKpi), ak.flatten(mpipi))
X, Y = dalitz.axes.edges
fig, ax = plt.subplots()
mesh = ax.pcolormesh(X.T, Y.T, dalitz.view().T)
fig.colorbar(mesh) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Reducing from combinationsThe mass-peak examples above don't need to "reduce" combinations, but many applications do. Suppose that we want to find the "nearest photon to each electron" (e.g. bremsstrahlung). | electrons = events.prt[abs(events.prt.pdg) == abs(Particle.from_string("e-").pdgid)]
photons = events.prt[events.prt.pdg == Particle.from_string("gamma").pdgid] | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
The problem with the raw output of `ak.cartesian` is that all the combinations are mixed together in the same lists. | ak.to_list(ak.cartesian([electrons[["pdg", "id"]], photons[["pdg", "id"]]])[8]) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
We can fix this by asking for `nested=True`, which adds another level of nesting to the output. | ak.to_list(ak.cartesian([electrons[["pdg", "id"]], photons[["pdg", "id"]]], nested=True)[8]) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
All electron-photon pairs associated with a given electron are grouped in a list-within-each-list.Now we can apply reducers to this inner dimension to sum over some quantity, pick the best one, etc. | def cos_angle(pairs):
left, right = ak.unzip(pairs)
return left.dir.x*right.dir.x + left.dir.y*right.dir.y + left.dir.z*right.dir.z
electron_photons = ak.cartesian([electrons, photons], nested=True)
cos_angle(electron_photons)
hep.histplot(bh.Histogram(bh.axis.Regular(100, -1, 1)).fill(
ak.flatten(cos_angle... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
We pick the "maximum according to a function" using the same `ak.singletons(ak.argmax(f(x))` trick as above. | best_electron_photons = electron_photons[ak.singletons(ak.argmax(cos_angle(electron_photons), axis=2))]
hep.histplot(bh.Histogram(bh.axis.Regular(100, -1, 1)).fill(
ak.flatten(cos_angle(best_electron_photons), axis=None)
)) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
By construction, `best_electron_photons` has zero or one elements in each *inner* nested list. | ak.num(electron_photons, axis=2), ak.num(best_electron_photons, axis=2) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Since we no longer care about that *inner* structure, we could flatten it at `axis=2` (leaving `axis=1` untouched). | best_electron_photons
ak.flatten(best_electron_photons, axis=2) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
But it would be better to invert the `ak.singletons` by calling `ak.firsts`. | ?ak.singletons
?ak.firsts
ak.firsts(best_electron_photons, axis=2) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Because then we can get back one value for each electron (with `None` if `ak.argmax` resulted in `None` because there were no pairs). | ak.num(electrons), ak.num(ak.firsts(best_electron_photons, axis=2))
ak.all(ak.num(electrons) == ak.num(ak.firsts(best_electron_photons, axis=2))) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
And that means that we can make this "closest photon" an attribute of the electrons. We have now performed electron-photon matching. | electrons["photon"] = ak.firsts(best_electron_photons, axis=2)
ak.to_list(electrons[8]) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Current set of reducers: * [ak.count](https://awkward-array.readthedocs.io/en/latest/_auto/ak.count.html): counts the number in each group (subtly different from [ak.num](https://awkward-array.readthedocs.io/en/latest/_auto/ak.num.html) because `ak.count` is a reducer) * [ak.count_nonzero](https://awkward-array.rea... | import numba as nb
@nb.jit
def monte_carlo_pi(nsamples):
acc = 0
for i in range(nsamples):
x = np.random.random()
y = np.random.random()
if (x**2 + y**2) < 1.0:
acc += 1
return 4.0 * acc / nsamples
%%timeit
# Run the pure Python function (without nb.jit)
monte_carlo_pi.... | 8.7 ms ± 194 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
| BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
The price for this magical speedup is that not all Python code can be accelerated; you have to be conservative with the functions and language features you use, and Numba has to recognize the data types.Numba recognizes Awkward Arrays. | @nb.jit
def lambda_mass(events):
num_lambdas = 0
for event in events:
num_lambdas += len(event.pions) * len(event.protons)
lambda_masses = np.empty(num_lambdas, np.float64)
i = 0
for event in events:
for pion in event.pions:
for proton in event.protons:
p... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Some constraints: * Awkward arrays are read-only structures (always true, even outside of Numba) * Awkward arrays can't be created inside a Numba-compiled functionThat was fine for a function that creates and returns a NumPy array, but what if we want to create something with structure? The [ak.ArrayBuilder](https:... | ?ak.ArrayBuilder
builder = ak.ArrayBuilder()
builder.begin_list()
builder.begin_record()
builder.field("x").integer(1)
builder.field("y").real(1.1)
builder.field("z").string("one")
builder.end_record()
builder.begin_record()
builder.field("x").integer(2)
builder.field("y").real(2.2)
builder.field("z").string("two")
... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
ArrayBuilders can be used in Numba, albeit with some constraints: * ArrayBuilders can't be created inside a Numba-compiled function (pass them in) * The `snapshot` method (to turn it into an array) can't be used in a Numba-compiled function (use it outside) | @nb.jit(nopython=True)
def make_electron_photons(events, builder):
for event in events:
builder.begin_list()
for electron in event.electrons:
best_i = -1
best_angle = -1.0
for i in range(len(event.photons)):
photon = event.photons[i]
... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
A few of them are `None` (called `builder.null()` because there were no photons to attach to the electron). | ak.count_nonzero(ak.is_none(ak.flatten(builder.snapshot()))) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
But the `builder.snapshot()` otherwise matches up with the `events.electrons`, so it's something we could attach to it, as before. | ?ak.with_field
events["electrons"] = ak.with_field(events.electrons, builder.snapshot(), "photon")
ak.to_list(events[8].electrons) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Grafting jagged data onto PandasAwkward Arrays can be Pandas columns. | import pandas as pd
df = pd.DataFrame({"pions": events.pions,
"kaons": events.kaons,
"protons": events.protons})
df
df["pions"].dtype | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
But that's unlikely to be useful for very complex data structures because there aren't any Pandas functions for deeply nested structure.Instead, you'll probably want to *convert* the nested structures into the corresponding Pandas [MultiIndex](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html). | ak.pandas.df(events.pions) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Now the nested lists are represented as MultiIndex rows and the nested records are represented as MultiIndex columns, which are structures that Pandas knows how to deal with. But what about two types of particles, pions and kaons? (And let's simplify to just `"px", "py", "pz", "vtx"`.) | simpler = ak.zip({"pions": events.pions[["px", "py", "pz", "vtx"]],
"kaons": events.kaons[["px", "py", "pz", "vtx"]]}, depthlimit=1)
ak.type(simpler)
ak.pandas.df(simpler) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
There's only one row MultiIndex, so pion 1 in each event is the same row as kaon 1. That assocation is probably meaningless.The issue is that a single Pandas DataFrame represents *less* information than an Awkward Array. In general, we would need a collection of DataFrames to losslessly encode an Awkward Array. (Pandas... | # This array corresponds to *two* Pandas DataFrames.
pions_df, kaons_df = ak.pandas.dfs(simpler)
pions_df
kaons_df | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
NumExpr, Autograd, and other third-party libraries [NumExpr](https://numexpr.readthedocs.io/en/latest/user_guide.html) can calcuate pure numerical expressions faster than NumPy because it does so in one pass. (It has a low-overhead virtual machine.)NumExpr doesn't recognize Awkward Arrays, but we have a wrapper for it... | import numexpr
# This works because px, py, pz are flat, like NumPy
px = ak.flatten(events.pions.px)
py = ak.flatten(events.pions.py)
pz = ak.flatten(events.pions.pz)
numexpr.evaluate("px**2 + py**2 + pz**2")
# This doesn't work because px, py, pz have structure
px = events.pions.px
py = events.pions.py
pz = events.pi... | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
Similarly for [Autograd](https://github.com/HIPS/autogradreadme), which has an `elementwise_grad` for differentiating expressions with respect to NumPy [universal functions](https://docs.scipy.org/doc/numpy/reference/ufuncs.html), but not Awkward Arrays. | @ak.autograd.elementwise_grad
def tanh(x):
y = np.exp(-2.0 * x)
return (1.0 - y) / (1.0 + y)
ak.to_list(tanh([{"x": 0.0, "y": []}, {"x": 0.1, "y": [1]}, {"x": 0.2, "y": [2, 2]}, {"x": 0.3, "y": [3, 3, 3]}])) | _____no_output_____ | BSD-3-Clause | docs-jupyter/2020-04-08-eic-jlab.ipynb | reikdas/awkward-1.0 |
说明: 给定由数字(‘0’-‘9’)和‘’组成的字符串s。 我们希望将s映射到英文小写字符,如下所示: 1、字符(‘a’到‘i’)分别由(‘1’到‘9’)表示。 2、字符(‘j’到‘z’)分别由(‘10’到‘26’)表示。 返回映射后形成的字符串。 可以保证唯一的映射将始终存在。Example 1: Input: s = "101112" Output: "jkab" Explanation: "j" -> "10" , "k" -> "11" , "a" -> "1" , "b" -> "2".Example 2: Input: s = "1326" Output:... | class Solution:
def freqAlphabets(self, s: str) -> str:
res = ''
idx = 0
while idx < len(s):
if idx + 2 < len(s) and 1 <= int(s[idx]) <= 2 and s[idx + 2] == '#':
val = int(s[idx] + s[idx + 1])
idx += 2
else:
val = int(s[... | _____no_output_____ | Apache-2.0 | String/1013/1309. Decrypt String from Alphabet to Integer Mapping.ipynb | YuHe0108/Leetcode |
IEEE-CIS Fraud Detection Can you detect fraud from customer transactions? | # Análise dos dados
import pandas as pd
# Visualização dos dados
import matplotlib.pyplot as plt
import seaborn as sn | _____no_output_____ | MIT | Mentoria Fraudes/Mentoria - Fraudes Leon.ipynb | leon-maia/Portfolio-Voyager |
SampleSubmission é o formato de entrega do modelo. Desconsiderar Dataset. | df_SampleSubmission = pd.read_csv('sample_submission.csv')
df_SampleSubmission.head() | _____no_output_____ | MIT | Mentoria Fraudes/Mentoria - Fraudes Leon.ipynb | leon-maia/Portfolio-Voyager |
Analisando o dataset test_identity.csv MetadadosIdentity TableVariables in this table are identity information – network connection information (IP, ISP, Proxy, etc) and digital signature (UA/browser/os/version, etc) associated with transactions.They're collected by Vesta’s fraud protection system and digital security... | df_test_identity = pd.read_csv('test_identity.csv')
l, c = df_test_identity.shape
l
df_test_identity.head()
df_test_identity.tail()
df_test_identity.info()
df_test_identity.isnull().sum().sort_values(ascending=False)
(df_test_identity.isnull().sum().sort_values(ascending=False) / l) * 100
df_test_identity_corr = df_tes... | _____no_output_____ | MIT | Mentoria Fraudes/Mentoria - Fraudes Leon.ipynb | leon-maia/Portfolio-Voyager |
Analisando o dataset test_transaction.csv Transaction table“It contains money transfer and also other gifting goods and service, like you booked a ticket for others, etc.”TransactionDT: timedelta from a given reference datetime (not an actual timestamp)“TransactionDT first value is 86400, which corresponds to the numb... | df_test_transaction = pd.read_csv('test_transaction.csv')
display(df_test_transaction)
l2, c2 = df_test_transaction.shape
df_test_transaction.info(verbose=True)
# Para visualizar todas as colunas (antes de conhecer o atributo 'verbose'), criei uma Serie com o nome das colunas
df_test_transactionColumns = pd.Series(df_t... | _____no_output_____ | MIT | Mentoria Fraudes/Mentoria - Fraudes Leon.ipynb | leon-maia/Portfolio-Voyager |
High-level RNN TF Example | import numpy as np
import os
import sys
import tensorflow as tf
from common.params_lstm import *
from common.utils import *
# Force one-gpu
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
print("OS: ", sys.platform)
print("Python: ", sys.version)
print("Numpy: ", np.__version__)
print("Tensorflow: ", tf.__version__)
print("GP... | Accuracy: 0.8598557692307692
| MIT | notebooks/Tensorflow_RNN.ipynb | ThomasDelteil/DeepLearningFrameworks |
Question Engagement Analysis Select course and load data set | data_dir = '/Users/benny/data/L@S_2021'
course = 'microbiology'
data_set_filename = f'engagement_{course}.txt'
data_set = pd.read_csv( f'{data_dir}/{data_set_filename}', sep='\t' )
data_set | _____no_output_____ | CC-BY-4.0 | l@s-2021/Question Engagement Analysis.ipynb | vitalsource/data |
Mean engagement | data_set.groupby( 'question_type' ).mean().sort_values( by='answered', ascending=False ) | _____no_output_____ | CC-BY-4.0 | l@s-2021/Question Engagement Analysis.ipynb | vitalsource/data |
Regression model | %%R
library( lme4 ) | R[write to console]: Loading required package: Matrix
| CC-BY-4.0 | l@s-2021/Question Engagement Analysis.ipynb | vitalsource/data |
Standardize the continuous variables. | for col in [ 'course_page_number', 'unit_page_number', 'module_page_number', 'page_question_number' ]:
data_set[ col ] = ( data_set[ col ] - data_set[ col ].mean() ) / data_set[ col ].std()
data_set.to_csv( '/tmp/to_r.csv', index=False )
%%R
df <- read.csv( '/tmp/to_r.csv' )
%%R
lme.model <- glmer( answered ~ cours... | R[write to console]: fixed-effect model matrix is rank deficient so dropping 1 column / coefficient
| CC-BY-4.0 | l@s-2021/Question Engagement Analysis.ipynb | vitalsource/data |
1- Write a list comprehensions that contains numbers from 1 to 31, append the prefix "1-" to the numbers, these are day of January | L = [f"1-{day}" for day in range(1,32)] | _____no_output_____ | MIT | 10-warmup-solution_comprehensions.ipynb | hanisaf/advanced-data-management-and-analytics |
2- convert the list to a string so each entry prints on one line. Print the result | line = '\n'.join(L)
print(line)
from functools import reduce
line = reduce(lambda x, y: f"{x}\n{y}", L)
print(line)
def combine(x, y):
return x + '\n' + y
line = reduce(combine, L)
print(line) | _____no_output_____ | MIT | 10-warmup-solution_comprehensions.ipynb | hanisaf/advanced-data-management-and-analytics |
3- Update the comprehension to vary prefix from 1- to 12- to generate all days of the year, do not worry about incorrect dates for now | L = [ f"{month}-{day}" for month in range(1, 13) for day in range(1,32) ]
L | _____no_output_____ | MIT | 10-warmup-solution_comprehensions.ipynb | hanisaf/advanced-data-management-and-analytics |
4- now, address the issue of some months being only 30 days and february if 28 days (this year). Hint, use the `valid_date` function | def valid_date(day, month):
days_of_month = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30,
7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
max_month = days_of_month[month]
return day <= max_month
L = [ f"{month}-{day}" for month in range(1, 13) for day in range(1,32) if valid_date(day, month)]
L | _____no_output_____ | MIT | 10-warmup-solution_comprehensions.ipynb | hanisaf/advanced-data-management-and-analytics |
5- using dictionary comprehensions create `f2e` dictionary from the `e2f` dictionary | e2f = {'hi':'bonjour', 'bye':'au revoir', 'bread':'pain', 'water':'eau'}
f2e = { e2f[k]:k for k in e2f}
f2e
f2e = {item[1]:item[0] for item in e2f.items()}
f2e
f2e = {v:k for (k,v) in e2f.items()}
f2e
f2e = {e2f[k]:k for k in e2f} | _____no_output_____ | MIT | 10-warmup-solution_comprehensions.ipynb | hanisaf/advanced-data-management-and-analytics |
div.container { width: 100% }Tutorial 4. Interlinked Plots hvPlot allows you to generate a number of different types of plot quickly from a standard API, returning Bokeh-based [HoloViews](https://holoviews.org) objects as discussed in the previous notebook. Each initial plot will make some aspects of the data clear, an... | import holoviews as hv
import pandas as pd
import hvplot.pandas # noqa
import colorcet as cc | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
First let us load the data as before: | %%time
df = pd.read_parquet('../data/earthquakes-projected.parq')
df.time = df.time.astype('datetime64[ns]')
df = df.set_index(df.time) | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
And filter to the most severe earthquakes (magnitude `> 7`): | most_severe = df[df.mag >= 7] | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
Linked brushing across elementsIn the previous notebook, we saw how plot axes are automatically linked for panning and zooming when using the `+` operator, provided the dimensions match. When dimensions or an underlying index match across multiple plots, we can use a similar principle to achieve linked brushing, where... | mag_hist = most_severe.hvplot(
y='mag', kind='hist', responsive=True, min_height=150)
depth_hist = most_severe.hvplot(
y='depth', kind='hist', responsive=True, min_height=150) | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
These two histograms are plotting two different dimensions of our earthquake dataset (magnitude and depth), derived from the same set of earthquake samples. The samples between these two histograms share an index, and the relationships between these data points can be discovered and exploited programmatically even thou... | ls = hv.link_selections.instance() | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
Given some HoloViews objects (elements, layouts, etc.), we can create versions of them linked to this shared linking object by calling `ls` on them: | ls(depth_hist + mag_hist) | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
Try using the first Bokeh tool to select areas of either histogram: you'll then see both the depth and magnitude distributions for the bins you have selected, compared to the overall distribution. By default, selections on both histograms are combined so that the selection is the intersection of the two regions selecte... | geo = most_severe.hvplot(
'easting', 'northing', color='mag', kind='points', tiles='ESRI', xlim=(-3e7,3e7), ylim=(-5e6,5e6),
xaxis=None, yaxis=None, responsive=True, height=350, cmap = cc.CET_L4[::-1], framewise=True) | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
Once again, we just need to pass our points to the `ls` object (newly declared here to be independent of the one above) to declare the linkage: | ls2 = hv.link_selections.instance()
(ls2(geo + depth_hist)).cols(1) | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
Now you can use the box-select tool to select earthquakes on the map and view their corresponding depth distribution, or vice versa. E.g. if you select just the earthquakes in Alaska, you can see that they tend not to be very deep underground (though that may be a sampling issue). Other selections will show other prope... | ls2.filter(most_severe) | _____no_output_____ | BSD-3-Clause | examples/tutorial/04_Interlinked_Plots.ipynb | maximlt/holoviz |
How does our lab collect data?Here was a small Python project that I thought of - are there trends in the rate of data collection in our lab at the CfA? From a qualitative sense, it always felt that when visitors come, several come at once and one would expect this would reflect in the number of scans produced in a sm... | ft1_df = pd.read_pickle("../data/FTM1_scans.pkl")
ft2_df = pd.read_pickle("../data/FTM2_scans.pkl")
# Convert the datetime handling into numpy format
for df in [ft1_df, ft2_df]:
df["date"] = df["date"].astype("datetime64") | _____no_output_____ | MIT | notebooks/1_Lab scan collection.ipynb | laserkelvin/SlowFourierTransform |
Simple statistics behind the data collection, I'll be using FT1, and also exclude the last row (which is 2019). | yearly = ft1_df.groupby([ft1_df["date"].dt.year]) | _____no_output_____ | MIT | notebooks/1_Lab scan collection.ipynb | laserkelvin/SlowFourierTransform |
Average number of scans per year | scans = ufloat(
np.average(yearly["shots"].describe()["count"].iloc[:-1]),
np.std(yearly["shots"].describe()["count"].iloc[:-1])
)
scans
shots = ufloat(
np.average(yearly["shots"].describe()["mean"].iloc[:-1]),
np.std(yearly["shots"].describe()["mean"].iloc[:-1])
)
shots | _____no_output_____ | MIT | notebooks/1_Lab scan collection.ipynb | laserkelvin/SlowFourierTransform |
Convert this to time spent per year in days | ((shots / 5.) * scans) / 60. / 60. / 24. | _____no_output_____ | MIT | notebooks/1_Lab scan collection.ipynb | laserkelvin/SlowFourierTransform |
What's the actual number of shots in a year? | actual_shots = ufloat(
np.average(yearly.sum()["shots"].iloc[:-1]),
np.std(yearly.sum()["shots"].iloc[:-1])
)
actual_shots
(actual_shots / 5. / 60.) / 60. / 24. | _____no_output_____ | MIT | notebooks/1_Lab scan collection.ipynb | laserkelvin/SlowFourierTransform |
So approximately, the experiments are taking data only for 42 days a year total. Of course, this doesn't reflect reality (you spend most of the time trying to make the experiment work the way you want to of course). I'm also curious how this compares with other labs... | # Bin all of the data into year, month, and day
grouped_dfs = [
df.groupby([df["date"].dt.year, df["date"].dt.month, df["date"].dt.day]).count() for df in [ft1_df, ft2_df]
]
for df in grouped_dfs:
df["cumulative"] = np.cumsum(df["id"])
flattened_dfs = [
df.set_index(df.index.map(lambda t: pd.datetime(*t))) ... | <div><div id="b01d543c-a117-41d1-943d-7fdd17531616" style="height: 600.0px; width: 100%;" class="plotly-graph-div"></div><script type="text/javascript">window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("b01d543c-a117-41d1-943d-7fdd17531616", [{"name": "FT1", "x": ["2014-... | MIT | notebooks/1_Lab scan collection.ipynb | laserkelvin/SlowFourierTransform |
***KNN Classification*** | from sklearn.neighbors import KNeighborsClassifier
knc = KNeighborsClassifier(n_neighbors = 17)
X,y = credit.loc[:,credit.columns != 'Class'], credit.loc[:,'Class']
knc.fit(X_train,y_train)
y_knc = knc.predict(X_test)
print('accuracy of training set: {:.4f}'.format(knc.score(X_train,y_train)))
print('accuracy of test s... | confusion_matrix of KNN: [[71070 12]
[ 26 94]]
precision_score of KNN: 0.8867924528301887
recall_score of KNN: 0.7833333333333333
precision_recall_curve: (array([0.00168535, 0.88679245, 1. ]), array([1. , 0.78333333, 0. ]), array([0, 1]))
| MIT | dataset/creditCard/Credit Card.ipynb | Necropsy/XXIIISI-Minicurso |
**Random Forest Regression** | from sklearn.ensemble import RandomForestRegressor
reg = RandomForestRegressor(n_estimators = 20, random_state = 0)
reg.fit(X_train,y_train)
y_rfr = reg.predict(X_test)
reg.score(X_test, y_test)
print('accuracy of training set: {:.4f}'.format(reg.score(X_train,y_train)))
print('accuaracy of test set: {:.4f}'.format(reg... | accuracy_score of decision tree regression: 0.999283727985169
confusion_matrix of decision tree regression: [[71061 30]
[ 21 90]]
precision_score of decision tree regression: 0.75
recall_score of decision tree regression: 0.8108108108108109
precision_recall_curve: (array([0.00155894, 0.75 , 1. ... | MIT | dataset/creditCard/Credit Card.ipynb | Necropsy/XXIIISI-Minicurso |
**Decision Tree Regression** | from sklearn.tree import DecisionTreeRegressor
regs = DecisionTreeRegressor(random_state = 0)
regs.fit(X_train, y_train)
y_dtr = regs.predict(X_test)
regs.score(X_test, y_test)
print('accuracy of training set: {:.4f}'.format(regs.score(X_train,y_train)))
print('accuaracy of test set: {:.4f}'.format(regs.score(X_test, y... | accuracy_score of decision tree regression: 0.999283727985169
confusion_matrix of decision tree regression: [[71061 30]
[ 21 90]]
precision_score of decision tree regression: 0.75
recall_score of decision tree regression: 0.8108108108108109
precision_recall_curve: (array([0.00155894, 0.75 , 1. ... | MIT | dataset/creditCard/Credit Card.ipynb | Necropsy/XXIIISI-Minicurso |
**Logistic Regression** | from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression(random_state = 0)
logreg.fit(X_train, y_train)
y_lr = logreg.predict(X_test)
logreg.score(X_test, y_test)
print('accuracy of training set: {:.4f}'.format(logreg.score(X_train,y_train)))
print('accuaracy of test set: {:.4f}'.format(logreg.sc... | accuracy of training set: 0.9990
accuaracy of test set: 0.9991
| MIT | dataset/creditCard/Credit Card.ipynb | Necropsy/XXIIISI-Minicurso |
**Decision Tree Classification** | from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)
y_dtc = classifier.predict(X_test)
classifier.score(X_test, y_test)
print('accuracy of training set: {:.4f}'.format(classifier.score(X_train,y_train)))
print('acc... | accuracy_score of decesion tree classifier: 0.9991994606893064
confusion_matrix of decision tree classifier: [[71048 23]
[ 34 97]]
precision_score of decision tree classifier: 0.8083333333333333
recall_score of decision tree classifier: 0.7404580152671756
precision_recall_curve of decision tree classifier:... | MIT | dataset/creditCard/Credit Card.ipynb | Necropsy/XXIIISI-Minicurso |
**Naive Bayes Classification** | from sklearn.naive_bayes import GaussianNB
NBC = GaussianNB()
NBC.fit(X_train, y_train)
y_nb = NBC.predict(X_test)
NBC.score(X_test, y_test)
print('accuracy of training set: {:.4f}'.format(NBC.score(X_train,y_train)))
print('accuaracy of test set: {:.4f}'.format(NBC.score(X_test, y_test)))
print('accuracy_score of Naiv... | accuracy_score of Naive Bayes: 0.9784697059071374
confusion_matrix of Naive Bayes: [[69569 1513]
[ 20 100]]
precision_score of Naive Bayes: 0.06199628022318661
recall_score of Naive Bayes: 0.8333333333333334
precision_recall_curve of Naive Bayes: (array([0.00168535, 0.06199628, 1. ]), array([1. ... | MIT | dataset/creditCard/Credit Card.ipynb | Necropsy/XXIIISI-Minicurso |
#@title
!git clone https://github.com/hiren14/World-health-organization-WHO-GUIDELINES-SYSTEM # clone
%cd World-health-organization-WHO-GUIDELINES-SYSTEM
%pip install -qr requirements.txt # install
#@title
import torch
import utils
display = utils.notebook_init() # checks
!python detect.py --weights yolov5s.pt --... | [34m[1mdetect: [0mweights=['yolov5s.pt'], source=data/images/img3.jpg, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs... | MIT | World_health_organization_WHO_GUIDELINES_SYSTEM.ipynb | hiren14/World-health-organization-WHO-GUIDELINES-SYSTEM | |
I once had a coworker tasked with creating a web-based dashboard. Unfortunately, the data he needed to log and visualize came from this binary application that didn't have any sort of documented developer api -- it just printed everything to stdout -- that he didn't have the source code for either. It was basically a b... | from subprocess import Popen, PIPE
import logging; logging.getLogger().setLevel(logging.INFO)
import sys
import time
import json
PROG = """
import json
import time
from datetime import datetime
while True:
data = {
'time': datetime.now().strftime('%c %f milliseconds'),
'string': 'hello, world',
... | INFO:root:{'time': 'Mon Sep 25 16:16:21 2017 690000 milliseconds', 'string': 'hello, world'}
INFO:root:{'time': 'Mon Sep 25 16:16:21 2017 690084 milliseconds', 'string': 'hello, world'}
INFO:root:{'time': 'Mon Sep 25 16:16:21 2017 690111 milliseconds', 'string': 'hello, world'}
INFO:root:{'time': 'Mon Sep 25 16:16:21 2... | MIT | notebooks/Wrapping Subprocesses in Asyncio.ipynb | knowsuchagency/knowsuchagency.github.io.old |
The problem The problem my coworker had is that in the time he marshaled one line of output of the program and logged the information, several more lines had already been printed by the subprocess. His wrapper simply couldn't keep up with the subprocess' output.Notice in the example above, that although many more line... | #!/usr/bin/env python3
#
# Spawns multiple instances of printer.py and attempts to deserialize the output
# of each line in another process and print the result to the screen,
import typing as T
import asyncio.subprocess
import logging
import sys
import json
from concurrent.futures import ProcessPoolExecutor, Executor... | _____no_output_____ | MIT | notebooks/Wrapping Subprocesses in Asyncio.ipynb | knowsuchagency/knowsuchagency.github.io.old |
Week 3 Inroduction Date: 21 Oct 2021Last week you learned about different methods for segmenting an image into regions of interest. In this session you will get some experience coding image segmentation algorithms. Your task will be to code a simple statistical method that uses k-means clustering. | import numpy as np
import copy
import cv2
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
%matplotlib inline #to visualize the plots within the notebook | UsageError: unrecognized arguments: #to visualize the plots within the notebook
| MIT | labs/week_3.ipynb | Meewnicorn/ImPro26 |
K-means SegmentationK-means clustering is a well-known approach for separating data (often of high dimensionality) intodifferent groups depending on their distance. In the case of images this is a useful method forsegmenting an image into regions, provided that the number of regions (k) is known in advance. It isbased... | # Load image and conver to float representation
raw_img = cv2.imread("../images/sample_image.jpg") # change file name to load different images
raw_gray_img = cv2.cvtColor(raw_img, cv2.COLOR_BGR2GRAY)
img = raw_img.astype(np.float32) / 255.
gray_img = raw_gray_img.astype(np.float32) / 255.
plt.subplot(1, 2, 1)
plt.imsho... | _____no_output_____ | MIT | labs/week_3.ipynb | Meewnicorn/ImPro26 |
Results on Gray-scale Image | from sklearn.cluster import KMeans
# write your code here
| [[0.762243 ]
[0.28945854]]
| MIT | labs/week_3.ipynb | Meewnicorn/ImPro26 |
Results on RGB image | # write your code here
| [[0.82212555 0.7523794 0.7282207 ]
[0.2380477 0.32608324 0.22135933]]
| MIT | labs/week_3.ipynb | Meewnicorn/ImPro26 |
2. Implement your own k-meansNow you need to implement your own k-means function. Use your function on different greyscale images and try comparing the results to the results you get from sklearn kmeans function. Implement your own functions here: | def my_kmeans(I, k):
"""
Parameters
----------
I: the image to be segmented (greyscale to begin with) H by W array
k: the number of clusters (use a simple image with k=2 to begin with)
Returns
----------
clusters: a vector that contains the final cluster centres
L: an array the same... | _____no_output_____ | MIT | labs/week_3.ipynb | Meewnicorn/ImPro26 |
Show results here: | centroids, labels = my_kmeans(gray_img, 2)
print(centroids)
plt.imshow(labels) | [0.28945825 0.76224351]
| MIT | labs/week_3.ipynb | Meewnicorn/ImPro26 |
More things to try out:1. Try different values for k. For k > 2 you will need some way to display the output L (other than simple black and white). Consider using a colour map with the imshow function.2. Adapt your function so that it will handle colour images as well. What changes do you have to make? | # k=3
centroids, labels = my_kmeans_vec(gray_img, 3)
plt.imshow(labels)
print(centroids)
centroids, labels = my_kmeans_rgb(img, 2)
plt.imshow(labels)
print(centroids) | [[0.23840699 0.32619616 0.22162087]
[0.82255203 0.75285155 0.72873324]]
| MIT | labs/week_3.ipynb | Meewnicorn/ImPro26 |
Copyright 2019 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/en/r2/tutorials/estimators/_boosted_trees_model_understanding.ipynb | ThomasTransboundaryYan/docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.