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
Indexing and slicing work the exact same way with a 3-dimensional array, but now we have an extra axis to pass in. If we wanted to get the earnings for **January of all years**, we could do this:
# all years, 1st quarter, 1st month (January) earnings[:,0,0]
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
If we wanted to get first quarter earnings from both years, we could do this:
# all years, 1st quarter, all months (January, February, March) earnings[:,0,:]
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
Adding more dimensions can make it much easier to query your data if it's organized in a certain way. As we go from 3-dimensional arrays to 4-dimensional and larger arrays, the same properties apply, and they can be indexed and sliced in the same ways. NumPy Data TypesAs we mentioned earlier, each NumPy array can stor...
wines.dtype
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
NumPy has several different data types, which mostly map to Python data types, like ```float```, and ```str```. You can find a full listing of NumPy data types [here](https://www.dataquest.io/blog/numpy-tutorial-python/), but here are a few important ones:* ```float``` -- numeric floating point data.* ```int``` -- inte...
# convert wines to the int data type wines.astype(int)
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
As you can see above, all of the items in the resulting array are integers. Note that we used the Python ```int``` type instead of a NumPy data type when converting wines. This is because several Python data types, including ```float```, ```int```, and ```string```, can be used with NumPy, and are automatically convert...
# convert to int int_wines = wines.astype(int) # check the data type int_wines.dtype.name
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
The array has been converted to a **64-bit integer** data type. This allows for very long integer values, **but takes up more space in memory** than storing the values as 32-bit integers.If you want more control over how the array is stored in memory, you can directly create NumPy dtype objects like ```numpy.int32```
np.int32
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
You can use these directly to convert between types:
# convert to a 64-bit integer wines.astype(np.int64) # convert to a 32-bit integer wines.astype(np.int32) # convert to a 16-bit integer wines.astype(np.int16) # convert to a 8-bit integer wines.astype(np.int8)
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
NumPy Array OperationsNumPy makes it simple to perform mathematical operations on arrays. This is one of the primary advantages of NumPy, and makes it quite easy to do computations. Single Array MathIf you do any of the basic mathematical operations ```/```, ```*```, ```-```, ```+```, ```^``` with an array and a value...
# add 10 points to the quality score wines[:,-1] + 10
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
*Note: that the above operation won't change the wines array -- it will return a new 1-dimensional array where 10 has been added to each element in the quality column of wines.*If we instead did ```+=```, we'd modify the array in place:
print('Before', wines[:,11]) # modify the data in place wines[:,11] += 10 print('After', wines[:,11])
Before [5. 5. 5. ... 6. 5. 6.] After [15. 15. 15. ... 16. 15. 16.]
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
All the other operations work the same way. For example, if we want to multiply each of the quality score by 2, we could do it like this:
# multiply the quality score by 2 wines[:,11] * 2
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
Multiple Array MathIt's also possible to do mathematical operations between arrays. This will apply the operation to pairs of elements. For example, if we add the quality column to itself, here's what we get:
# add the quality column to itself wines[:,11] + wines[:,11]
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
Note that this is equivalent to ```wines[:,11] * 2``` -- this is because NumPy adds each pair of elements. The first element in the first array is added to the first element in the second array, the second to the second, and so on.
# add the quality column to itself wines[:,11] * 2
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
We can also use this to multiply arrays. Let's say we want to pick a wine that maximizes alcohol content and quality. We'd multiply alcohol by quality, and select the wine with the highest score:
# multiply alcohol content by quality alcohol_by_quality = wines[:,10] * wines[:,11] print(alcohol_by_quality) alcohol_by_quality.sort() print(alcohol_by_quality, alcohol_by_quality[-1])
[650. 650. 650. ... 900. 900. 900.] 900.0
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
All of the common operations ```/```, ```*```, ```-```, ```+```, ```^``` will work between arrays. NumPy Array MethodsIn addition to the common mathematical operations, NumPy also has several methods that you can use for more complex calculations on arrays. An example of this is the ```numpy.ndarray.sum``` method. Thi...
# find the sum of all rows and the quality column total = 0 for row in wines: total += row[11] print(total) # find the sum of all rows and the quality column wines[:,11].sum(axis=0) # find the sum of the rows 1, 2, and 3 across all columns totals = [] for i in range(3): total = 0 for col in wines[i,:]: ...
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
We can pass the ```axis``` keyword argument into the sum method to find sums over an axis. If we call sum across the wines matrix, and pass in ```axis=0```, we'll find the sums over the first axis of the array. This will give us the **sum of all the values in every column**. This may seem backwards that the sums over t...
# sum each column for all rows totals = [0] * len(wines[0]) for i, total in enumerate(totals): for row_val in wines[:,i]: total += row_val totals[i] = total print(totals) # sum each column for all rows wines.sum(axis=0)
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
We can verify that we did the sum correctly by checking the shape. The shape should be 12, corresponding to the number of columns:
wines.sum(axis=0).shape
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
If we pass in axis=1, we'll find the sums over the second axis of the array. This will give us the sum of each row:
# sum each row for all columns totals = [0] * len(wines) for i, total in enumerate(totals): for col_val in wines[i,:]: total += col_val totals[i] = total print(totals[0:3], '...', totals[-3:]) # sum each row for all columns wines.sum(axis=1) wines.sum(axis=1).shape
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
There are several other methods that behave like the sum method, including:* ```numpy.ndarray.mean``` — finds the mean of an array.* ```numpy.ndarray.std``` — finds the standard deviation of an array.* ```numpy.ndarray.min``` — finds the minimum value in an array.* ```numpy.ndarray.max``` — finds the maximum value in a...
# return True for all rows in the Quality column that are greater than 5 wines[:,11] > 5
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
We get a Boolean array that tells us which of the wines have a quality rating greater than 5. We can do something similar with the other operators. For instance, we can see if any wines have a quality rating equal to 10:
# return True for all rows that have a Quality rating of 10 wines[:,11] == 10
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
SubsettingOne of the powerful things we can do with a Boolean array and a NumPy array is select only certain rows or columns in the NumPy array. For example, the below code will only select rows in wines where the quality is over 7:
# create a boolean array for wines with quality greater than 15 high_quality = wines[:,11] > 15 print(len(high_quality), high_quality) # use boolean indexing to find high quality wines high_quality_wines = wines[high_quality,:] print(len(high_quality_wines), high_quality_wines)
855 [[1.12e+01 2.80e-01 5.60e-01 ... 5.80e-01 5.00e+01 1.60e+01] [7.30e+00 6.50e-01 0.00e+00 ... 4.70e-01 5.00e+01 1.70e+01] [7.80e+00 5.80e-01 2.00e-02 ... 5.70e-01 5.00e+01 1.70e+01] ... [5.90e+00 5.50e-01 1.00e-01 ... 7.60e-01 5.00e+01 1.60e+01] [6.30e+00 5.10e-01 1.30e-01 ... 7.50e-01 5.00e+01 1.60e+01] [6.00...
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
We select only the rows where ```high_quality``` contains a ```True``` value, and all of the columns. This subsetting makes it simple to filter arrays for certain criteria. For example, we can look for wines with a lot of alcohol and high quality. In order to specify multiple conditions, we have to place each condition...
# create a boolean array for high alcohol content and high quality high_alcohol_and_quality = (wines[:,11] > 7) & (wines[:,10] > 10) print(high_alcohol_and_quality) # use boolean indexing to select out the wines wines[high_alcohol_and_quality,:]
[ True True True ... True True True]
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
We can combine subsetting and assignment to overwrite certain values in an array:
high_alcohol_and_quality = (wines[:,10] > 10) & (wines[:,11] > 7) wines[high_alcohol_and_quality,10:] = 20
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
Reshaping NumPy ArraysWe can change the shape of arrays while still preserving all of their elements. This often can make it easier to access array elements. The simplest reshaping is to flip the axes, so rows become columns, and vice versa. We can accomplish this with the ```numpy.transpose``` function:
np.transpose(wines).shape
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
We can use the ```numpy.ravel``` function to turn an array into a one-dimensional representation. It will essentially flatten an array into a long sequence of values:
wines.ravel()
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
Here's an example where we can see the ordering of ```numpy.ravel```:
array_one = np.array( [ [1, 2, 3, 4], [5, 6, 7, 8] ] ) array_one.ravel()
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
Finally, we can use the numpy.reshape function to reshape an array to a certain shape we specify. The below code will turn the second row of wines into a 2-dimensional array with 2 rows and 6 columns:
# print the current shape of the 2nd row and all columns wines[1,:].shape # reshape the 2nd row to a 2 by 6 matrix wines[1,:].reshape((2,6))
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
Combining NumPy ArraysWith NumPy, it's very common to combine multiple arrays into a single unified array. We can use ```numpy.vstack``` to vertically stack multiple arrays. Think of it like the second arrays's items being added as new rows to the first array. We can read in the ```winequality-white.csv``` dataset tha...
white_wines = np.genfromtxt("winequality-white.csv", delimiter=";", skip_header=1) white_wines.shape
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
As you can see, we have attributes for 4898 wines. Now that we have the white wines data, we can combine all the wine data.In the below code, we:* Use the ```vstack``` function to combine wines and white_wines.* Display the shape of the result.
all_wines = np.vstack((wines, white_wines)) all_wines.shape
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
As you can see, the result has 6497 rows, which is the sum of the number of rows in wines and the number of rows in red_wines.If we want to combine arrays horizontally, where the number of rows stay constant, but the columns are joined, then we can use the ```numpy.hstack``` function. The arrays we combine need to have...
x = np.concatenate((wines, white_wines), axis=0) print(x.shape, x)
(6497, 12) [[7.40e+00 7.00e-01 0.00e+00 ... 5.60e-01 5.00e+01 1.50e+01] [7.80e+00 8.80e-01 0.00e+00 ... 6.80e-01 5.00e+01 1.50e+01] [7.80e+00 7.60e-01 4.00e-02 ... 6.50e-01 5.00e+01 1.50e+01] ... [6.50e+00 2.40e-01 1.90e-01 ... 4.60e-01 9.40e+00 6.00e+00] [5.50e+00 2.90e-01 3.00e-01 ... 3.80e-01 1.28e+01 7.00e+00]...
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
BroadcastingUnless the arrays that you're operating on are the exact same size, it's not possible to do elementwise operations. In cases like this, NumPy performs broadcasting to try to match up elements. Essentially, broadcasting involves a few steps:* The last dimension of each array is compared. * If the dimensi...
wines * np.array([1,2])
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
The above example didn't work because the two arrays don't have a matching trailing dimension. Here's an example where the last dimension does match:
array_one = np.array( [ [1,2], [3,4] ] ) array_two = np.array([4,5]) array_one + array_two
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
As you can see, array_two has been broadcasted across each row of array_one. Here's an example with our wines data:
rand_array = np.random.rand(12) wines + rand_array
_____no_output_____
MIT
lectures/Week 05 - Data Processing and Visualization Part 2/02 - NumPy Data analysis.ipynb
xiangyuzeng/data-focused-python
This notebook shows how to use yt to make plots and examine FITS X-ray images and events files. Sloshing, Shocks, and Bubbles in Abell 2052 This example uses data provided by [Scott Randall](http://hea-www.cfa.harvard.edu/~srandall/), presented originally in [Blanton, E.L., Randall, S.W., Clarke, T.E., et al. 2011, A...
ds = yt.load( "xray_fits/A2052_merged_0.3-2_match-core_tmap_bgecorr.fits", auxiliary_files=["xray_fits/A2052_core_tmap_b1_m2000_.fits"], )
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
Since the flux and projected temperature images are in two different files, we had to use one of them (in this case the "flux" file) as a master file, and pass in the "temperature" file with the `auxiliary_files` keyword to `load`. Next, let's derive some new fields for the number of counts, the "pseudo-pressure", and...
def _counts(field, data): exposure_time = data.get_field_parameter("exposure_time") return data["fits", "flux"] * data["fits", "pixel"] * exposure_time ds.add_field( ("gas", "counts"), function=_counts, sampling_type="cell", units="counts", take_log=False, ) def _pp(field, data): ret...
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
Here, we're deriving a "counts" field from the "flux" field by passing it a `field_parameter` for the exposure time of the time and multiplying by the pixel scale. Second, we use the fact that the surface brightness is strongly dependent on density ($S_X \propto \rho^2$) to use the counts in each pixel as a "stand-in"....
exposure_time = ds.quan(ds.primary_header["exposure"], "s")
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
Now, we can make the `SlicePlot` object of the fields we want, passing in the `exposure_time` as a `field_parameter`. We'll also set the width of the image to 250 pixels.
slc = yt.SlicePlot( ds, "z", [ ("fits", "flux"), ("fits", "projected_temperature"), ("gas", "pseudo_pressure"), ("gas", "pseudo_entropy"), ], origin="native", field_parameters={"exposure_time": exposure_time}, ) slc.set_log(("fits", "flux"), True) slc.set_log(("ga...
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
To add the celestial coordinates to the image, we can use `PlotWindowWCS`, if you have a recent version of AstroPy (>= 1.3) installed:
from yt.frontends.fits.misc import PlotWindowWCS wcs_slc = PlotWindowWCS(slc) wcs_slc.show()
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
We can make use of yt's facilities for profile plotting as well.
v, c = ds.find_max(("fits", "flux")) # Find the maximum flux and its center my_sphere = ds.sphere(c, (100.0, "code_length")) # Radius of 150 pixels my_sphere.set_field_parameter("exposure_time", exposure_time)
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
Such as a radial profile plot:
radial_profile = yt.ProfilePlot( my_sphere, "radius", ["counts", "pseudo_pressure", "pseudo_entropy"], n_bins=30, weight_field="ones", ) radial_profile.set_log("counts", True) radial_profile.set_log("pseudo_pressure", True) radial_profile.set_log("pseudo_entropy", True) radial_profile.set_xlim(3, 10...
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
Or a phase plot:
phase_plot = yt.PhasePlot( my_sphere, "pseudo_pressure", "pseudo_entropy", ["counts"], weight_field=None ) phase_plot.show()
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
Finally, we can also take an existing [ds9](http://ds9.si.edu/site/Home.html) region and use it to create a "cut region", using `ds9_region` (the [pyregion](https://pyregion.readthedocs.io) package needs to be installed for this):
from yt.frontends.fits.misc import ds9_region reg_file = [ "# Region file format: DS9 version 4.1\n", "global color=green dashlist=8 3 width=3 include=1 source=1 fk5\n", 'circle(15:16:44.817,+7:01:19.62,34.6256")', ] f = open("circle.reg", "w") f.writelines(reg_file) f.close() circle_reg = ds9_region( ...
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
This region may now be used to compute derived quantities:
print( circle_reg.quantities.weighted_average_quantity("projected_temperature", "counts") )
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
Or used in projections:
prj = yt.ProjectionPlot( ds, "z", [ ("fits", "flux"), ("fits", "projected_temperature"), ("gas", "pseudo_pressure"), ("gas", "pseudo_entropy"), ], origin="native", field_parameters={"exposure_time": exposure_time}, data_source=circle_reg, method="sum", ) p...
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
The Bullet Cluster This example uses an events table file from a ~100 ks exposure of the "Bullet Cluster" from the [Chandra Data Archive](http://cxc.harvard.edu/cda/). In this case, the individual photon events are treated as particle fields in yt. However, you can make images of the object in different energy bands u...
from yt.frontends.fits.api import setup_counts_fields
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
`load` will handle the events file as FITS image files, and will set up a grid using the WCS information in the file. Optionally, the events may be reblocked to a new resolution. by setting the `"reblock"` parameter in the `parameters` dictionary in `load`. `"reblock"` must be a power of 2.
ds2 = yt.load("xray_fits/acisf05356N003_evt2.fits.gz", parameters={"reblock": 2})
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
`setup_counts_fields` will take a list of energy bounds (emin, emax) in keV and create a new field from each where the photons in that energy range will be deposited onto the image grid.
ebounds = [(0.1, 2.0), (2.0, 5.0)] setup_counts_fields(ds2, ebounds)
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
The "x", "y", "energy", and "time" fields in the events table are loaded as particle fields. Each one has a name given by "event\_" plus the name of the field:
dd = ds2.all_data() print(dd["io", "event_x"]) print(dd["io", "event_y"])
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
Now, we'll make a plot of the two counts fields we made, and pan and zoom to the bullet:
slc = yt.SlicePlot( ds2, "z", [("gas", "counts_0.1-2.0"), ("gas", "counts_2.0-5.0")], origin="native" ) slc.pan((100.0, 100.0)) slc.set_width(500.0) slc.show()
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
The counts fields can take the field parameter `"sigma"` and use [AstroPy's convolution routines](https://astropy.readthedocs.io/en/latest/convolution/) to smooth the data with a Gaussian:
slc = yt.SlicePlot( ds2, "z", [("gas", "counts_0.1-2.0"), ("gas", "counts_2.0-5.0")], origin="native", field_parameters={"sigma": 2.0}, ) # This value is in pixel scale slc.pan((100.0, 100.0)) slc.set_width(500.0) slc.set_zlim(("gas", "counts_0.1-2.0"), 0.01, 100.0) slc.set_zlim(("gas", "counts_2.0...
_____no_output_____
BSD-3-Clause-Clear
doc/source/cookbook/fits_xray_images.ipynb
Kiradorn/yt
tobac example: Tracking deep convection based on OLR from geostationary satellite retrievals==This example notebook demonstrates the use of tobac to track isolated deep convective clouds based on outgoing longwave radiation (OLR) calculated based on a combination of two different channels of the GOES-13 imaging instrum...
# Import libraries: import iris import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import iris.plot as iplt import iris.quickplot as qplt import zipfile from six.moves import urllib from glob import glob %matplotlib inline # Import tobac itself: import tobac # Disable a few warnings: impor...
_____no_output_____
BSD-3-Clause
examples/Example_OLR_Tracking_satellite/Example_OLR_Tracking_satellite.ipynb
rcjackson/tobac
**Download example data:** This has to be done only once for all tobac examples.
data_out='../' # # Download the data: This only has to be done once for all tobac examples and can take a while # file_path='https://zenodo.org/record/3195910/files/climate-processes/tobac_example_data-v1.0.1.zip' # tempfile='temp.zip' # print('start downloading data') # request=urllib.request.urlretrieve(file_path,tem...
_____no_output_____
BSD-3-Clause
examples/Example_OLR_Tracking_satellite/Example_OLR_Tracking_satellite.ipynb
rcjackson/tobac
**Load data:**
data_file=os.path.join(data_out,'*','data','Example_input_OLR_satellite.nc') data_file = glob(data_file)[0] print(data_file) # Load Data from downloaded file: OLR=iris.load_cube(data_file,'OLR') # Display information about the input data cube: display(OLR) #Set up directory to save output and plots: savedir='Save' if n...
_____no_output_____
BSD-3-Clause
examples/Example_OLR_Tracking_satellite/Example_OLR_Tracking_satellite.ipynb
rcjackson/tobac
**Feature identification:** Identify features based on OLR field and a set of threshold values
# Determine temporal and spatial sampling of the input data: dxy,dt=tobac.get_spacings(OLR,grid_spacing=4000) # Keyword arguments for the feature detection step parameters_features={} parameters_features['position_threshold']='weighted_diff' parameters_features['sigma_threshold']=0.5 parameters_features['min_num']=4 pa...
starting feature detection feature detection performed and saved
BSD-3-Clause
examples/Example_OLR_Tracking_satellite/Example_OLR_Tracking_satellite.ipynb
rcjackson/tobac
**Segmentation:** Segmentation is performed based on the OLR field and a threshold value to determine the cloud areas.
# Keyword arguments for the segmentation step: parameters_segmentation={} parameters_segmentation['target']='minimum' parameters_segmentation['method']='watershed' parameters_segmentation['threshold']=250 # Perform segmentation and save results to files: Mask_OLR,Features_OLR=tobac.segmentation_2D(Features,OLR,dxy,**pa...
segmentation OLR performed, start saving results to files segmentation OLR performed and saved
BSD-3-Clause
examples/Example_OLR_Tracking_satellite/Example_OLR_Tracking_satellite.ipynb
rcjackson/tobac
**Trajectory linking:** The detected features are linked into cloud trajectories using the trackpy library (http://soft-matter.github.io/trackpy). This takes the feature positions determined in the feature detection step into account but does not include information on the shape of the identified objects.
# keyword arguments for linking step parameters_linking={} parameters_linking['v_max']=20 parameters_linking['stubs']=2 parameters_linking['order']=1 parameters_linking['extrapolate']=1 parameters_linking['memory']=0 parameters_linking['adaptive_stop']=0.2 parameters_linking['adaptive_step']=0.95 parameters_linking['su...
Frame 53: 19 trajectories present.
BSD-3-Clause
examples/Example_OLR_Tracking_satellite/Example_OLR_Tracking_satellite.ipynb
rcjackson/tobac
**Visualisation:**
# Set extent of maps created in the following cells: axis_extent=[-95,-89,28,32] # Plot map with all individual tracks: import cartopy.crs as ccrs fig_map,ax_map=plt.subplots(figsize=(10,10),subplot_kw={'projection': ccrs.PlateCarree()}) ax_map=tobac.map_tracks(Track,axis_extent=axis_extent,axes=ax_map) # Creat...
_____no_output_____
BSD-3-Clause
examples/Example_OLR_Tracking_satellite/Example_OLR_Tracking_satellite.ipynb
rcjackson/tobac
Transfer Learning Template
%load_ext autoreload %autoreload 2 %matplotlib inline import os, json, sys, time, random import numpy as np import torch from torch.optim import Adam from easydict import EasyDict import matplotlib.pyplot as plt from steves_models.steves_ptn import Steves_Prototypical_Network from steves_utils.lazy_iterable_wr...
_____no_output_____
MIT
experiments/tl_1v2/oracle.run1.framed-oracle.run2.framed/trials/27/trial.ipynb
stevester94/csc500-notebooks
Allowed ParametersThese are allowed parameters, not defaultsEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)Papermill uses the cell tag "parameters" to inject the real parameters below this cell.Enable tags to see what I mean
required_parameters = { "experiment_name", "lr", "device", "seed", "dataset_seed", "n_shot", "n_query", "n_way", "train_k_factor", "val_k_factor", "test_k_factor", "n_epoch", "patience", "criteria_for_best", "x_net", "datasets", "torch_default_dtype", ...
_____no_output_____
MIT
experiments/tl_1v2/oracle.run1.framed-oracle.run2.framed/trials/27/trial.ipynb
stevester94/csc500-notebooks
To pytraj.Topology
from molsysmt.tools import file_pdb #file_pdb.to_pytraj_Topology(item)
_____no_output_____
MIT
docs/contents/tools/files/file_pdb/to_pytraj_Topology.ipynb
dprada/molsysmt
Building a Fraud Prediction Model with EvalMLIn this demo, we will build an optimized fraud prediction model using EvalML. To optimize the pipeline, we will set up an objective function to minimize the percentage of total transaction value lost to fraud. At the end of this demo, we also show you how introducing the ri...
import evalml from evalml import AutoMLSearch from evalml.objectives import FraudCost
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
Configure "Cost of Fraud" To optimize the pipelines toward the specific business needs of this model, we can set our own assumptions for the cost of fraud. These parameters are* `retry_percentage` - what percentage of customers will retry a transaction if it is declined?* `interchange_fee` - how much of each successfu...
fraud_objective = FraudCost(retry_percentage=.5, interchange_fee=.02, fraud_payout_percentage=.75, amount_col='amount')
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
Search for best pipeline In order to validate the results of the pipeline creation and optimization process, we will save some of our data as the holdout set.
X, y = evalml.demos.load_fraud(n_rows=5000)
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
EvalML natively supports one-hot encoding. Here we keep 1 out of the 6 categorical columns to decrease computation time.
cols_to_drop = ['datetime', 'expiration_date', 'country', 'region', 'provider'] for col in cols_to_drop: X.ww.pop(col) X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(X, y, problem_type='binary', test_size=0.2, random_seed=0) X.ww
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
Because the fraud labels are binary, we will use `AutoMLSearch(X_train=X_train, y_train=y_train, problem_type='binary')`. When we call `.search()`, the search for the best pipeline will begin.
automl = AutoMLSearch(X_train=X_train, y_train=y_train, problem_type='binary', objective=fraud_objective, additional_objectives=['auc', 'f1', 'precision'], allowed_model_families=["random_forest", "linear_model"], ...
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
View rankings and select pipelinesOnce the fitting process is done, we can see all of the pipelines that were searched, ranked by their score on the fraud detection objective we defined.
automl.rankings
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
To select the best pipeline we can call `automl.best_pipeline`.
best_pipeline = automl.best_pipeline
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
Describe pipelinesWe can get more details about any pipeline created during the search process, including how it performed on other objective functions, by calling the `describe_pipeline` method and passing the `id` of the pipeline of interest.
automl.describe_pipeline(automl.rankings.iloc[1]["id"])
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
Evaluate on holdout dataFinally, since the best pipeline is already trained, we evaluate it on the holdout data. Now, we can score the pipeline on the holdout data using both our fraud cost objective and the AUC (Area under the ROC Curve) objective.
best_pipeline.score(X_holdout, y_holdout, objectives=["auc", fraud_objective])
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
Why optimize for a problem-specific objective?To demonstrate the importance of optimizing for the right objective, let's search for another pipeline using AUC, a common machine learning metric. After that, we will score the holdout data using the fraud cost objective to see how the best pipelines compare.
automl_auc = AutoMLSearch(X_train=X_train, y_train=y_train, problem_type='binary', objective='auc', additional_objectives=['f1', 'precision'], max_batches=1, allowed_model_families=["random_...
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
Like before, we can look at the rankings of all of the pipelines searched and pick the best pipeline.
automl_auc.rankings best_pipeline_auc = automl_auc.best_pipeline # get the fraud score on holdout data best_pipeline_auc.score(X_holdout, y_holdout, objectives=["auc", fraud_objective]) # fraud score on fraud optimized again best_pipeline.score(X_holdout, y_holdout, objectives=["auc", fraud_objective])
_____no_output_____
BSD-3-Clause
docs/source/demos/fraud.ipynb
freddyaboulton/evalml
Ruben Arias >- Simple - Compuesto - Continuo
# interes, i, C0, capital inicial, r, periodos def intSimpleCapital(capital, periodos, interes): return capital * (1 + periodos * interes) import numpy as np import matplotlib.pyplot as plt %matplotlib inline listaDeInteres = [.05,.1, .15, .2, .5] # capital = 10000 periodos = 12 for interes in listaDeInteres: ...
_____no_output_____
MIT
ModeloDeAhorro.ipynb
Rubn01/simlacion
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/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Keras custom callbacksA custom callback is a powerful tool to customize the behavior of a Keras model during training, evaluation, or inference, including reading/changing the Keras model. Examples include `...
from __future__ import absolute_import, division, print_function, unicode_literals try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import tensorflow as tf
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Introduction to Keras callbacksIn Keras, `Callback` is a python class meant to be subclassed to provide specific functionality, with a set of methods called at various stages of training (including batch/epoch start and ends), testing, and predicting. Callbacks are useful to get a view on internal states and statistic...
# Define the Keras model to add callbacks to def get_model(): model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(1, activation = 'linear', input_dim = 784)) model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.1), loss='mean_squared_error', metrics=['mae']) return model
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Then, load the MNIST data for training and testing from Keras datasets API:
# Load example MNIST data and pre-process it (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape(60000, 784).astype('float32') / 255 x_test = x_test.reshape(10000, 784).astype('float32') / 255
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Now, define a simple custom callback to track the start and end of every batch of data. During those calls, it prints the index of the current batch.
import datetime class MyCustomCallback(tf.keras.callbacks.Callback): def on_train_batch_begin(self, batch, logs=None): print('Training: batch {} begins at {}'.format(batch, datetime.datetime.now().time())) def on_train_batch_end(self, batch, logs=None): print('Training: batch {} ends at {}'.format(batch,...
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Providing a callback to model methods such as `tf.keras.Model.fit()` ensures the methods are called at those stages:
model = get_model() _ = model.fit(x_train, y_train, batch_size=64, epochs=1, steps_per_epoch=5, verbose=0, callbacks=[MyCustomCallback()])
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Model methods that take callbacksUsers can supply a list of callbacks to the following `tf.keras.Model` methods: [`fit()`](https://www.tensorflow.org/api_docs/python/tf/keras/Modelfit), [`fit_generator()`](https://www.tensorflow.org/api_docs/python/tf/keras/Modelfit_generator)Trains the model for a fixed number of epo...
_ = model.evaluate(x_test, y_test, batch_size=128, verbose=0, steps=5, callbacks=[MyCustomCallback()])
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
An overview of callback methods Common methods for training/testing/predictingFor training, testing, and predicting, following methods are provided to be overridden. `on_(train|test|predict)_begin(self, logs=None)`Called at the beginning of `fit`/`evaluate`/`predict`. `on_(train|test|predict)_end(self, logs=None)`Call...
class LossAndErrorPrintingCallback(tf.keras.callbacks.Callback): def on_train_batch_end(self, batch, logs=None): print('For batch {}, loss is {:7.2f}.'.format(batch, logs['loss'])) def on_test_batch_end(self, batch, logs=None): print('For batch {}, loss is {:7.2f}.'.format(batch, logs['loss'])) def on_...
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Similarly, one can provide callbacks in `evaluate()` calls.
_ = model.evaluate(x_test, y_test, batch_size=128, verbose=0, steps=20, callbacks=[LossAndErrorPrintingCallback()])
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Examples of Keras callback applicationsThe following section will guide you through creating simple Callback applications. Early stopping at minimum lossFirst example showcases the creation of a `Callback` that stops the Keras training when the minimum of loss has been reached by mutating the attribute `model.stop_tr...
import numpy as np class EarlyStoppingAtMinLoss(tf.keras.callbacks.Callback): """Stop training when the loss is at its min, i.e. the loss stops decreasing. Arguments: patience: Number of epochs to wait after min has been hit. After this number of no improvement, training stops. """ def __init__(s...
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Learning rate schedulingOne thing that is commonly done in model training is changing the learning rate as more epochs have passed. Keras backend exposes get_value API which can be used to set the variables. In this example, we're showing how a custom Callback can be used to dynamically change the learning rate.Note: ...
class LearningRateScheduler(tf.keras.callbacks.Callback): """Learning rate scheduler which sets the learning rate according to schedule. Arguments: schedule: a function that takes an epoch index (integer, indexed from 0) and current learning rate as inputs and returns a new learning rate ...
_____no_output_____
Apache-2.0
site/en/guide/keras/custom_callback.ipynb
bogdan-marian/tensorflow-docs
Imports
from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Dropout, Flatten, Input, Concatenate from tensorflow.keras.optimizers import Adam, RMSprop import numpy as np import matplotlib.pyplot as plt import copy
_____no_output_____
MIT
python/GAN/GAN.ipynb
alexandre-lavoie/deep-physics
Global Variables
epochs = 500 batch_size = 16 number_of_particles = epochs * 2 * batch_size dt = 0.1
_____no_output_____
MIT
python/GAN/GAN.ipynb
alexandre-lavoie/deep-physics
Classes
class Particle: def __str__(self): return "Position: %s, Velocity: %s, Accleration: %s" % (self.position, self.velocity, self.acceleration) def __repr__(self): return "Position: %s, Velocity: %s, Accleration: %s" % (self.position, self.velocity, self.acceleration) def __init__(self...
_____no_output_____
MIT
python/GAN/GAN.ipynb
alexandre-lavoie/deep-physics
Training Data
training_set = [] actual_set = [] for i in range(number_of_particles): p = Particle() if(i%2==0): training_set.append(p.get_list()) else: actual_set.append(p.get_list_physics(dt))
_____no_output_____
MIT
python/GAN/GAN.ipynb
alexandre-lavoie/deep-physics
Training
network = GAN(input_size=6,output_size=4,dropout=0) loss = network.train(adverserial_set=training_set,discriminator_set=actual_set,epochs=epochs,batch_size=batch_size) fig = plt.figure(figsize=(13,7)) plt.title("Loss Function over Epochs") plt.xlabel("Epoch") plt.ylabel("Loss") plt.plot(loss["g"], label="Adversarial Lo...
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= Generator_Input (InputLayer) (None, 6) 0 ________________________________________________________...
MIT
python/GAN/GAN.ipynb
alexandre-lavoie/deep-physics
Field operationsThere are several convenience methods that can be used to analyse the field. Let us first define the mesh we are going to work with.
import discretisedfield as df p1 = (-50, -50, -50) p2 = (50, 50, 50) n = (2, 2, 2) mesh = df.Mesh(p1=p1, p2=p2, n=n)
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
We are going to initialise the vector field (`dim=3`), with$$\mathbf{f}(x, y, z) = (xy, 2xy, xyz)$$For that, we are going to use the following Python function.
def value_function(pos): x, y, z = pos return x*y, 2*x*y, x*y*z
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
Finally, our field is
field = df.Field(mesh, dim=3, value=value_function)
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
1. Sampling the fieldAs we have shown previously, a field can be sampled by calling it. The argument must be a 3-length iterable and it contains the coordinates of the point.
point = (0, 0, 0) field(point)
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
However if the point is outside the mesh, an exception is raised.
point = (100, 100, 100) try: field(point) except ValueError: print('Exception raised.')
Exception raised.
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
2. Extracting the component of a vector fieldA three-dimensional vector field can be understood as three separate scalar fields, where each scalar field is a component of a vector field value. A scalar field of a component can be extracted by accessing `x`, `y`, or `z` attribute of the field.
x_component = field.x x_component((0, 0, 0))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
Default names `x`, `y`, and (for dim 3) `z` are only available for fields with dimensionality 2 or 3.
field.components
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
It is possible to change the component names:
field.components = ['mx', 'my', 'mz'] field.mx((0, 0, 0))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
This overrides the component labels and the old `x`, `y` and `z` cannot be used anymore:
try: field.x except AttributeError as e: print(e)
Object has no attribute x.
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
We change the component labels back to `x`, `y`, and `z` for the rest of this notebook.
field.components = ['x', 'y', 'z']
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
Custom component names can optionally also be specified during field creation. If not specified, the default values are used for fields with dimensions 2 or 3. Higher-dimensional fields have no defaults and custom labes have to be specified in order to access individual field components:
field_4d = df.Field(mesh, dim=4, value=[1, 1, 1, 1], components=['c1', 'c2', 'c3', 'c4']) field_4d field_4d.c1((0, 0, 0))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
3. Computing the averageThe average of the field can be obtained by calling `discretisedfield.Field.average` property.
field.average
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
Average always return a tuple, independent of the dimension of the field's value.
field.x.average
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield