markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Multi-dimension slice indexing
If you are familiar with numpy, sliced index then this should be cake for the SimpleITK image. The Python standard slice interface for 1-D object:
<table>
<tr><td>Operation</td> <td>Result</td></tr>
<tr><td>d[i]</td> <td>i-th item of d, starting index 0</td></tr>
<tr><td>d[... | img[24, 24] | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
Cropping | myshow(img[16:48, :])
myshow(img[:, 16:-16])
myshow(img[:32, :32]) | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
Flipping | img_corner = img[:32, :32]
myshow(img_corner)
myshow(img_corner[::-1, :])
myshow(
sitk.Tile(
img_corner,
img_corner[::-1, ::],
img_corner[::, ::-1],
img_corner[::-1, ::-1],
[2, 2],
)
) | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
Slice Extraction
A 2D image can be extracted from a 3D one. | img = sitk.GaborSource(size=[64] * 3, frequency=0.05)
# Why does this produce an error?
myshow(img)
myshow(img[:, :, 32])
myshow(img[16, :, :]) | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
Subsampling | myshow(img[:, ::3, 32]) | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
Mathematical Operators
Most python mathematical operators are overloaded to call the SimpleITK filter which does that same operation on a per-pixel basis. They can operate on a two images or an image and a scalar.
If two images are used then both must have the same pixel type. The output image type is usually the same.... | img = sitk.ReadImage(fdata("cthead1.png"))
img = sitk.Cast(img, sitk.sitkFloat32)
myshow(img)
img[150, 150]
timg = img**2
myshow(timg)
timg[150, 150] | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
Division Operators
All three Python division operators are implemented __floordiv__, __truediv__, and __div__.
The true division's output is a double pixel type.
See PEP 238 to see why Python changed the division operator in Python 3.
Bitwise Logic Operators
<table>
<tr><td>Operators</td></tr>
<tr><td>&</td></t... | img = sitk.ReadImage(fdata("cthead1.png"))
myshow(img) | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
Comparative Operators
<table>
<tr><td>Operators</td></tr>
<tr><td>></td></tr>
<tr><td>>=</td></tr>
<tr><td><</td></tr>
<tr><td><=</td></tr>
<tr><td>==</td></tr>
</table>
These comparative operators follow the same convention as the reset of SimpleITK for binary images. They have the... | img = sitk.ReadImage(fdata("cthead1.png"))
myshow(img) | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
Amazingly make common trivial tasks really trivial | myshow(img > 90)
myshow(img > 150)
myshow((img > 90) + (img > 150)) | Python/02_Pythonic_Image.ipynb | InsightSoftwareConsortium/SimpleITK-Notebooks | apache-2.0 |
First we define the positions of the 3 sites in the perovskite structure and specify the allowed oxidation states at each site. Note that the A site is defined as an anion (i.e. with a -1 oxidation state). | site_A = lattice.Site([0,0,0],[-1])
site_B = lattice.Site([0.5,0.5,0.5],[+5,+4])
site_C = lattice.Site([0.5,0.5,0.5],[-2,-1])
perovskite = lattice.Lattice([site_A,site_B,site_C],space_group=221) | examples/Inverse_perovskites/Inverse_formate_perovskites.ipynb | WMD-group/SMACT | mit |
Approach 1
We now search through the elements of interest (Li-Fr) and find those that are allowed on each site. In this example, we use the F- anion with an increased Shannon radius to simulate the formate anion. We access the Shannon radii data directly from the smact data directory and are interested in the octahedra... | search = smact.ordered_elements(3,87) # Li - Fr
A_list = [] # will be populated with anions
B_list = [] # will be populated with cations
C_list = [['F',-1,4.47]] # is always the "formate anion"
for element in search:
with open(os.path.join(data_directory, 'shannon_radii.csv'),'r') as f... | examples/Inverse_perovskites/Inverse_formate_perovskites.ipynb | WMD-group/SMACT | mit |
NB: We access the data directly from the data directory file here for transparency. However, reading the file multiple times would slow down the code if we were looping over many (perhaps millions to billions) of compositions. As such, reading all the data in once into a dictionary, then accessing that dictionary from ... | # We define the different categories of list we will populate
charge_balanced = []
goldschmidt_cubic = []
goldschmidt_ortho = []
a_too_large = []
A_B_similar = []
pauling_perov = []
anion_stats = []
# We recursively search all ABC combinations using nested for loops
for C in C_list:
anion_hex = 0
anion_cub = 0... | examples/Inverse_perovskites/Inverse_formate_perovskites.ipynb | WMD-group/SMACT | mit |
Approach 2 | # Get list of Element objects
search = [el for el in smact.ordered_elements(3,87) if
Element(el).oxidation_states]
# Covert to list of Species objects
all_species = []
for el in search:
for oxi_state in Element(el).oxidation_states:
all_species.append(Species(el,oxi_state,"6_n"))
... | examples/Inverse_perovskites/Inverse_formate_perovskites.ipynb | WMD-group/SMACT | mit |
Import relevant stingray libraries. | from stingray import Lightcurve, Crossspectrum, sampledata
from stingray.simulator import simulator, models | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Initializing
Instantiate a simulator object and define a variability signal. | var = sampledata.sample_data()
# Beware: set tstart here, or nothing will work!
sim = simulator.Simulator(N=1024, mean=0.5, dt=0.125, rms=0.4, tstart=var.tstart)
| Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
For ease of analysis, define a simple delta impulse response with width 1. Here, start parameter refers to the lag delay, which we will soon see. | delay = 10
s_ir = sim.simple_ir(start=delay, width=1) | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Finally, simulate a filtered light curve. Here, filtered means that the initial lag delay portion is cut. | lc = sim.simulate(var.counts, s_ir)
plt.plot(lc.time, lc.counts)
plt.plot(var.time, var.counts) | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Analysis
Compute crossspectrum. | cross = Crossspectrum(var, lc) | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Rebin the crosss-spectrum for ease of visualization. | cross = cross.rebin(0.0050) | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Calculate time lag. | lag = cross.time_lag() | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Plot lag. | plt.figure()
# Plot lag-frequency spectrum.
plt.plot(cross.freq, lag, 'r')
# Find cutoff points
v_cutoff = 1.0/(2*delay)
h_cutoff = lag[int((v_cutoff-0.0050)*1/0.0050)]
plt.axvline(v_cutoff, color='g',linestyle='--')
plt.axhline(h_cutoff, color='g', linestyle='-.')
# Define axis
plt.axis([0,0.2,-20,20])
plt.xlabel(... | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
According to Uttley et al (2014), the lag-frequency spectrum shows a constant delay until the frequency (1/2*time_delay) which is represented by the green vertical line in the above figure. After this point, the phase wraps and the lag becomes negative.
Energy Dependent Impulse Responses
In practical situations, diffe... | delays = [10,20]
h1 = sim.simple_ir(start=delays[0], width=1)
h2 = sim.simple_ir(start=delays[1], width=1) | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Now, we create two energy channels to simulate light curves for these two impulse responses. | sim.simulate_channel('3.5-4.5', var, h1)
sim.simulate_channel('4.5-5.5', var, h2) | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Compute cross-spectrum for each channel. | cross = [Crossspectrum(var, lc).rebin(0.005) for lc in sim.get_channels(['3.5-4.5', '4.5-5.5'])] | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Calculate lags. | lags = [c.time_lag() for c in cross] | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Get cut-off points. | v_cuts = [1.0/(2*d) for d in delays]
h_cuts = [lag[int((v_cutoff-0.005)*1/0.005)] for lag, v_cut in zip(lags, v_cuts)] | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Plot lag-frequency spectrums. | plt.figure()
plots = []
colors = ['r','g']
energies = ['3.5-4.5 keV', '4.5-5.5 keV']
# Plot lag-frequency spectrum
for i in range(0,len(lags)):
plots += plt.plot(cross[i].freq, lags[i], colors[i], label=energies[i])
plt.axvline(v_cuts[i],color=colors[i],linestyle='--')
plt.axhline(h_cuts[i], color=colors[i... | Simulator/Lag Analysis.ipynb | StingraySoftware/notebooks | mit |
Pre-filter data from other programs (e.g., FreeBayes, GATK)
You can use the program bcftools to pre-filter your data to exclude indels and low quality SNPs. If you ran the conda install commands above then you will have all of the required tools installed. To achieve the format that ipyrad expects you will need to excl... | %%bash
# compress the VCF file if not already done (creates .vcf.gz)
bgzip data.vcf
# tabix index the compressed VCF (creates .vcf.gz.tbi)
tabix data.vcf.gz
# remove multi-allelic SNPs and INDELs and PIPE to next command
bcftools view -m2 -M2 -i'CIGAR="1X" & QUAL>30' data.vcf.gz -Ou |
# remove extra annotation... | newdocs/API-analysis/cookbook-vcf2hdf5.ipynb | dereneaton/ipyrad | gpl-3.0 |
A peek at the cleaned VCF file | # load the VCF as an datafram
dfchunks = pd.read_csv(
"/home/deren/Documents/ipyrad/sandbox/Macaque-Chr1.clean.vcf.gz",
sep="\t",
skiprows=1000,
chunksize=1000,
)
# show first few rows of first dataframe chunk
next(dfchunks).head() | newdocs/API-analysis/cookbook-vcf2hdf5.ipynb | dereneaton/ipyrad | gpl-3.0 |
Converting clean VCF to HDF5
Here I using a VCF file from whole geome data for 20 monkey's from an unpublished study (in progress). It contains >6M SNPs all from chromosome 1. Because many SNPs are close together and thus tightly linked we will likely wish to take linkage into account in our downstream analyses.
The ip... | # init a conversion tool
converter = ipa.vcf_to_hdf5(
name="Macaque_LD20K",
data="/home/deren/Documents/ipyrad/sandbox/Macaque-Chr1.clean.vcf.gz",
ld_block_size=20000,
)
# run the converter
converter.run() | newdocs/API-analysis/cookbook-vcf2hdf5.ipynb | dereneaton/ipyrad | gpl-3.0 |
Downstream analyses
The data file now contains 6M SNPs across 20 samples and N linkage blocks. By default the PCA tool subsamples a single SNP per linkage block. To explore variation over multiple random subsamplings we can use the nreplicates argument. | # init a PCA tool and filter to allow no missing data
pca = ipa.pca(
data="./analysis-vcf2hdf5/Macaque_LD20K.snps.hdf5",
mincov=1.0,
) | newdocs/API-analysis/cookbook-vcf2hdf5.ipynb | dereneaton/ipyrad | gpl-3.0 |
Run a single PCA analysis from subsampled unlinked SNPs | pca.run_and_plot_2D(0, 1, seed=123); | newdocs/API-analysis/cookbook-vcf2hdf5.ipynb | dereneaton/ipyrad | gpl-3.0 |
Run multiple PCAs over replicates of subsampled SNPs
Here you can see the results for a different 10K SNPs that are sampled in each replicate iteration. If the signal in the data is robust then we should expect to see the points clustering at a similar place across replicates. Internally ipyrad will rotate axes to ensu... | pca.run_and_plot_2D(0, 1, seed=123, nreplicates=25); | newdocs/API-analysis/cookbook-vcf2hdf5.ipynb | dereneaton/ipyrad | gpl-3.0 |
Just some helper code to make things easier. metpy_units_handler plugins into siphon to automatically add units to variables. post_process_data is used to clean up some oddities from the NCSS point feature collection. | units.define('degrees_north = 1 degree')
units.define('degrees_east = 1 degree')
unit_remap = dict(inches='inHg', Celsius='celsius')
def metpy_units_handler(vals, unit):
arr = np.array(vals)
if unit:
unit = unit_remap.get(unit, unit)
arr = arr * units(unit)
return arr
# Fix dates and sortin... | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
METAR Meteogram
First we need to grab the catalog for the METAR feature collection data from http://thredds.ucar.edu/thredds/catalog.html | cat = TDSCatalog('http://thredds.ucar.edu/thredds/catalog/nws/metar/ncdecoded/catalog.xml?dataset=nws/metar/ncdecoded/Metar_Station_Data_fc.cdmr') | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Set up NCSS access to the dataset | ds = list(cat.datasets.values())[0]
ncss = NCSS(ds.access_urls['NetcdfSubset'])
ncss.unit_handler = metpy_units_handler | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Create a query for the last 7 days of data for a specific lon/lat point. We should ask for: air temperature, dewpoint temperature, wind speed, and wind direction. | now = datetime.utcnow()
query = ncss.query().accept('csv')
query.lonlat_point(-97, 35.25).time_range(now - timedelta(days=7), now)
query.variables('air_temperature', 'dew_point_temperature', 'wind_speed', 'wind_from_direction') | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Get the data | data = ncss.get_data(query)
data = post_process_data(data) # Fixes for NCSS point | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Heat Index
First, we need relative humidity:
$$RH = e / e_s$$ | e = mpcalc.saturation_vapor_pressure(data['dew_point_temperature'])
e_s = mpcalc.saturation_vapor_pressure(data['air_temperature'])
rh = e / e_s | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Calculate heat index: | # RH should be [0, 100]
hi = mpcalc.heat_index(data['air_temperature'], rh * 100) | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Plot the temperature, dewpoint, and heat index. Bonus points to also plot wind speed and direction. | import matplotlib.pyplot as plt
times = data['time']
fig, axes = plt.subplots(2, 1, figsize=(9, 9))
axes[0].plot(times, data['air_temperature'].to('degF'), 'r', linewidth=2)
axes[0].plot(times, data['dew_point_temperature'].to('degF'), 'g', linewidth=2)
axes[0].plot(times, hi, color='darkred', linestyle='--', linewidth... | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Sounding
First grab the catalog for the Best dataset from the GSD HRRR from http://thredds.ucar.edu/thredds/catalog.html | cat = TDSCatalog('http://thredds-jumbo.unidata.ucar.edu/thredds/catalog/grib/HRRR/CONUS_3km/wrfprs/catalog.xml?dataset=grib/HRRR/CONUS_3km/wrfprs/Best') | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Set up NCSS access to the dataset | best_ds = list(cat.datasets.values())[0]
ncss = NCSS(best_ds.access_urls['NetcdfSubset'])
ncss.unit_handler = metpy_units_handler | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
What variables do we have? | ncss.variables | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Set up a query for the most recent set of data from a point. We should request temperature, dewpoint, and U and V. | query = ncss.query().accept('csv')
query.lonlat_point(-105, 40).time(datetime.utcnow())
query.variables('Temperature_isobaric', 'Dewpoint_temperature_isobaric',
'u-component_of_wind_isobaric', 'v-component_of_wind_isobaric') | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Get the data | data = ncss.get_data(query)
T = data['Temperature_isobaric'].to('degC')
Td = data['Dewpoint_temperature_isobaric'].to('degC')
p = data['vertCoord'].to('mbar') | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Plot a sounding of the data | fig = plt.figure(figsize=(9, 9))
skew = SkewT(fig=fig)
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.ax.set_ylim(1050, 100)
skew.plot_mixing_lines()
skew.plot_dry_adiabats()
skew.plot_moist_adiabats() | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Also calculate the parcel profile and add that to the plot | prof = mpcalc.parcel_profile(p[::-1], T[-1], Td[-1])
skew.plot(p[::-1], prof.to('degC'), 'k', linewidth=2)
fig | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Let's also plot the location of the LCL and the 0 isotherm as well: | lcl = mpcalc.lcl(p[-1], T[-1], Td[-1])
lcl_temp = mpcalc.dry_lapse(concatenate((p[-1], lcl)), T[-1])[-1].to('degC')
skew.plot(lcl, lcl_temp, 'bo')
skew.ax.axvline(0, color='blue', linestyle='--', linewidth=2)
fig | talks/MetPy Exercise.ipynb | Unidata/MetPy | bsd-3-clause |
Let's start with the original regular expression and
string to search from Travis'
regex problem. | pattern = re.compile(r"""
(?P<any>any4?) # "any"
# association
| # or
(?P<object_eq>object ([\w-]+) eq (\d+)) # object
alone... | 20160826-dojo-regex-travis.ipynb | james-prior/cohpy | mit |
The regex had two bugs.
- Two [[ near the end of the pattern string.
- The significant spaces in the pattern (such as after object-group) were being ignored because of re.VERBOSE.
So those bugs are fixed in the pattern below. | pattern = re.compile(r"""
(?P<any>any4?) # "any"
# association
| # or
(?P<object_eq>object\ ([\w-]+)\ eq\ (\d+)) # object
al... | 20160826-dojo-regex-travis.ipynb | james-prior/cohpy | mit |
The above works, but keeping track of the indexes of the unnamed groups drives me crazy. So I add names for all groups. | pattern = re.compile(r"""
(?P<any>any4?) # "any"
# association
| # or
(?P<object_eq>object\ (?P<oe_name>[\w-]+)\ eq\ (?P<oe_i>\d+)) ... | 20160826-dojo-regex-travis.ipynb | james-prior/cohpy | mit |
The following shows me just the groups that matched. | for m in re.finditer(pattern, s):
for key, value in m.groupdict().items():
if value is not None:
print(key, repr(value))
print() | 20160826-dojo-regex-travis.ipynb | james-prior/cohpy | mit |
Looking at the above,
I see that I probably don't care about the big groups,
just the parameters,
so I remove the big groups (except for "any")
from the regular expression. | pattern = re.compile(r"""
(?P<any>any4?) # "any"
# association
| # or
(object\ (?P<oe_name>[\w-]+)\ eq\ (?P<oe_i>\d+)) # object
... | 20160826-dojo-regex-travis.ipynb | james-prior/cohpy | mit |
Now it tells me just the meat of what I want to know. | for m in re.finditer(pattern, s):
for key, value in m.groupdict().items():
if value is not None:
print(key, repr(value))
print() | 20160826-dojo-regex-travis.ipynb | james-prior/cohpy | mit |
Since the variable answer here is defined within each function seperately, you can reuse the same name of the variable, as the scope of the variables itself is different.
Note : Functions, however, can access variables that are defined outside of its scope or in the larger scope, but can only read the value of the va... | egg_count = 0
def buy_eggs():
egg_count += 12 # purchase a dozen eggs
# buy_eggs() | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
In such situations its better to redefine the functions as below. | egg_count = 0
def buy_eggs():
return egg_count + 12
egg_count = buy_eggs()
print(egg_count)
egg_count = buy_eggs()
print(egg_count) | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
List Basics
In Python, it is possible to create a list of values. Each item in the list is called an element and can be accessed individually using a zero-based index. Hence avoiding the need to create multiple variables to store individual values.
Note: negative indexes help access elements from the end of the array. ... | # list of numbers of type Integer
numbers = [1, 2, 3, 4, 5]
print("List :", numbers)
print("Second element :", numbers[1]) ## 2
print("Length of list :",len(numbers)) ## 5
print() # Empty line
# list of strings
colors = ['red', 'blue', 'green']
print("List :", colors)
print ("First color :", colors[0]) ## ... | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Since lists are considered to be sequentially ordered, they support a number of operations that can be applied to any Python sequence.
|Operation Name|Operator|Explanation|
|:-------------|:-------|:----------|
|Indexing|[ ]|Access an element of a sequence|
|Concatenation|+|Combine sequences together|
|Repetition|*|Co... | myList = [1,2,3,4]
# Indexing
A = myList[2]
print(A)
# Repititoin
A = [A]*3
print(A)
# Concatenation
print(myList + A)
# Membership
print(1 in myList)
# Length
print(len(myList))
# Slicing [inclusive : exclusive]
print(myList[1:3])
# Leaving the exclusive parameter empty
print(myList[-3:]) | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Mutability
Strings are immutable and list are mutable.
For example : | # Creating sentence and list form of sentence
name = "Welcome to coding with Python v3.6"
words = ["Welcome", "to", "coding", "with", "Python", "v3.6"]
print(name[4])
print(words[4])
# This is okay
words[5] = "v2.7"
print(words)
# This is not
# name[5] = "d"
# print(name) | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Passed by reference
The list is stored at a memory locations and only a reference of this memory location is what the variable holds. So changes applied to one variable reflect in other variables as well. | langs = ["Python", "Java", "C++", "C"]
languages = langs
langs.append("C#")
print(langs)
print(languages) | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
List Methods
Besides simple accessing of values, lists have a large variety of methods that are used to performed different useful manipulations on them.
Some of them are:
list.append(element): adds a single element to the end of the list. Common error: does not return the new list, just modifies the original. | # list.append example
names = ['Hermione Granger', 'Ronald Weasley']
names.append('Harry Potter')
print("New list :", names) ## ['Hermione Granger', 'Ronald Weasley', 'Harry Potter'] | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
list.insert(index, element): inserts the element at the given index, shifting elements to the right. | # list.insert example
names = ['Ronald Weasley', 'Hermione Granger']
names.insert(1, 'Harry Potter')
print("New list :", names) ## ['Ronald Weasley', 'Harry Potter', 'Hermione Granger'] | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
list.extend(list2): adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend(). | # list.extend example
MainChar = ['Ronald Weasley', 'Harry Potter', 'Hermione Granger']
SupChar = ['Neville Longbottom', 'Luna Lovegood']
MainChar.extend(SupChar)
print("Full list :", MainChar) ## ['Ronald Weasley', 'Harry Potter', 'Hermione Granger', 'Neville Longbottom', 'Luna Lovegood'] | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
list.index(element): searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use 'in' to check without a ValueError). | # list.index example
names = ['Ronald Weasley', 'Harry Potter', 'Hermione Granger']
index = names.index('Harry Potter')
print("Index of Harry Potter in list :",index) ## 1
# Throws a ValueError (Uncomment to see error.)
# index = names.index('Albus Dumbledore') | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
list.remove(element): searches for the first instance of the given element and removes it (throws ValueError if not present) | names = ['Ronald Weasley', 'Harry Potter', 'Hermione Granger']
index = names.remove('Harry Potter') ## ['Ronald Weasley', 'Hermione Granger']
print("Modified list :", names)
| 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
list.pop(index): removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()). | names = ['Ronald Weasley', 'Harry Potter', 'Hermione Granger']
index = names.pop(1)
print("Modified list :", names) ## ['Ronald Weasley', 'Hermione Granger'] | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
list.sort(): sorts the list in place (does not return it). (The sorted() function shown below is preferred.) | alphabets = ['a', 'f','c', 'e','b', 'd']
alphabets.sort();
print ("Sorted list :", alphabets) ## ['a', 'b', 'c', 'd', 'e', 'f']
| 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
list.reverse(): reverses the list in place (does not return it). | alphabets = ['a', 'b', 'c', 'd', 'e', 'f']
alphabets.reverse()
print("Reversed list :", alphabets) ## ['f', 'e', 'd', 'c', 'b', 'a'] | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Others methods include :
- Count : list.count()
- Delete : del list[index]
- Join : "[Seperator string]".join(list)
List Comprehensions
In Python, List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each mem... | # Using loops and list methods
squares = []
for x in range(10):
squares.append(x**2)
print("Squares :", squares) ## [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
exponents = []
for i in range(13):
exponents.append(2**i)
print("Exponents :", exponents) ## [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048,... | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
These extend to more than one line. But by using list comprehensions you can bring it down to just one line. | # Using list comprehensions
squares = [x**2 for x in range(10)]
exponents = [2**i for i in range(13)]
evenSquares = [x for x in squares if x % 2 == 0]
print("Squares :", squares) ## [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print("Exponents :", exponents) ## [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 204... | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Searching
Searching is the process of finding a particular item in a collections of items. It is one of the most common problems that arise in computer programming. A search typically answers either True or False as to whether the item is present.
In Python, there is a very easy way to ask whether an item is in a list ... | # Using in to check if number is present in the list.
print(15 in [3,5,2,4,1])
print('Work' in 'Python Advanced Workshop')
| 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Sometimes it can be important to get the position of the searched value. In that case, we can use index method for lists and the find method for strings. | # Using index to get position of the number if present in list.
# In case of lists, its important to remember that the index function will throw an error if the value isn't present in the list.
values = [3,5,2,4,1]
if 5 in values:
print("Value present at",values.index(5)) ## 1
else:
print("Value not present in li... | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
For more efficient Search Algorithms, look through the Algorithm Implementation section of this repository
Sorting
Sorting is the process of placing elements from a collection in some kind of order.
For example, a list of words could be sorted alphabetically or by length.
A list of cities could be sorted by popula... | # Using sort() with a list.
values = [7, 4, 3, 6, 1, 2, 5]
print("Unsorted list :", values) ## [7, 4, 3, 6, 1, 2, 5]
newValues = values.sort()
print("New list :", newValues) ## None
print("Old list :", values) ## [1, 2, 3, 4, 5, 6, 7]
print()
# Using sorted() with a list.
values = [7, 4, 3, 6, 1, 2... | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Sorting using additional key
For more complex custom sorting, sorted() takes an optional "key=" specifying a "key" function that transforms each element before comparison.
The key function takes in 1 value and returns 1 value, and the returned "proxy" value is used for the comparisons within the sort. | # Using key in sorted
values = ['ccc', 'aaaa', 'd', 'bb']
print (sorted(values, key=len)) ## ['d', 'bb', 'ccc', 'aaaa']
# Remember case sensitivity : All upper case characters come before lower case character in an ascending sequence.
sentence = "This is a test string from Andrew"
print(sorted(sentence.sp... | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Basics on Class and OOP
This section is built around the fundamental of Object Oriented Programming (OOP).
It aims strengthening basics but doesn't justify the broad topic itself. As OOP is a very important programming concept you should read further to better get a grip on python as well as go deep in understanding ho... | class Person:
pass # An empty block
p = Person()
print(p)
| 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Methods
Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object... | class Person:
def say_hi(self):
print('Hello, how are you?')
p = Person()
p.say_hi()
| 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
The init
There are many method names which have special significance in Python classes. We will see the significance of the init method now.
The init method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the double undersc... | class Person:
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Shantanu')
p.say_hi() | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
Object variables
Now let us learn about the data part. The data part, i.e. fields, are nothing but ordinary variables that are bound to the namespaces of the classes and objects. This means that these names are valid within the context of these classes and objects only. That's why they are called name spaces.
There ... | class Robot:
## Represents a robot, with a name.
# A class variable, counting the number of robots
population = 0
def __init__(self, name):
## Initializes the data.
self.name = name
print("(Initializing {})".format(self.name))
# When this person is created, the rob... | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
How It Works
This is a long example but helps demonstrate the nature of class and object variables. Here, population belongs to the Robot class and hence is a class variable. The name variable belongs to the object (it is assigned using self) and hence is an object variable.
Thus, we refer to the population class var... | # ( Uncomment to see Syntax error. )
# for i in range(10) | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
The other type of error, known as a logic error, denotes a situation where the program executes but gives the wrong result. This can be due to an error in the underlying algorithm or an error in your translation of that algorithm. In some cases, logic errors lead to very bad situations such as trying to dividing by zer... | import math
anumber = int(input("Please enter an integer "))
# Give input as negative number and also see output from next code snippet
print(math.sqrt(anumber)) | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
We can handle this exception by calling the print function from within a try block. A corresponding except block catches the exception and prints a message back to the user in the event that an exception occurs. For example: | try:
print(math.sqrt(anumber))
except:
print("Bad Value for square root")
print("Using absolute value instead")
print(math.sqrt(abs(anumber))) | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
It is also possible for a programmer to cause a runtime exception by using the raise statement. For example, instead of calling the square root function with a negative number, we could have checked the value first and then raised our own exception. The code fragment below shows the result of creating a new RuntimeErro... | if anumber < 0:
raise RuntimeError("You can't use a negative number")
else:
print(math.sqrt(anumber)) | 2. Python Advanced.ipynb | ShantanuKamath/PythonWorkshop | mit |
General information on the Gapminder data | display(Markdown("Number of countries: {}".format(len(data))))
display(Markdown("Number of variables: {}".format(len(data.columns))))
# Convert interesting variables in numeric format
for variable in ('internetuserate', 'suicideper100th', 'employrate'):
data[variable] = pd.to_numeric(data[variable], errors='coerce... | Making_Data_Management.ipynb | fcollonval/coursera_data_visualization | mit |
But the unemployment rate is not provided directly. In the database, the employment rate (% of the popluation) is available. So the unemployement rate will be computed as 100 - employment rate: | data['unemployrate'] = 100. - data['employrate'] | Making_Data_Management.ipynb | fcollonval/coursera_data_visualization | mit |
The first records of the data restricted to the three analyzed variables are: | subdata = data[['internetuserate', 'suicideper100th', 'unemployrate']]
subdata.head(10) | Making_Data_Management.ipynb | fcollonval/coursera_data_visualization | mit |
Data analysis
We will now have a look at the frequencies of the variables after grouping them as all three are continuous variables. I will group the data in intervals using the cut function.
Internet use rate frequencies | display(Markdown("Internet Use Rate (min, max) = ({0:.2f}, {1:.2f})".format(subdata['internetuserate'].min(), subdata['internetuserate'].max())))
internetuserate_bins = pd.cut(subdata['internetuserate'],
bins=np.linspace(0, 100., num=21))
counts1 = internetuserate_bins.value_counts(sort... | Making_Data_Management.ipynb | fcollonval/coursera_data_visualization | mit |
Suicide per 100,000 people frequencies | display(Markdown("Suicide per 100,000 people (min, max) = ({:.2f}, {:.2f})".format(subdata['suicideper100th'].min(), subdata['suicideper100th'].max())))
suiciderate_bins = pd.cut(subdata['suicideper100th'],
bins=np.linspace(0, 40., num=21))
counts2 = suiciderate_bins.value_counts(sort=False... | Making_Data_Management.ipynb | fcollonval/coursera_data_visualization | mit |
Unemployment rate frequencies | display(Markdown("Unemployment rate (min, max) = ({0:.2f}, {1:.2f})".format(subdata['unemployrate'].min(), subdata['unemployrate'].max())))
unemployment_bins = pd.cut(subdata['unemployrate'],
bins=np.linspace(0, 100., num=21))
counts3 = unemployment_bins.value_counts(sort=False, dropna=Fals... | Making_Data_Management.ipynb | fcollonval/coursera_data_visualization | mit |
Decision Tree Classification | from plots import plot_tree_interactive
plot_tree_interactive() | 05.1 Trees and Forests.ipynb | amueller/advanced_training | bsd-2-clause |
Random Forests | from plots import plot_forest_interactive
plot_forest_interactive()
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
X, y = make_moons(n_samples=100, noise=0.25, random_state=3)
X_train, X_test, y_train, y_test = train_tes... | 05.1 Trees and Forests.ipynb | amueller/advanced_training | bsd-2-clause |
Selecting the Optimal Estimator via Cross-Validation | from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
boston = load_boston()
X, y = boston.data, boston.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_st... | 05.1 Trees and Forests.ipynb | amueller/advanced_training | bsd-2-clause |
Prepare the pipeline
(str) filepath: Give the csv file
(str) y_col: The column to predict
(bool) regression: Regression or Classification ?
(bool) process: (WARNING) apply some preprocessing on your data (tune this preprocess with params below)
(char) sep: delimiter
(list) col_to_drop: which columns you don't want to u... | cls = Baboulinet(filepath="toto.csv", y_col="predict", regression=False) | mozinor/example/Mozinor example Class.ipynb | Jwuthri/Mozinor | mit |
Now run the pipeline
May take some times | res = cls.babouline() | mozinor/example/Mozinor example Class.ipynb | Jwuthri/Mozinor | mit |
The class instance, now contains 2 objects, the model for this data, and the best stacking for this data
To make auto generate the code of the model
Generate the code for the best model | cls.bestModelScript() | mozinor/example/Mozinor example Class.ipynb | Jwuthri/Mozinor | mit |
Generate the code for the best stacking | cls.bestStackModelScript() | mozinor/example/Mozinor example Class.ipynb | Jwuthri/Mozinor | mit |
To check which model is the best
Best model | res.best_model
show = """
Model: {},
Score: {}
"""
print(show.format(res.best_model["Estimator"], res.best_model["Score"])) | mozinor/example/Mozinor example Class.ipynb | Jwuthri/Mozinor | mit |
Best stacking | res.best_stack_models
show = """
FirstModel: {},
SecondModel: {},
Score: {}
"""
print(show.format(res.best_stack_models["Fit1stLevelEstimator"], res.best_stack_models["Fit2ndLevelEstimator"], res.best_stack_models["Score"])) | mozinor/example/Mozinor example Class.ipynb | Jwuthri/Mozinor | mit |
Network Architecture
The encoder part of the network will be a typical convolutional pyramid. Each convolutional layer will be followed by a max-pooling layer to reduce the dimensions of the layers. The decoder though might be something new to you. The decoder needs to convert from a narrow representation to a wide rec... | learning_rate = 0.001
inputs_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='input')
targets_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='input')
### Encoder
conv1 = tf.layers.conv2d(inputs_, 16, (3, 3), padding='SAME', activation=tf.nn.relu)
# Now 28x28x16
maxpool1 = tf.layers.max_pooling2d(conv1, (2... | autoencoder/Convolutional_Autoencoder.ipynb | danresende/deep-learning | mit |
Denoising
As I've mentioned before, autoencoders like the ones you've built so far aren't too useful in practive. However, they can be used to denoise images quite successfully just by training the network on noisy images. We can create the noisy images ourselves by adding Gaussian noise to the training images, then cl... | learning_rate = 0.001
inputs_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='inputs')
targets_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='targets')
### Encoder
conv1 = tf.layers.conv2d(inputs_, 32, (3, 3), padding='SAME', activation=tf.nn.relu)
# Now 28x28x32
maxpool1 = tf.layers.max_pooling2d(conv1,... | autoencoder/Convolutional_Autoencoder.ipynb | danresende/deep-learning | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.