repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
content
stringlengths
335
154k
mne-tools/mne-tools.github.io
0.13/_downloads/plot_point_spread.ipynb
bsd-3-clause
import os.path as op import numpy as np import mne from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, apply_inverse from mne.simulation import simulate_stc, simulate_evoked """ Explanation: Corrupt known signal with point spread The aim of this tutorial is to demonstrate how to put a known signal at a desired location(s) in a :class:mne.SourceEstimate and then corrupt the signal with point-spread by applying a forward and inverse solution. End of explanation """ seed = 42 # parameters for inverse method method = 'sLORETA' snr = 3. lambda2 = 1.0 / snr ** 2 # signal simulation parameters # do not add extra noise to the known signals evoked_snr = np.inf T = 100 times = np.linspace(0, 1, T) dt = times[1] - times[0] # Paths to MEG data data_path = sample.data_path() subjects_dir = op.join(data_path, 'subjects') fname_fwd = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-oct-6-fwd.fif') fname_inv = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-oct-6-meg-fixed-inv.fif') fname_evoked = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif') """ Explanation: First, we set some parameters. End of explanation """ fwd = mne.read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) fwd['info']['bads'] = [] inv_op = read_inverse_operator(fname_inv) raw = mne.io.RawFIF(op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')) events = mne.find_events(raw) event_id = {'Auditory/Left': 1, 'Auditory/Right': 2} epochs = mne.Epochs(raw, events, event_id, baseline=(None, 0), preload=True) epochs.info['bads'] = [] evoked = epochs.average() labels = mne.read_labels_from_annot('sample', subjects_dir=subjects_dir) label_names = [l.name for l in labels] n_labels = len(labels) """ Explanation: Load the MEG data End of explanation """ cov = mne.compute_covariance(epochs, tmin=None, tmax=0.) """ Explanation: Estimate the background noise covariance from the baseline period End of explanation """ # The known signal is all zero-s off of the two labels of interest signal = np.zeros((n_labels, T)) idx = label_names.index('inferiorparietal-lh') signal[idx, :] = 1e-7 * np.sin(5 * 2 * np.pi * times) idx = label_names.index('rostralmiddlefrontal-rh') signal[idx, :] = 1e-7 * np.sin(7 * 2 * np.pi * times) """ Explanation: Generate sinusoids in two spatially distant labels End of explanation """ hemi_to_ind = {'lh': 0, 'rh': 1} for i, label in enumerate(labels): # The `center_of_mass` function needs labels to have values. labels[i].values.fill(1.) # Restrict the eligible vertices to be those on the surface under # consideration and within the label. surf_vertices = fwd['src'][hemi_to_ind[label.hemi]]['vertno'] restrict_verts = np.intersect1d(surf_vertices, label.vertices) com = labels[i].center_of_mass(subject='sample', subjects_dir=subjects_dir, restrict_vertices=restrict_verts, surf='white') # Convert the center of vertex index from surface vertex list to Label's # vertex list. cent_idx = np.where(label.vertices == com)[0][0] # Create a mask with 1 at center vertex and zeros elsewhere. labels[i].values.fill(0.) labels[i].values[cent_idx] = 1. """ Explanation: Find the center vertices in source space of each label We want the known signal in each label to only be active at the center. We create a mask for each label that is 1 at the center vertex and 0 at all other vertices in the label. This mask is then used when simulating source-space data. End of explanation """ stc_gen = simulate_stc(fwd['src'], labels, signal, times[0], dt, value_fun=lambda x: x) """ Explanation: Create source-space data with known signals Put known signals onto surface vertices using the array of signals and the label masks (stored in labels[i].values). End of explanation """ kwargs = dict(subjects_dir=subjects_dir, hemi='split', views=['lat', 'med'], smoothing_steps=4, time_unit='s', initial_time=0.05) clim = dict(kind='value', pos_lims=[1e-9, 1e-8, 1e-7]) brain_gen = stc_gen.plot(clim=clim, **kwargs) """ Explanation: Plot original signals Note that the original signals are highly concentrated (point) sources. End of explanation """ evoked_gen = simulate_evoked(fwd, stc_gen, evoked.info, cov, evoked_snr, tmin=0., tmax=1., random_state=seed) # Map the simulated sensor-space data to source-space using the inverse # operator. stc_inv = apply_inverse(evoked_gen, inv_op, lambda2, method=method) """ Explanation: Simulate sensor-space signals Use the forward solution and add Gaussian noise to simulate sensor-space (evoked) data from the known source-space signals. The amount of noise is controlled by evoked_snr (higher values imply less noise). End of explanation """ brain_inv = stc_inv.plot(**kwargs) """ Explanation: Plot the point-spread of corrupted signal Notice that after applying the forward- and inverse-operators to the known point sources that the point sources have spread across the source-space. This spread is due to the minimum norm solution so that the signal leaks to nearby vertices with similar orientations so that signal ends up crossing the sulci and gyri. End of explanation """
ebmdatalab/openprescribing
notebooks/measure-calculations.ipynb
mit
import pandas as pd import requests """ Explanation: Measure calculations This notebook describes how we perform measure calculations. A measure is the compuation of a ratio between two values (a numerator and a denominator). For instance: The proportion of prescribing (either items or quantity) for a chemical that is not prescribed generically (eg Desogestrel prescribed as a branded product) The amount of prescribing per population (eg High dose opioids per 1000 patients) Measures are computed monthly for each practice, and are also aggregated at CCG and national level, and we call the results of the computations "measure values". For each month, we compute the deciles in the distribution of measure values for practices and CCGs. Certain measures are identified as cost-saving. For these measures, we want to know how much a practice or CCG would have saved if its prescribing had been in line with the practice or CCG at the 10th percentile. For the measures on the website, these calculations are done by performing a series of queries against data in BigQuery. The code is here, and some of the queries are quite gnarly. (Note: In the OpenPrescribing source, we store measure values for practices and CCGs in MeasureValue objects, and national measure values in MeasureGlobal objects. Deciles for practices and CCGs are also stored in MeasureGlobal objects. Cost-saving calculations are stored in both kinds of objects.) This notebook works through these calculations for the Cerazette/Desogestrel measure using one month of relevant prescribing data, using Pandas. The OpenPrescribing implementation metadata for the measure is here. Note that the measure value is computed as the ratio of the quantity of prescriptions for presentations whose BNF code starts with 0703021Q0B (ie branded prescriptions for Desogestrel) to the quantity of prescriptions for presentations whose BNF code starts with 0703021Q0 (ie all prescriptions for Desogestrel). Also note that the is_cost_based and low_is_good fields are true. Setup We need pandas for the computation, and requests to validate the computation against the OpenPrescribing implementation, via the OpenPrescribing API. End of explanation """ sql = ''' SELECT prescriptions.pct AS ccg, prescriptions.practice, prescriptions.bnf_code, prescriptions.bnf_name, prescriptions.quantity, prescriptions.actual_cost AS cost FROM hscic.normalised_prescribing_standard AS prescriptions INNER JOIN hscic.practices ON prescriptions.practice = practices.code WHERE prescriptions.month = TIMESTAMP('2018-08-01') AND prescriptions.bnf_code LIKE '0703021Q0%' AND practices.setting = 4 ''' prescriptions = pd.read_gbq(sql, 'ebmdatalab', dialect='standard') prescriptions.head() """ Explanation: We can get the prescribing data from BigQuery. We're only interested in prescribing from GPs. End of explanation """ numerators = prescriptions[prescriptions['bnf_code'].str.startswith('0703021Q0B')] denominators = prescriptions[prescriptions['bnf_code'].str.startswith('0703021Q0')] """ Explanation: We filter prescribing to find the prescriptions that contribute to the measure's numerator (that is, prescriptions for branded Desogestrel), and the prescriptions that contribute to the measure's denominator (that is, all prescriptions for Desogestrel). End of explanation """ numerators[numerators['practice'] == 'A81001'] denominators[denominators['practice'] == 'A81001'] """ Explanation: We can look at the numerators and deonominators for one particular practice. End of explanation """ sql = 'SELECT code, name, ccg_id AS ccg FROM hscic.practices WHERE setting = 4 ORDER BY code' practices = pd.read_gbq(sql, 'ebmdatalab', dialect='standard').set_index('code') practices.head() """ Explanation: Note the branded prescriptions (Cerelle, Cerazette, Zelleta) are present in both the numerator and the denominator. Generic prescriptions are only present in the denominator. Practices We'll start with the calculations for practices. Not every practice will have prescribed Desogestrel in January 2018, so we also want a list of all practices. End of explanation """ practices['quantity_total'] = denominators.groupby('practice')['quantity'].sum() practices['cost_total'] = denominators.groupby('practice')['cost'].sum() practices['quantity_branded'] = numerators.groupby('practice')['quantity'].sum() practices['cost_branded'] = numerators.groupby('practice')['cost'].sum() # Practices with no prescribing will have NaN values for the new columns. This # also means that the new columns will have dtypes of float64, but quantities # should always be ints. practices = practices.fillna(0) practices['quantity_total'] = practices['quantity_total'].astype('int') practices['quantity_branded'] = practices['quantity_branded'].astype('int') practices['quantity_generic'] = practices['quantity_total'] - practices['quantity_branded'] practices['cost_generic'] = practices['cost_total'] - practices['cost_branded'] practices.head() """ Explanation: practices is a DataFrame indexed by practice code. We will add columns to practices as we compute the measure values, percentiles, and cost savings. For each practice, we want to know the total quantity and total cost for Desogestrel prescriptions, as well as the quantity and cost for branded and for generic prescriptions. We can get the total quantity and cost from the denominators, the quantity and cost of branded prescriptions from the numerators, and the quantity and cost of generic prescriptions by subtracting one from the other. End of explanation """ practices['quantity_ratio'] = practices['quantity_branded'] / practices['quantity_total'] practices.head() """ Explanation: The measure value for this measure is the ratio of the quantity of branded prescriptions to the quantity of total prescriptions. End of explanation """ # In order to match the percentiles calculated by the OpenPrescribing # implementation (via BigQuery) we need to adjust the results of .rank() to # ignore any NaNs. # # I can't see why this isn't the same as: # # practices['quantity_ratio'].dropna().rank(method='min', pct=True) * 100 # # But it's not, quite. # # Thanks Dave for working out what to do here! ranks = practices['quantity_ratio'].rank(method='min') num_non_nans = practices['quantity_ratio'].count() practices['quantity_ratio_percentile'] = (ranks - 1) / ((num_non_nans - 1) / 100) practices.head() """ Explanation: Note the quantity_ratio for a practice with no prescribing is NaN. The OpenPrescribing implementation stores such values as database NULLs, or Python Nones. We can compute each practice's percentile, according to their quantity_ratio. End of explanation """ practice_quantity_ratio_10 = practices['quantity_ratio'].quantile(0.1) practice_quantity_ratio_10 """ Explanation: We can compute the value of the ratio of the practice at the 10th percentile: End of explanation """ practices['unit_cost_branded'] = practices['cost_branded'] / practices['quantity_branded'] practices['unit_cost_generic'] = practices['cost_generic'] / practices['quantity_generic'] practices[['name', 'unit_cost_branded', 'unit_cost_generic']].head() """ Explanation: That is, for the practice at the 10th percentile, the ratio of the quantity of branded prescriptions to total prescriptions is 0.0172. To find out the how much a practice would have saved if its prescribing had matched that of the practice at the 10th percentile, we first need to compute the unit cost of branded and generic prescriptions. End of explanation """ global_unit_cost_branded = practices['cost_branded'].sum() / practices['quantity_branded'].sum() global_unit_cost_generic = practices['cost_generic'].sum() / practices['quantity_generic'].sum() global_unit_cost_branded, global_unit_cost_generic practices['unit_cost_branded'] = practices['unit_cost_branded'].fillna(global_unit_cost_branded) practices['unit_cost_generic'] = practices['unit_cost_generic'].fillna(global_unit_cost_generic) practices[['name', 'unit_cost_branded', 'unit_cost_generic']].head() """ Explanation: When a practice hasn't prescribed either branded or generic or both, we use global values. End of explanation """ practices['quantity_branded_10'] = practices['quantity_total'] * practice_quantity_ratio_10 practices['quantity_generic_10'] = practices['quantity_total'] - practices['quantity_branded_10'] practices[['name', 'quantity_branded', 'quantity_branded_10', 'quantity_generic', 'quantity_generic_10']].head() """ Explanation: We also need the quantity of branded and generic prescriptions that would have been prescribed had its prescribing matched that of the practice at the 10th percentile, assuming the total prescribing remains the same. End of explanation """ practices['target_cost_10'] = practices['unit_cost_branded'] * practices['quantity_branded_10'] + practices['unit_cost_generic'] * practices['quantity_generic_10'] practices['cost_saving_10'] = practices['cost_total'] - practices['target_cost_10'] practices.head() """ Explanation: We can then work out a target cost for each practice, and the amount that would be saved if the practice could make that target. End of explanation """ practices.sort_values('cost_saving_10').head()[['name', 'cost_saving_10']] """ Explanation: Here are the practices that would save the least. End of explanation """ practices.sort_values('cost_saving_10').tail()[['name', 'cost_saving_10']] """ Explanation: And the practices that would save the most. End of explanation """ def get_practice_data_from_api(practice_id): url = 'https://openprescribing.net/api/1.0/measure_by_practice/' params = { 'format': 'json', 'measure': 'desogestrel', 'org': practice_id, } rsp = requests.get(url, params) for record in rsp.json()['measures'][0]['data']: if record['date'] == '2018-08-01': return record assert False for partition in [ practices[practices['quantity_total'] == 0], # no prescribing practices[(practices['quantity_total'] > 0) & (practices['quantity_generic'] == 0)], # all branded practices[(practices['quantity_total'] > 0) & (practices['quantity_branded'] == 0)], # all generic practices[(practices['quantity_branded'] > 0) & (practices['quantity_generic'] > 0)], # a mixture ]: practice_id = partition.sample().index[0] data = get_practice_data_from_api(practice_id) practice = practices.loc[practice_id] print('-' * 80) print(practice) print(data) assert data['numerator'] == practice['quantity_branded'] assert data['denominator'] == practice['quantity_total'] if data['percentile'] is not None: assert abs(data['percentile'] - practice['quantity_ratio_percentile']) < 0.001 assert abs(data['cost_savings']['10'] - practice['cost_saving_10']) < 0.001 """ Explanation: We can verify our calculations by checking against data returned by the API, for each of the following kinds of practice: No prescribing All prescribing is branded All prescribing is generic Prescribing is mixture of branded and generic End of explanation """ sql = ''' SELECT ccgs.code, ccgs.name FROM hscic.ccgs INNER JOIN ( SELECT DISTINCT(ccg_id) FROM hscic.practices WHERE practices.setting = 4 AND practices.status_code = 'A' ) AS practices ON ccgs.code = practices.ccg_id WHERE ccgs.org_type = 'CCG' ORDER BY ccgs.code ''' ccgs = pd.read_gbq(sql, 'ebmdatalab', dialect='standard').set_index('code') ccgs.head() ccgs['quantity_total'] = denominators.groupby('ccg')['quantity'].sum() ccgs['cost_total'] = denominators.groupby('ccg')['cost'].sum() ccgs['quantity_branded'] = numerators.groupby('ccg')['quantity'].sum() ccgs['cost_branded'] = numerators.groupby('ccg')['cost'].sum() ccgs = ccgs.fillna(0) ccgs['quantity_total'] = ccgs['quantity_total'].astype('int') ccgs['quantity_branded'] = ccgs['quantity_branded'].astype('int') ccgs['quantity_generic'] = ccgs['quantity_total'] - ccgs['quantity_branded'] ccgs['cost_generic'] = ccgs['cost_total'] - ccgs['cost_branded'] ccgs['quantity_ratio'] = ccgs['quantity_branded'] / ccgs['quantity_total'] ranks = ccgs['quantity_ratio'].rank(method='min') num_non_nans = ccgs['quantity_ratio'].count() ccgs['quantity_ratio_percentile'] = (ranks - 1) / ((num_non_nans - 1) / 100) ccgs.head() ccg_quantity_ratio_10 = ccgs['quantity_ratio'].quantile(0.1) ccg_quantity_ratio_10 ccgs['unit_cost_branded'] = ccgs['cost_branded'] / ccgs['quantity_branded'] ccgs['unit_cost_generic'] = ccgs['cost_generic'] / ccgs['quantity_generic'] ccgs[['name', 'unit_cost_branded', 'unit_cost_generic']].head() global_unit_cost_branded = ccgs['cost_branded'].sum() / ccgs['quantity_branded'].sum() global_unit_cost_generic = ccgs['cost_generic'].sum() / ccgs['quantity_generic'].sum() global_unit_cost_branded, global_unit_cost_generic ccgs['unit_cost_branded'] = ccgs['unit_cost_branded'].fillna(global_unit_cost_branded) ccgs['unit_cost_generic'] = ccgs['unit_cost_generic'].fillna(global_unit_cost_generic) ccgs[['name', 'unit_cost_branded', 'unit_cost_generic']].head() ccgs['quantity_branded_10'] = ccgs['quantity_total'] * ccg_quantity_ratio_10 ccgs['quantity_generic_10'] = ccgs['quantity_total'] - ccgs['quantity_branded_10'] ccgs[['name', 'quantity_branded', 'quantity_branded_10', 'quantity_generic', 'quantity_generic_10']].head() ccgs['target_cost_10'] = ccgs['unit_cost_branded'] * ccgs['quantity_branded_10'] + ccgs['unit_cost_generic'] * ccgs['quantity_generic_10'] ccgs['cost_saving_10'] = ccgs['cost_total'] - ccgs['target_cost_10'] ccgs.head() """ Explanation: CCGs We'll move onto the calculations for CCGs. The calculations are very similar to those for practices. We're interested in CCGs with active GPs. End of explanation """ ccgs.sort_values('cost_saving_10').head()[['name', 'cost_saving_10']] """ Explanation: Here are the CCGs that would save the least. End of explanation """ ccgs.sort_values('cost_saving_10').tail()[['name', 'cost_saving_10']] """ Explanation: And the CCGs that would save the most. End of explanation """ def get_ccg_data_from_api(ccg_id): url = 'https://openprescribing.net/api/1.0/measure_by_ccg/' params = { 'format': 'json', 'measure': 'desogestrel', 'org': ccg_id, } rsp = requests.get(url, params) for record in rsp.json()['measures'][0]['data']: if record['date'] == '2018-08-01': return record assert False for ccg_id, ccg in ccgs.sample(4).iterrows(): data = get_ccg_data_from_api(ccg_id) print('-' * 80) print(ccg) assert data['numerator'] == ccg['quantity_branded'] assert data['denominator'] == ccg['quantity_total'] assert abs(data['percentile'] - ccg['quantity_ratio_percentile']) < 0.001 assert abs(data['cost_savings']['10'] - ccg['cost_saving_10']) < 0.001 """ Explanation: Again, we can verify our calculations by checking against data returned by the API. End of explanation """
mne-tools/mne-tools.github.io
dev/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb
bsd-3-clause
# Authors: Denis Engemann <denis.engemann@gmail.com> # Luke Bloy <luke.bloy@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause import os.path as op from mne.filter import next_fast_len import mne print(__doc__) data_path = mne.datasets.opm.data_path() subject = 'OPM_sample' subjects_dir = op.join(data_path, 'subjects') bem_dir = op.join(subjects_dir, subject, 'bem') bem_fname = op.join(subjects_dir, subject, 'bem', subject + '-5120-5120-5120-bem-sol.fif') src_fname = op.join(bem_dir, '%s-oct6-src.fif' % subject) vv_fname = data_path / 'MEG' / 'SQUID' / 'SQUID_resting_state.fif' vv_erm_fname = data_path / 'MEG' / 'SQUID' / 'SQUID_empty_room.fif' vv_trans_fname = data_path / 'MEG' / 'SQUID' / 'SQUID-trans.fif' opm_fname = data_path / 'MEG' / 'OPM' / 'OPM_resting_state_raw.fif' opm_erm_fname = data_path / 'MEG' / 'OPM' / 'OPM_empty_room_raw.fif' opm_trans = mne.transforms.Transform('head', 'mri') # use identity transform opm_coil_def_fname = op.join(data_path, 'MEG', 'OPM', 'coil_def.dat') """ Explanation: Compute source power spectral density (PSD) of VectorView and OPM data Here we compute the resting state from raw for data recorded using a Neuromag VectorView system and a custom OPM system. The pipeline is meant to mostly follow the Brainstorm :footcite:TadelEtAl2011 OMEGA resting tutorial pipeline_. The steps we use are: Filtering: downsample heavily. Artifact detection: use SSP for EOG and ECG. Source localization: dSPM, depth weighting, cortically constrained. Frequency: power spectral density (Welch), 4 sec window, 50% overlap. Standardize: normalize by relative power for each source. Preprocessing End of explanation """ raws = dict() raw_erms = dict() new_sfreq = 60. # Nyquist frequency (30 Hz) < line noise freq (50 Hz) raws['vv'] = mne.io.read_raw_fif(vv_fname, verbose='error') # ignore naming raws['vv'].load_data().resample(new_sfreq) raws['vv'].info['bads'] = ['MEG2233', 'MEG1842'] raw_erms['vv'] = mne.io.read_raw_fif(vv_erm_fname, verbose='error') raw_erms['vv'].load_data().resample(new_sfreq) raw_erms['vv'].info['bads'] = ['MEG2233', 'MEG1842'] raws['opm'] = mne.io.read_raw_fif(opm_fname) raws['opm'].load_data().resample(new_sfreq) raw_erms['opm'] = mne.io.read_raw_fif(opm_erm_fname) raw_erms['opm'].load_data().resample(new_sfreq) # Make sure our assumptions later hold assert raws['opm'].info['sfreq'] == raws['vv'].info['sfreq'] """ Explanation: Load data, resample. We will store the raw objects in dicts with entries "vv" and "opm" to simplify housekeeping and simplify looping later. End of explanation """ titles = dict(vv='VectorView', opm='OPM') kinds = ('vv', 'opm') n_fft = next_fast_len(int(round(4 * new_sfreq))) print('Using n_fft=%d (%0.1f sec)' % (n_fft, n_fft / raws['vv'].info['sfreq'])) for kind in kinds: fig = raws[kind].plot_psd(n_fft=n_fft, proj=True) fig.suptitle(titles[kind]) fig.subplots_adjust(0.1, 0.1, 0.95, 0.85) """ Explanation: Explore data End of explanation """ # Here we use a reduced size source space (oct5) just for speed src = mne.setup_source_space( subject, 'oct5', add_dist=False, subjects_dir=subjects_dir) # This line removes source-to-source distances that we will not need. # We only do it here to save a bit of memory, in general this is not required. del src[0]['dist'], src[1]['dist'] bem = mne.read_bem_solution(bem_fname) # For speed, let's just use a 1-layer BEM bem = mne.make_bem_solution(bem['surfs'][-1:]) fwd = dict() # check alignment and generate forward for VectorView kwargs = dict(azimuth=0, elevation=90, distance=0.6, focalpoint=(0., 0., 0.)) fig = mne.viz.plot_alignment( raws['vv'].info, trans=vv_trans_fname, subject=subject, subjects_dir=subjects_dir, dig=True, coord_frame='mri', surfaces=('head', 'white')) mne.viz.set_3d_view(figure=fig, **kwargs) fwd['vv'] = mne.make_forward_solution( raws['vv'].info, vv_trans_fname, src, bem, eeg=False, verbose=True) """ Explanation: Alignment and forward End of explanation """ with mne.use_coil_def(opm_coil_def_fname): fig = mne.viz.plot_alignment( raws['opm'].info, trans=opm_trans, subject=subject, subjects_dir=subjects_dir, dig=False, coord_frame='mri', surfaces=('head', 'white')) mne.viz.set_3d_view(figure=fig, **kwargs) fwd['opm'] = mne.make_forward_solution( raws['opm'].info, opm_trans, src, bem, eeg=False, verbose=True) del src, bem """ Explanation: And for OPM: End of explanation """ freq_bands = dict(alpha=(8, 12), beta=(15, 29)) topos = dict(vv=dict(), opm=dict()) stcs = dict(vv=dict(), opm=dict()) snr = 3. lambda2 = 1. / snr ** 2 for kind in kinds: noise_cov = mne.compute_raw_covariance(raw_erms[kind]) inverse_operator = mne.minimum_norm.make_inverse_operator( raws[kind].info, forward=fwd[kind], noise_cov=noise_cov, verbose=True) stc_psd, sensor_psd = mne.minimum_norm.compute_source_psd( raws[kind], inverse_operator, lambda2=lambda2, n_fft=n_fft, dB=False, return_sensor=True, verbose=True) topo_norm = sensor_psd.data.sum(axis=1, keepdims=True) stc_norm = stc_psd.sum() # same operation on MNE object, sum across freqs # Normalize each source point by the total power across freqs for band, limits in freq_bands.items(): data = sensor_psd.copy().crop(*limits).data.sum(axis=1, keepdims=True) topos[kind][band] = mne.EvokedArray( 100 * data / topo_norm, sensor_psd.info) stcs[kind][band] = \ 100 * stc_psd.copy().crop(*limits).sum() / stc_norm.data del inverse_operator del fwd, raws, raw_erms """ Explanation: Compute and apply inverse to PSD estimated using multitaper + Welch. Group into frequency bands, then normalize each source point and sensor independently. This makes the value of each sensor point and source location in each frequency band the percentage of the PSD accounted for by that band. End of explanation """ def plot_band(kind, band): """Plot activity within a frequency band on the subject's brain.""" title = "%s %s\n(%d-%d Hz)" % ((titles[kind], band,) + freq_bands[band]) topos[kind][band].plot_topomap( times=0., scalings=1., cbar_fmt='%0.1f', vmin=0, cmap='inferno', time_format=title) brain = stcs[kind][band].plot( subject=subject, subjects_dir=subjects_dir, views='cau', hemi='both', time_label=title, title=title, colormap='inferno', time_viewer=False, show_traces=False, clim=dict(kind='percent', lims=(70, 85, 99)), smoothing_steps=10) brain.show_view(azimuth=0, elevation=0, roll=0) return fig, brain fig_alpha, brain_alpha = plot_band('vv', 'alpha') """ Explanation: Now we can make some plots of each frequency band. Note that the OPM head coverage is only over right motor cortex, so only localization of beta is likely to be worthwhile. Alpha End of explanation """ fig_beta, brain_beta = plot_band('vv', 'beta') """ Explanation: Beta Here we also show OPM data, which shows a profile similar to the VectorView data beneath the sensors. VectorView first: End of explanation """ fig_beta_opm, brain_beta_opm = plot_band('opm', 'beta') """ Explanation: Then OPM: End of explanation """
AbnerZheng/Titanic_Kaggle
scikit-learn/03_getting_started_with_iris.ipynb
mit
from IPython.display import HTML HTML('<iframe src=http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data width=300 height=200></iframe>') """ Explanation: Getting started in scikit-learn with the famous iris dataset From the video series: Introduction to machine learning with scikit-learn Agenda What is the famous iris dataset, and how does it relate to machine learning? How do we load the iris dataset into scikit-learn? How do we describe a dataset using machine learning terminology? What are scikit-learn's four key requirements for working with data? Introducing the iris dataset 50 samples of 3 different species of iris (150 samples total) Measurements: sepal length, sepal width, petal length, petal width End of explanation """ # import load_iris function from datasets module from sklearn.datasets import load_iris # save "bunch" object containing iris dataset and its attributes iris = load_iris() type(iris) # print the iris data print iris.data """ Explanation: Machine learning on the iris dataset Framed as a supervised learning problem: Predict the species of an iris using the measurements Famous dataset for machine learning because prediction is easy Learn more about the iris dataset: UCI Machine Learning Repository Loading the iris dataset into scikit-learn End of explanation """ # print the names of the four features print iris.feature_names # print integers representing the species of each observation print iris.target # print the encoding scheme for species: 0 = setosa, 1 = versicolor, 2 = virginica print iris.target_names """ Explanation: Machine learning terminology Each row is an observation (also known as: sample, example, instance, record) Each column is a feature (also known as: predictor, attribute, independent variable, input, regressor, covariate) End of explanation """ # check the types of the features and response print type(iris.data) print type(iris.target) # check the shape of the features (first dimension = number of observations, second dimensions = number of features) print iris.data.shape # check the shape of the response (single dimension matching the number of observations) print iris.target.shape # store feature matrix in "X" X = iris.data # store response vector in "y" y = iris.target """ Explanation: Each value we are predicting is the response (also known as: target, outcome, label, dependent variable) Classification is supervised learning in which the response is categorical Regression is supervised learning in which the response is ordered and continuous Requirements for working with data in scikit-learn Features and response are separate objects Features and response should be numeric Features and response should be NumPy arrays Features and response should have specific shapes End of explanation """ from IPython.core.display import HTML def css_styling(): styles = open("styles/custom.css", "r").read() return HTML(styles) css_styling() """ Explanation: Resources scikit-learn documentation: Dataset loading utilities Jake VanderPlas: Fast Numerical Computing with NumPy (slides, video) Scott Shell: An Introduction to NumPy (PDF) Comments or Questions? Email: &#107;&#101;&#118;&#105;&#110;&#64;&#100;&#97;&#116;&#97;&#115;&#99;&#104;&#111;&#111;&#108;&#46;&#105;&#111; Website: http://dataschool.io Twitter: @justmarkham End of explanation """
rnder/data-science-from-scratch
notebook/ch16_logistic_regression.ipynb
unlicense
from collections import Counter from functools import partial, reduce from linear_algebra import dot, vector_add from gradient_descent import maximize_stochastic, maximize_batch from working_with_data import rescale from machine_learning import train_test_split from multiple_regression import estimate_beta, predict import math, random import numpy as np import matplotlib.pyplot as plt def logistic(x): return 1.0 / (1 + math.exp(-x)) def logistic_prime(x): return logistic(x) * (1 - logistic(x)) def logistic_log_likelihood_i(x_i, y_i, beta): if y_i == 1: return math.log(logistic(dot(x_i, beta))) else: return math.log(1 - logistic(dot(x_i, beta))) def logistic_log_likelihood(x, y, beta): return sum(logistic_log_likelihood_i(x_i, y_i, beta) for x_i, y_i in zip(x, y)) def logistic_log_partial_ij(x_i, y_i, beta, j): """here i is the index of the data point, j the index of the derivative""" return (y_i - logistic(dot(x_i, beta))) * x_i[j] def logistic_log_gradient_i(x_i, y_i, beta): """the gradient of the log likelihood corresponding to the i-th data point""" return [logistic_log_partial_ij(x_i, y_i, beta, j) for j, _ in enumerate(beta)] def logistic_log_gradient(x, y, beta): return reduce(vector_add, [logistic_log_gradient_i(x_i, y_i, beta) for x_i, y_i in zip(x,y)]) # [experience, salary, paid_account] data = [(0.7,48000,1),(1.9,48000,0),(2.5,60000,1),(4.2,63000,0),(6,76000,0),(6.5,69000,0),(7.5,76000,0),(8.1,88000,0),(8.7,83000,1),(10,83000,1),(0.8,43000,0),(1.8,60000,0),(10,79000,1),(6.1,76000,0),(1.4,50000,0),(9.1,92000,0),(5.8,75000,0),(5.2,69000,0),(1,56000,0),(6,67000,0),(4.9,74000,0),(6.4,63000,1),(6.2,82000,0),(3.3,58000,0),(9.3,90000,1),(5.5,57000,1),(9.1,102000,0),(2.4,54000,0),(8.2,65000,1),(5.3,82000,0),(9.8,107000,0),(1.8,64000,0),(0.6,46000,1),(0.8,48000,0),(8.6,84000,1),(0.6,45000,0),(0.5,30000,1),(7.3,89000,0),(2.5,48000,1),(5.6,76000,0),(7.4,77000,0),(2.7,56000,0),(0.7,48000,0),(1.2,42000,0),(0.2,32000,1),(4.7,56000,1),(2.8,44000,1),(7.6,78000,0),(1.1,63000,0),(8,79000,1),(2.7,56000,0),(6,52000,1),(4.6,56000,0),(2.5,51000,0),(5.7,71000,0),(2.9,65000,0),(1.1,33000,1),(3,62000,0),(4,71000,0),(2.4,61000,0),(7.5,75000,0),(9.7,81000,1),(3.2,62000,0),(7.9,88000,0),(4.7,44000,1),(2.5,55000,0),(1.6,41000,0),(6.7,64000,1),(6.9,66000,1),(7.9,78000,1),(8.1,102000,0),(5.3,48000,1),(8.5,66000,1),(0.2,56000,0),(6,69000,0),(7.5,77000,0),(8,86000,0),(4.4,68000,0),(4.9,75000,0),(1.5,60000,0),(2.2,50000,0),(3.4,49000,1),(4.2,70000,0),(7.7,98000,0),(8.2,85000,0),(5.4,88000,0),(0.1,46000,0),(1.5,37000,0),(6.3,86000,0),(3.7,57000,0),(8.4,85000,0),(2,42000,0),(5.8,69000,1),(2.7,64000,0),(3.1,63000,0),(1.9,48000,0),(10,72000,1),(0.2,45000,0),(8.6,95000,0),(1.5,64000,0),(9.8,95000,0),(5.3,65000,0),(7.5,80000,0),(9.9,91000,0),(9.7,50000,1),(2.8,68000,0),(3.6,58000,0),(3.9,74000,0),(4.4,76000,0),(2.5,49000,0),(7.2,81000,0),(5.2,60000,1),(2.4,62000,0),(8.9,94000,0),(2.4,63000,0),(6.8,69000,1),(6.5,77000,0),(7,86000,0),(9.4,94000,0),(7.8,72000,1),(0.2,53000,0),(10,97000,0),(5.5,65000,0),(7.7,71000,1),(8.1,66000,1),(9.8,91000,0),(8,84000,0),(2.7,55000,0),(2.8,62000,0),(9.4,79000,0),(2.5,57000,0),(7.4,70000,1),(2.1,47000,0),(5.3,62000,1),(6.3,79000,0),(6.8,58000,1),(5.7,80000,0),(2.2,61000,0),(4.8,62000,0),(3.7,64000,0),(4.1,85000,0),(2.3,51000,0),(3.5,58000,0),(0.9,43000,0),(0.9,54000,0),(4.5,74000,0),(6.5,55000,1),(4.1,41000,1),(7.1,73000,0),(1.1,66000,0),(9.1,81000,1),(8,69000,1),(7.3,72000,1),(3.3,50000,0),(3.9,58000,0),(2.6,49000,0),(1.6,78000,0),(0.7,56000,0),(2.1,36000,1),(7.5,90000,0),(4.8,59000,1),(8.9,95000,0),(6.2,72000,0),(6.3,63000,0),(9.1,100000,0),(7.3,61000,1),(5.6,74000,0),(0.5,66000,0),(1.1,59000,0),(5.1,61000,0),(6.2,70000,0),(6.6,56000,1),(6.3,76000,0),(6.5,78000,0),(5.1,59000,0),(9.5,74000,1),(4.5,64000,0),(2,54000,0),(1,52000,0),(4,69000,0),(6.5,76000,0),(3,60000,0),(4.5,63000,0),(7.8,70000,0),(3.9,60000,1),(0.8,51000,0),(4.2,78000,0),(1.1,54000,0),(6.2,60000,0),(2.9,59000,0),(2.1,52000,0),(8.2,87000,0),(4.8,73000,0),(2.2,42000,1),(9.1,98000,0),(6.5,84000,0),(6.9,73000,0),(5.1,72000,0),(9.1,69000,1),(9.8,79000,1),] data = list(map(list, data)) # change tuples to lists x = [[1] + row[:2] for row in data] # each element is [1, experience, salary] y = [row[2] for row in data] # each element is paid_account """ Explanation: Ch.16 - Logistic Regression End of explanation """ unpaid_salaries = [row[0] for row in data if row[2] == 0] unpaid_users = [row[1] for row in data if row[2] == 0] paid_salaries = [row[0] for row in data if row[2] == 1] paid_users = [row[1] for row in data if row[2] == 1] plt.scatter(paid_salaries, paid_users, marker='o', label='paid') plt.scatter(unpaid_salaries, unpaid_users, marker='+', label='unpaid') plt.title("Paid and Unpaid Users") plt.xlabel("years experience") plt.ylabel("annual salary") plt.legend(loc=8) plt.show() print("linear regression:") rescaled_x = rescale(x) beta = estimate_beta(rescaled_x, y) # [0.26, 0.43, -0.43] print(beta) predictions = [predict(x_i, beta) for x_i in rescaled_x] plt.scatter(predictions, y) plt.xlabel("predicted") plt.ylabel("actual") plt.show() sig_x = np.arange(-10., 10., 0.2) sig_y = [logistic(_) for _ in sig_x] plt.plot(sig_x, sig_y) plt.margins(0, 0.1) plt.title("logistic function") plt.show() """ Explanation: $paid acount = \beta_0+\beta_1 experience+\beta_2 salary+\epsilon$ End of explanation """ print("logistic regression:") random.seed(0) x_train, x_test, y_train, y_test = train_test_split(rescaled_x, y, 0.33) # want to maximize log likelihood on the training data fn = partial(logistic_log_likelihood, x_train, y_train) gradient_fn = partial(logistic_log_gradient, x_train, y_train) # pick a random starting point beta_0 = [1, 1, 1] # beta_0 = [random.random() for _ in range(3)] # and maximize using gradient descent beta_hat = maximize_batch(fn, gradient_fn, beta_0) print("beta_batch", beta_hat) # beta_0 = [1, 1, 1] beta_hat = maximize_stochastic(logistic_log_likelihood_i, logistic_log_gradient_i, x_train, y_train, beta_0) print("beta stochastic", beta_hat) """ Explanation: $ logistic(x) = \frac{1.0} {1+e^-x}\ p(y_i|x_i\beta) = f(x_i\beta)^{y_i}(1-f(x_i\beta))^{1-y_i} \ log L(\beta|x_iy_i) = y_i log f(x_i\beta) + (1 - y_i) log(1 - f(x_i\beta)) $ End of explanation """ true_positives = true_negatives = false_positives = false_negatives = 0 for x_i, y_i in zip(x_test, y_test): predict = logistic(dot(beta_hat, x_i)) if y_i == 1 and predict >= 0.5: # TP: paid and we predict paid true_positives += 1 elif y_i == 1: # FN: paid and we predict unpaid false_negatives += 1 elif y_i == 0 and predict >= 0.5: # FP: unpaid and we predict paid false_positives += 1 else: # TN: unpaid and we predict unpaid true_negatives += 1 precision = true_positives / (true_positives + false_positives) recall = true_positives / (true_positives + false_negatives) print("precision", precision) print("recall", recall) predictions = [logistic(dot(beta_hat, x_i)) for x_i in x_test] plt.scatter(predictions, y_test) plt.xlabel("predicted probability") plt.ylabel("actual outcome") plt.title("Logistic Regression Predicted vs. Actual") plt.show() """ Explanation: Confusion Matrix $Accuracy(정확도) = \frac{TP+TN} {TP+TN+FN+FP} \ Precision(정밀도) = \frac{TP} {TP+FP} \ Recall(재현율) = \frac{TP} {TP+FN} \ F1 Score = \frac{2 * Recall * Precision} {Recall + Precision}$ End of explanation """ plt.scatter(paid_salaries, paid_users, marker='o', label='paid') plt.scatter(unpaid_salaries, unpaid_users, marker='+', label='unpaid') plt.title("Logistic Regression Decision Boundary") plt.xlabel("years experience") plt.ylabel("annual salary") plt.legend(loc=8) plt.show() """ Explanation: Decision Boundary https://www.coursera.org/learn/machine-learning/lecture/WuL1H/decision-boundary End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/bnu/cmip6/models/bnu-esm-1-1/toplevel.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bnu', 'bnu-esm-1-1', 'toplevel') """ Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: BNU Source ID: BNU-ESM-1-1 Sub-Topics: Radiative Forcings. Properties: 85 (42 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:53:41 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Flux Correction 3. Key Properties --&gt; Genealogy 4. Key Properties --&gt; Software Properties 5. Key Properties --&gt; Coupling 6. Key Properties --&gt; Tuning Applied 7. Key Properties --&gt; Conservation --&gt; Heat 8. Key Properties --&gt; Conservation --&gt; Fresh Water 9. Key Properties --&gt; Conservation --&gt; Salt 10. Key Properties --&gt; Conservation --&gt; Momentum 11. Radiative Forcings 12. Radiative Forcings --&gt; Greenhouse Gases --&gt; CO2 13. Radiative Forcings --&gt; Greenhouse Gases --&gt; CH4 14. Radiative Forcings --&gt; Greenhouse Gases --&gt; N2O 15. Radiative Forcings --&gt; Greenhouse Gases --&gt; Tropospheric O3 16. Radiative Forcings --&gt; Greenhouse Gases --&gt; Stratospheric O3 17. Radiative Forcings --&gt; Greenhouse Gases --&gt; CFC 18. Radiative Forcings --&gt; Aerosols --&gt; SO4 19. Radiative Forcings --&gt; Aerosols --&gt; Black Carbon 20. Radiative Forcings --&gt; Aerosols --&gt; Organic Carbon 21. Radiative Forcings --&gt; Aerosols --&gt; Nitrate 22. Radiative Forcings --&gt; Aerosols --&gt; Cloud Albedo Effect 23. Radiative Forcings --&gt; Aerosols --&gt; Cloud Lifetime Effect 24. Radiative Forcings --&gt; Aerosols --&gt; Dust 25. Radiative Forcings --&gt; Aerosols --&gt; Tropospheric Volcanic 26. Radiative Forcings --&gt; Aerosols --&gt; Stratospheric Volcanic 27. Radiative Forcings --&gt; Aerosols --&gt; Sea Salt 28. Radiative Forcings --&gt; Other --&gt; Land Use 29. Radiative Forcings --&gt; Other --&gt; Solar 1. Key Properties Key properties of the model 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top level overview of coupled model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of coupled model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.flux_correction.details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Flux Correction Flux correction properties of the model 2.1. Details Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how flux corrections are applied in the model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.genealogy.year_released') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Genealogy Genealogy and history of the model 3.1. Year Released Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Year the model was released End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.genealogy.CMIP3_parent') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.2. CMIP3 Parent Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 CMIP3 parent if any End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.genealogy.CMIP5_parent') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.3. CMIP5 Parent Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 CMIP5 parent if any End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.genealogy.previous_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.4. Previous Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Previously known as End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Software Properties Software properties of model 4.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.software_properties.components_structure') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.4. Components Structure Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe how model realms are structured into independent software components (coupled via a coupler) and internal software components. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.software_properties.coupler') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OASIS" # "OASIS3-MCT" # "ESMF" # "NUOPC" # "Bespoke" # "Unknown" # "None" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 4.5. Coupler Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Overarching coupling framework for model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.coupling.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Key Properties --&gt; Coupling ** 5.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of coupling in the model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.coupling.atmosphere_double_flux') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 5.2. Atmosphere Double Flux Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the atmosphere passing a double flux to the ocean and sea ice (as opposed to a single one)? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.coupling.atmosphere_fluxes_calculation_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Atmosphere grid" # "Ocean grid" # "Specific coupler grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 5.3. Atmosphere Fluxes Calculation Grid Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Where are the air-sea fluxes calculated End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.coupling.atmosphere_relative_winds') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 5.4. Atmosphere Relative Winds Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Are relative or absolute winds used to compute the flux? I.e. do ocean surface currents enter the wind stress calculation? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.tuning_applied.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Key Properties --&gt; Tuning Applied Tuning methodology for model 6.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview description of tuning: explain and motivate the main targets and metrics/diagnostics retained. Document the relative weight given to climate performance metrics/diagnostics versus process oriented metrics/diagnostics, and on the possible conflicts with parameterization level tuning. In particular describe any struggle with a parameter value that required pushing it to its limits to solve a particular model deficiency. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.tuning_applied.global_mean_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.2. Global Mean Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List set of metrics/diagnostics of the global mean state used in tuning model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.tuning_applied.regional_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.3. Regional Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of regional metrics/diagnostics of mean state (e.g THC, AABW, regional means etc) used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.tuning_applied.trend_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.4. Trend Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List observed trend metrics/diagnostics used in tuning model/component (such as 20th century) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.tuning_applied.energy_balance') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.5. Energy Balance Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how energy balance was obtained in the full system: in the various components independently or at the components coupling stage? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.tuning_applied.fresh_water_balance') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.6. Fresh Water Balance Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how fresh_water balance was obtained in the full system: in the various components independently or at the components coupling stage? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.heat.global') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Key Properties --&gt; Conservation --&gt; Heat Global heat convervation properties of the model 7.1. Global Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how heat is conserved globally End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.heat.atmos_ocean_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.2. Atmos Ocean Interface Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how heat is conserved at the atmosphere/ocean coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.heat.atmos_land_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.3. Atmos Land Interface Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how heat is conserved at the atmosphere/land coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.heat.atmos_sea-ice_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.4. Atmos Sea-ice Interface Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how heat is conserved at the atmosphere/sea-ice coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.heat.ocean_seaice_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.5. Ocean Seaice Interface Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how heat is conserved at the ocean/sea-ice coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.heat.land_ocean_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.6. Land Ocean Interface Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how heat is conserved at the land/ocean coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.global') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Key Properties --&gt; Conservation --&gt; Fresh Water Global fresh water convervation properties of the model 8.1. Global Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how fresh_water is conserved globally End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.atmos_ocean_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.2. Atmos Ocean Interface Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how fresh_water is conserved at the atmosphere/ocean coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.atmos_land_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.3. Atmos Land Interface Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how fresh water is conserved at the atmosphere/land coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.atmos_sea-ice_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.4. Atmos Sea-ice Interface Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how fresh water is conserved at the atmosphere/sea-ice coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.ocean_seaice_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.5. Ocean Seaice Interface Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how fresh water is conserved at the ocean/sea-ice coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.runoff') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.6. Runoff Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe how runoff is distributed and conserved End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.iceberg_calving') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.7. Iceberg Calving Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how iceberg calving is modeled and conserved End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.endoreic_basins') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.8. Endoreic Basins Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how endoreic basins (no ocean access) are treated End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.fresh_water.snow_accumulation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.9. Snow Accumulation Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe how snow accumulation over land and over sea-ice is treated End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.salt.ocean_seaice_interface') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Key Properties --&gt; Conservation --&gt; Salt Global salt convervation properties of the model 9.1. Ocean Seaice Interface Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how salt is conserved at the ocean/sea-ice coupling interface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.key_properties.conservation.momentum.details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10. Key Properties --&gt; Conservation --&gt; Momentum Global momentum convervation properties of the model 10.1. Details Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how momentum is conserved in the model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11. Radiative Forcings Radiative forcings of the model for historical and scenario (aka Table 12.1 IPCC AR5) 11.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of radiative forcings (GHG and aerosols) implementation in model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.CO2.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12. Radiative Forcings --&gt; Greenhouse Gases --&gt; CO2 Carbon dioxide forcing 12.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.CO2.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.CH4.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13. Radiative Forcings --&gt; Greenhouse Gases --&gt; CH4 Methane forcing 13.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.CH4.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 13.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.N2O.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 14. Radiative Forcings --&gt; Greenhouse Gases --&gt; N2O Nitrous oxide forcing 14.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.N2O.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 14.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.tropospheric_O3.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15. Radiative Forcings --&gt; Greenhouse Gases --&gt; Tropospheric O3 Troposheric ozone forcing 15.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.tropospheric_O3.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.stratospheric_O3.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16. Radiative Forcings --&gt; Greenhouse Gases --&gt; Stratospheric O3 Stratospheric ozone forcing 16.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.stratospheric_O3.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 16.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.CFC.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17. Radiative Forcings --&gt; Greenhouse Gases --&gt; CFC Ozone-depleting and non-ozone-depleting fluorinated gases forcing 17.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.CFC.equivalence_concentration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "Option 1" # "Option 2" # "Option 3" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.2. Equivalence Concentration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Details of any equivalence concentrations used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.greenhouse_gases.CFC.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.3. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.SO4.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18. Radiative Forcings --&gt; Aerosols --&gt; SO4 SO4 aerosol forcing 18.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.SO4.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 18.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.black_carbon.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 19. Radiative Forcings --&gt; Aerosols --&gt; Black Carbon Black carbon aerosol forcing 19.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.black_carbon.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 19.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.organic_carbon.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 20. Radiative Forcings --&gt; Aerosols --&gt; Organic Carbon Organic carbon aerosol forcing 20.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.organic_carbon.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 20.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.nitrate.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 21. Radiative Forcings --&gt; Aerosols --&gt; Nitrate Nitrate forcing 21.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.nitrate.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 21.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.cloud_albedo_effect.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 22. Radiative Forcings --&gt; Aerosols --&gt; Cloud Albedo Effect Cloud albedo effect forcing (RFaci) 22.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.cloud_albedo_effect.aerosol_effect_on_ice_clouds') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 22.2. Aerosol Effect On Ice Clouds Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Radiative effects of aerosols on ice clouds are represented? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.cloud_albedo_effect.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 22.3. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.cloud_lifetime_effect.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23. Radiative Forcings --&gt; Aerosols --&gt; Cloud Lifetime Effect Cloud lifetime effect forcing (ERFaci) 23.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.cloud_lifetime_effect.aerosol_effect_on_ice_clouds') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 23.2. Aerosol Effect On Ice Clouds Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Radiative effects of aerosols on ice clouds are represented? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.cloud_lifetime_effect.RFaci_from_sulfate_only') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 23.3. RFaci From Sulfate Only Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Radiative forcing from aerosol cloud interactions from sulfate aerosol only? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.cloud_lifetime_effect.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 23.4. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.dust.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 24. Radiative Forcings --&gt; Aerosols --&gt; Dust Dust forcing 24.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.dust.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 24.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.tropospheric_volcanic.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25. Radiative Forcings --&gt; Aerosols --&gt; Tropospheric Volcanic Tropospheric volcanic forcing 25.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.tropospheric_volcanic.historical_explosive_volcanic_aerosol_implementation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Type A" # "Type B" # "Type C" # "Type D" # "Type E" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25.2. Historical Explosive Volcanic Aerosol Implementation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How explosive volcanic aerosol is implemented in historical simulations End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.tropospheric_volcanic.future_explosive_volcanic_aerosol_implementation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Type A" # "Type B" # "Type C" # "Type D" # "Type E" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25.3. Future Explosive Volcanic Aerosol Implementation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How explosive volcanic aerosol is implemented in future simulations End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.tropospheric_volcanic.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 25.4. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.stratospheric_volcanic.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 26. Radiative Forcings --&gt; Aerosols --&gt; Stratospheric Volcanic Stratospheric volcanic forcing 26.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.stratospheric_volcanic.historical_explosive_volcanic_aerosol_implementation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Type A" # "Type B" # "Type C" # "Type D" # "Type E" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 26.2. Historical Explosive Volcanic Aerosol Implementation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How explosive volcanic aerosol is implemented in historical simulations End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.stratospheric_volcanic.future_explosive_volcanic_aerosol_implementation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Type A" # "Type B" # "Type C" # "Type D" # "Type E" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 26.3. Future Explosive Volcanic Aerosol Implementation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How explosive volcanic aerosol is implemented in future simulations End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.stratospheric_volcanic.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 26.4. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.sea_salt.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 27. Radiative Forcings --&gt; Aerosols --&gt; Sea Salt Sea salt forcing 27.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.aerosols.sea_salt.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 27.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.other.land_use.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "M" # "Y" # "E" # "ES" # "C" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 28. Radiative Forcings --&gt; Other --&gt; Land Use Land use forcing 28.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How this forcing agent is provided (e.g. via concentrations, emission precursors, prognostically derived, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.other.land_use.crop_change_only') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 28.2. Crop Change Only Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Land use change represented via crop change only? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.other.land_use.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 28.3. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.other.solar.provision') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "N/A" # "irradiance" # "proton" # "electron" # "cosmic ray" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 29. Radiative Forcings --&gt; Other --&gt; Solar Solar forcing 29.1. Provision Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N How solar forcing is provided End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.toplevel.radiative_forcings.other.solar.additional_information') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 29.2. Additional Information Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Additional information relating to the provision and implementation of this forcing agent (e.g. citations, use of non-standard datasets, explaining how multiple provisions are used, etc.). End of explanation """
KitwareMedical/TubeTK
docs/examples/MergeAdjacentImages/MergeAdjacentImages.ipynb
apache-2.0
import os import sys import numpy # Path for TubeTK libs #Values takend from TubeTK launcher sys.path.append("C:/src/TubeTK_Python_ITK/TubeTK-build/lib/") sys.path.append("C:/src/TubeTK_Python_ITK/TubeTK-build/lib/Release") # Setting TubeTK Build Directory TubeTK_BUILD_DIR=None if 'TubeTK_BUILD_DIR' in os.environ: TubeTK_BUILD_DIR = os.environ['TubeTK_BUILD_DIR'] else: print('TubeTK_BUILD_DIR not found!') print(' Set environment variable') os.environ["TubeTK_BUILD_DIR"] = "C:/src/TubeTK_Python_ITK/TubeTK-build" TubeTK_BUILD_DIR = os.environ["TubeTK_BUILD_DIR"] #sys.exit( 1 ) if not os.path.exists(TubeTK_BUILD_DIR): print('TubeTK_BUILD_DIR set by directory not found!') print(' TubeTK_BUILD_DIR = ' + TubeTK_BUILD_DIR ) sys.exit(1) try: import itk except: ITK_BUILD_DIR = None if 'ITK_BUILD_DIR' in os.environ: ITK_BUILD_DIR = os.environ['ITK_BUILD_DIR'] else: print('ITK_BUILD_DIR not found!') print(' Set environment variable') os.environ["ITK_BUILD_DIR"] = "C:/src/TubeTK_Python_R/ITK-build" ITK_BUILD_DIR = os.environ["ITK_BUILD_DIR"] #sys.exit( 1 ) if not os.path.exists(ITK_BUILD_DIR): print('ITK_BUILD_DIR set by directory not found!') print(' ITK_BUIDL_DIR = ' + ITK_BUILD_DIR ) sys.exit(1) # Append ITK libs sys.path.append("C:/src/TubeTK_Python_ITK/ITK-build/Wrapping/Generators/Python/Release") sys.path.append("C:/src/TubeTK_Python_ITK/ITK-build/lib/Release") sys.path.append("C:/src/TubeTK_Python_ITK/ITK-build/lib") # Append TubeTK libs sys.path.append("C:/src/TubeTK_Python_ITK/TubeTK-build/ITKModules/TubeTKITK-build/Wrapping/Generators/Python/Release") import itk from itk import TubeTKITK as itktube import matplotlib.pyplot as plt from matplotlib import cm %matplotlib inline """ Explanation: MergeAdjacentImages Notebook This notebook contains a few examples of how to use the MergeAdjacentImages application from TubeTK. First, we will include Python's os package as well as ITK (Python wrapping). We also set the TubeTK build directory variable TUBETK_BUILD_DIR: If ITK is not installed in your python environment, you need to define the environment variable ITK_BUILD_DIR that contains the path to where ITK was built. We need to find the directory in which TubeTK was build. This is required to find the path to the testing data, and may be also required to find the TubeTK library paths if your python environment does not include it. The environment variable TubeTK_BUILD_DIR needs to be defined. End of explanation """ input_image1 = os.path.join(TubeTK_BUILD_DIR, 'MIDAS_Data\ES0015_Large.mha') reader0 = itk.ImageFileReader.New(FileName=input_image1) reader0.Update() im0=reader0.GetOutput() print("Origin:") print im0.GetOrigin() print("Spacing:") print im0.GetSpacing() print("Direction:") print im0.GetDirection() """ Explanation: Next, we load the first input image and show it's origin, spacing, etc.: End of explanation """ ImageType=itk.Image[itk.F,2] im_np0 = itk.PyBuffer[ImageType].GetArrayFromImage(im0) plt.imshow(im_np0, cm.gray) """ Explanation: We get the numpy array for the image and visualize it: End of explanation """ input_image0 = os.path.join(TubeTK_BUILD_DIR, 'MIDAS_Data\ES0015_Large_Wo_offset.mha') print("Image file path:%s"%input_image0) reader1 = itk.ImageFileReader.New(FileName=input_image0) reader1.Update() im1=reader1.GetOutput() print im1.GetOrigin() print im1.GetSpacing() print im1.GetDirection() im_np1 = itk.PyBuffer[ImageType].GetArrayFromImage(im1) plt.imshow(im_np1, cm.gray) """ Explanation: Let's do the same for the second image: End of explanation """ im0.GetSpacing() == im1.GetSpacing() and im0.GetDirection() == im1.GetDirection() """ Explanation: Let's check if the spacing and direction are compatible: End of explanation """ output_image = os.path.join(TubeTK_BUILD_DIR, 'Temporary\Python.MergeAdjacentImages-Ex1.mha') cmd = [os.path.join(TubeTK_BUILD_DIR, 'bin\Release\MergeAdjacentImages'), '-i', '0', # Number of iterations ... here i=0, which means no registration, input_image0, # First image to merge input_image1, # Second image to merge output_image ] """ Explanation: We see that im0 and im1 are in fact compatible, but the origin of im0 is at (200, 200). Merging - Example 1 In this example, we just want to merge our two images (without registration). Let's build the command-line arguments (The output image will be written to /tmp/merged.mha). End of explanation """ import subprocess subprocess.call(cmd) """ Explanation: Let's execute that command (via the subprocess module): End of explanation """ print os.path.exists(output_image) """ Explanation: ... and check if the output image /tmp/merged.mha was actually written to disk: End of explanation """ output_reader = itk.ImageFileReader.New(FileName=output_image) output_reader.Update() out_im=output_reader.GetOutput() print out_im.GetOrigin() print out_im.GetSpacing() print out_im.GetLargestPossibleRegion().GetSize() plt.imshow(itk.PyBuffer[ImageType].GetArrayFromImage(out_im), cm.gray) """ Explanation: We are now ready to visualize the result: End of explanation """ output_image = os.path.join(TubeTK_BUILD_DIR, 'Temporary/Python.MergeAdjacentImages-Ex2.mha') cmd1 = [os.path.join(TubeTK_BUILD_DIR, 'bin/Release/MergeAdjacentImages'), '-i','0', # Number of iterations ... here i=0, which means no registration, '-b','50,50', # This adds a white border around the second image (50 pixel each side) input_image0, input_image1, output_image ] subprocess.call(cmd1) reader=itk.ImageFileReader.New(FileName=output_image) reader.Update() plt.imshow(itk.PyBuffer[ImageType].GetArrayFromImage(reader.GetOutput()), cm.gray) """ Explanation: We see that the output image is larger by 212 pixel in both dimensions, since the second image's origin was at (200, 200) and the image size of both images was 512 times 512 pixel. Merging - Example 2 We can also add some padding (e.g., 50 pixel on each side). For that we modify cmd as follows: End of explanation """ output_image = os.path.join(TubeTK_BUILD_DIR, 'Temporary/Python.MergeAdjacentImages-Ex3.mha') cmd = [os.path.join(TubeTK_BUILD_DIR, 'bin/Release/MergeAdjacentImages'), input_image1, input_image0, output_image ] subprocess.call(cmd) reader=itk.ImageFileReader.New(FileName=output_image) reader.Update() plt.imshow(itk.PyBuffer[ImageType].GetArrayFromImage(reader.GetOutput()), cm.gray) """ Explanation: Merging - Example 3 Let's do the same example WITH rigid registration. End of explanation """
dsacademybr/PythonFundamentos
Cap10/Notebooks/DSA-Python-Cap10-Mini-Projeto3.ipynb
gpl-3.0
# Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) # Instala o TensorFlow !pip install -q tensorflow==2.5 # Instala o Pydot !pip install -q pydot # Imports import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Imports import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers print(tf.__version__) """ Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 10</font> Download: http://github.com/dsacademybr Mini-Projeto 3 - Guia de Modelagem Preditiva com Linguagem Python e TensorFlow Neste Mini-Projeto vamos apresentar um guia básico de modelagem preditiva usando Linguagem Python e TensorFlow, o principal framework para construção de modelos de Machine Learning e Deep Learning e para construir aplicações comerciais de Inteligência Artificial. Este é um guia básico pois o TensorFlow é um framework extenso. O TensorFlow é abordado em detalhes nos cursos da <a href="https://www.datascienceacademy.com.br/bundle/formacao-inteligencia-artificial">Formação Inteligência Artificial</a> (especialmente no curso Deep Learning Frameworks) e na <a href="https://www.datascienceacademy.com.br/bundle/formacao-inteligencia-artificial-aplicada-a-medicina">Formação IA Aplicada à Medicina</a>. Na <a href="https://www.datascienceacademy.com.br/bundle/formacao-cientista-de-dados">Formação Cientista de Dados</a>, no curso de Machine Learning também há um módulo sobre TensorFlow. Alguns projetos com TensorFlow podem ser encontrados no curso de IA Aplicada a Finanças da <a href="https://www.datascienceacademy.com.br/bundle/formacao-engenheiro-blockchain">Formação Engenheiro Blockchain</a>. Instalando e Carregando Pacotes End of explanation """ # Download dos dados import ssl ssl._create_default_https_context = ssl._create_unverified_context dataset_path = keras.utils.get_file("housing.data", "https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data") # Nomes das colunas nomes_colunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATION', 'B', 'LSTAT', 'MEDV'] # Carrega os dados dataset = pd.read_csv(dataset_path, names = nomes_colunas, na_values = "?", comment = '\t', sep = " ", skipinitialspace = True) # Shape dataset.shape # Visualiza os dados dataset.head() """ Explanation: Carregando os Dados Boston House Prices Dataset https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html Características: Número de Observções: 506 Os primeiros 13 recursos são recursos preditivos numéricos / categóricos. O último (atributo 14): o valor mediano é a variável de destino. End of explanation """ # Split dos dados dados_treino = dataset.sample(frac = 0.8, random_state = 0) dados_teste = dataset.drop(dados_treino.index) """ Explanation: Vamos dividir os dados em treino e teste com proporção 80/20. End of explanation """ # Representação visual dos dados de treino fig, ax = plt.subplots() x = dados_treino['RM'] y = dados_treino['MEDV'] ax.scatter(x, y, edgecolors = (0, 0, 0)) ax.set_xlabel('RM') ax.set_ylabel('MEDV') plt.show() """ Explanation: Modelagem Preditiva - Regressão Linear Simples Na regressão linear simples desejamos modelar a relação entre a variável dependente (y) e uma variável independente (x). Variável independente: 'RM' Variável dependente: 'MEDV' Queremos prever o valor da mediana das casas ocupadas por proprietários com base no número de quartos. Vamos criar um plot mostrando a relação atual entre as variáveis. Basicamente temos $MEDV=f(RM)$ e queremos estimar a função $f()$ usando regressão linear. End of explanation """ # Divisão x_treino = dados_treino['RM'] y_treino = dados_treino['MEDV'] x_teste = dados_teste['RM'] y_teste = dados_teste['MEDV'] """ Explanation: Vamos separar x e y. End of explanation """ # Função para construir o modelo def modelo_linear(): # Cria o modelo model = keras.Sequential([layers.Dense(1, use_bias = True, input_shape = (1,), name = 'layer')]) # Otimizador optimizer = tf.keras.optimizers.Adam(learning_rate = 0.01, beta_1 = 0.9, beta_2 = 0.99, epsilon = 1e-05, amsgrad = False, name = 'Adam') # Compila o modelo model.compile(loss = 'mse', optimizer = optimizer, metrics = ['mae','mse']) return model """ Explanation: Criação do Modelo Queremos encontrar os parâmetros (W) que permitem prever a saída y a partir da entrada x: $y = w_1 x + w_0$ A fórmula acima pode ser definida com a seguinte camada densa em um modelo de rede neural artificial: layers.Dense(1, use_bias=True, input_shape=(1,)) End of explanation """ # Cria o modelo modelo = modelo_linear() # Plot do modelo tf.keras.utils.plot_model(modelo, to_file = 'imagens/modelo.png', show_shapes = True, show_layer_names = True, rankdir = 'TB', expand_nested = False, dpi = 100) """ Explanation: MAE = Mean Absolute Error MSE = Mean Squared Error End of explanation """ # Hiperparâmetros n_epochs = 4000 batch_size = 256 n_idle_epochs = 100 n_epochs_log = 200 n_samples_save = n_epochs_log * x_treino.shape[0] print('Checkpoint salvo a cada {} amostras'.format(n_samples_save)) # Callback earlyStopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = n_idle_epochs, min_delta = 0.001) # Lista para as previsões predictions_list = [] # Caminho ppara salvar o checkpoint checkpoint_path = "dados/" # Create a callback that saves the model's weights every n_samples_save checkpointCallback = tf.keras.callbacks.ModelCheckpoint(filepath = "dados/", verbose = 1, save_weights_only = True, save_freq = n_samples_save) # Salva a primeira versão do modelo modelo.save_weights(checkpoint_path.format(epoch = 0)) # Treinamento history = modelo.fit(x_treino, y_treino, batch_size = batch_size, epochs = n_epochs, validation_split = 0.1, verbose = 1, callbacks = [earlyStopping, checkpointCallback]) # Métricas do histórico de treinamento print('keys:', history.history.keys()) """ Explanation: Treinamento do Modelo End of explanation """ # Retornando os valores desejados para o plot mse = np.asarray(history.history['mse']) val_mse = np.asarray(history.history['val_mse']) # Prepara os valores para o dataframe num_values = (len(mse)) values = np.zeros((num_values, 2), dtype = float) values[:,0] = mse values[:,1] = val_mse # Cria o dataframe steps = pd.RangeIndex(start = 0, stop = num_values) df = pd.DataFrame(values, steps, columns = ["MSE em Treino", "MSE em Validação"]) df.head() # Plot sns.set(style = "whitegrid") sns.lineplot(data = df, palette = "tab10", linewidth = 2.5) # Previsões com o modelo treinado previsoes = modelo.predict(x_teste).flatten() # Imprime as previsões previsoes """ Explanation: MSE = Mean Squared Error End of explanation """
sdpython/ensae_teaching_cs
_doc/notebooks/2a/seance_5_prog_fonctionnelle.ipynb
mit
from jyquickhelper import add_notebook_menu add_notebook_menu() """ Explanation: 2A.i - programmation fonctionnelle Itérateur, générateur, programmation fonctionnelle, tout pour éviter de charger l'intégralité des données en mémoire et commencer les calculs le plus vite possible. End of explanation """ import pyensae.datasource pyensae.datasource.download_data("twitter_for_network_100000.db.zip") """ Explanation: Données : twitter_for_network_100000.db.zip End of explanation """ def sorted_1(l): l.sort() return l a = [4,3,2,1] print(sorted_1(a)) print(a) a = [4,3,2,1] print(sorted(a)) print(a) import random l = list(range(100000)) random.shuffle( l ) %timeit l.sort() %timeit sorted(l) """ Explanation: Programmation fonctionnelle Fonction pure, tests et modularité La programmation fonctionnelle se concentre sur la notion de fonction, comme son nom l'indique, et plus précisément de fonction pure. Une fonction pure est une fonction: dont le résultat dépend uniquement des entrées qui n'a pas d'effet de bord End of explanation """ import os, psutil, gc, sys if not sys.platform.startswith("win"): import resource def memory_usage_psutil(): gc.collect() process = psutil.Process(os.getpid()) mem = process.memory_info()[0] / float(2 ** 20) print( "Memory used : %i MB" % mem ) if not sys.platform.startswith("win"): print( "Max memory usage : %i MB" % (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss//1024) ) memory_usage_psutil() """ Explanation: La programmation fonctionnelle est à mettre en contraste par rapport à la programmation orientée objet. L'objet est plus centré sur la représentation, la fonction sur l'action l'entrée et le résultat. Il existe des langages orientés fonctionnel, comme lisp. Elle présente en effet des avantages considérables sur au moins deux points essentiels en informatique: tests modularité Un exemple concret, les webservices en python. Ceux-ci sont définies comme des fonctions, ce qui permet notamment de facilement les rendre compatibles avec différents serveurs web, en donnant à ceux-ci non pas le webservice directement, mais une composition de celui-ci. Apache $\Rightarrow wrapper \; Apache \circ webservice$ IIS $\Rightarrow wrapper \; IIS \circ webservice$ CGI $\Rightarrow wrapper \; CGI \circ webservice$ La composition est une façon très puissante de modifier la comportement d'un objet, car elle n'impacte pas l'objet lui-même. End of explanation """ a = (it**2 for it in range(1000001)) %timeit a = (it**2 for it in range(1000001)) print( type(a) ) """ Explanation: Fonctions pour la gestion de grosses données : laziness Lors de la gestion de grosses données, le point crucial est que l'on ne veut pas stocker de valeurs intermédiaires, parce que celle-ci pourraient prendre trop de place en mémoire. Par exemple pour calculer la moyenne du nombre de followers dans la base de donnée, il n'est pas indispensable de stocker tous les users en mémoire. Les fonctions dans cytoolz sont dites "lazy", ce qui signifie qu'elles ne s'exécutent effectivement que quand nécessaire. Cela évite d'utiliser de la mémoire pour stocker un résultat intermédiaire. Par exemple la cellule ci-dessous s'exécute très rapidement, et ne consomme pas de mémoire. En effet a sert à représenter l'ensemble des nombres de 0 à 1000000 au carré, mais ils ne sont pas caculés immédiatement. End of explanation """ %timeit sum( (it**2 for it in range(1000001)) ) sum( a ) """ Explanation: Ici on calcule la somme de ces nombres, et c'est au moment où on appelle la fonction sum que l'on calcule effectivement les carrés. Mais du coup cette opération est beaucoup plus lente que si l'on avait déjà calculé ces nombres. End of explanation """ memory_usage_psutil() """ Explanation: Ma consommation mémoire n'a quasiment pas bougé. End of explanation """ b = [it**2 for it in range(1000001)] %timeit b = [it**2 for it in range(1000001)] print(type(b)) print( sum(b) ) %timeit sum(b) memory_usage_psutil() """ Explanation: Ci-dessous, on n'a simplement remplacé les parenthèses () par des crochets [], mais cela suffit pour dire que l'on veut effectivement calculer ces valeurs et en stocker la liste. Cela est plus lng, consomme de la mémoire, mais en calculer la somme sera beaucoup plus rapide. End of explanation """ sum(a) """ Explanation: Attention à ce que a est objet de type iterateur, qui retient sa position. Autrement dit, on ne peut l'utiliser qu'une seule fois. End of explanation """ def f(): return (it**2 for it in range(1000001)) print( sum(f()) ) %timeit sum(f()) """ Explanation: Si on a besoin de le réutiliser, on peut soit stocker les valeurs, soit le mettre dans une fonction End of explanation """ import pyensae.datasource pyensae.datasource.download_data("twitter_for_network_100000.db.zip") memory_usage_psutil() import cytoolz as ct # import groupby, valmap, compose import cytoolz.curried as ctc ## pipe, map, filter, get import sqlite3 import pprint try: import ujson as json except: print("ujson not available") import json tw_users_limit = 1000000 conn_sqlite = sqlite3.connect("twitter_for_network_100000.db") cursor_sqlite = conn_sqlite.cursor() """ Explanation: Exemple cytoolz / twitters data Liens vers les données : twitter_for_network_100000.db.zip twitter_for_network_full.db.zip End of explanation """ import ujson as ujson_test import json as json_test cursor_sqlite.execute("SELECT content FROM tw_users LIMIT 1") tw_user_json = cursor_sqlite.fetchone()[0] %timeit ujson_test.loads( tw_user_json ) %timeit json_test.loads( tw_user_json ) tw_users_limit = 1000000 """ Explanation: Note : sur internet vous verez plus souvent l'exemple json.loads. ujson est simplement une version plus rapide. Elle n'est pas indispensable End of explanation """ ## With storing in memory cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) tw_users_as_json = list( ctc.map( json.loads, ctc.pluck( 1, cursor_sqlite ) ) ) len(tw_users_as_json) """ Explanation: Ci-dessous on charge en mémoire la liste des profils utilisateurs de la table tw_users. Il est conseillé de tester vos fonctions sur des extraits de vos données qui tiennent en mémoire. Par contre ensuite il faudra éviter de les charger en mémoire. End of explanation """ ## Without storing in memory cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) tw_users_as_json = ctc.pluck("followers_count", # Même chose qu'avec le 1, mais on utilise une clé ctc.map(json.loads, # Map applique la fonction json.loads à tous les objets ctc.pluck(1, # Le curseur renvoit les objets sous forme de tuple des colonnes # pluck(1, _) est l'équivalent de (it[1] for it in _) cursor_sqlite) ) ) sum(tw_users_as_json) cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) %timeit -n 1 tw_users_as_json = ctc.pluck("followers_count", ctc.map(json.loads, ctc.pluck(1, cursor_sqlite) ) ) ## Without storing in memory def get_tw_users_as_json(): cursor_sqlite.execute("SELECT content FROM tw_users LIMIT %s" % tw_users_limit) return ctc.pluck("followers_count", ctc.map(json.loads, ctc.pluck(0, cursor_sqlite) ) ) sum(get_tw_users_as_json()) sum(get_tw_users_as_json()) """ Explanation: On a dans ces deux exemples deux fonctions des plus classiques : ctc.pluck => prend une séquence en entrée et renvoit une séquence de de l'item sélectionnée ctc.map => applique une fonction à chaque élément de la séquence End of explanation """ tw_users_limit = 1000000 import ujson def get_users_cyt(): cursor_sqlite.execute("SELECT content FROM tw_users LIMIT %s" % tw_users_limit) return ct.map(ujson.loads, ct.pluck( 0, cursor_sqlite ) ) def count_all_followers_cyt(): return sum( ct.pluck("followers_count", get_users_cyt() ) ) def count_all_followers_cyt_by_location(): return ct.reduceby( "location", lambda x, item: x + item["followers_count"], get_users_cyt(), 0 ) %timeit count_all_followers_cyt() %timeit count_all_followers_cyt_by_location() memory_usage_psutil() """ Explanation: Quelques exemples : count_all_followers_cyt() fait la somme des followers count_all_followers_cyt_by_location() fait la somme par location différente (nous verrons ensuite que cette donnée, du texte brute, mériterait des traitements particuliers) End of explanation """ from collections import defaultdict def count_all_followers(): cursor_sqlite.execute("SELECT content FROM tw_users LIMIT %s" % tw_users_limit) nb_totals_followers_id = 0 for it_json in cursor_sqlite: nb_totals_followers_id += json.loads(it_json[0])[ "followers_count" ] return nb_totals_followers_id def count_all_followers_by_location(): cursor_sqlite.execute("SELECT content FROM tw_users LIMIT %s" % tw_users_limit) res = defaultdict(int) for it_json in cursor_sqlite: it_json = json.loads(it_json[0]) res[it_json["location"]] += it_json[ "followers_count" ] return res %timeit count_all_followers() %timeit count_all_followers_by_location() cursor_sqlite.execute("SELECT content FROM tw_users LIMIT 10000") %timeit -n1000 first_content = cursor_sqlite.fetchone()[0] cursor_sqlite.execute("SELECT content FROM tw_users LIMIT 10000") first_content = cursor_sqlite.fetchone()[0] %timeit json.loads( first_content ) """ Explanation: Leur équivalent en code standard. A noter que la version fonctionnelle n'est pas significativement plus rapide. End of explanation """ import cytoolz as ct import cytoolz.curried as ctc cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) a = ctc.pluck( 1, cursor_sqlite ) b = ctc.map( json.loads, a ) c = ctc.pluck("followers_count", b) print( sum(c) ) """ Explanation: Cytoolz functions cytoolz est une implémentation plus performante de la librairie toolz, il faut donc vous référer à la documentation de celle-ci. http://toolz.readthedocs.org/en/latest/api.html A noter qu'il y a deux packages, cytoolz et cytoolz.curried, ils contiennent les mêmes fonctions, seulement celles du second supporte le "curry", l'évaluation partielle (voir plus bas). Cela peut représenter un petit overhead. les basiques cytoolz.curried.pluck => sélectionne un item dans chaque élément d'une séquence, à partir d'une clé ou d'un index cytoolz.curried.map => applique une fonction à tous les éléments d'une séquence End of explanation """ cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) pl_1 = ctc.pluck(1) ## ctc.pluck prend 2 arguments, cette fonction est donc une fonction d'un argument m_loads = ctc.map(json.loads) pl_fc = ctc.pluck("followers_count") a = pl_1( cursor_sqlite ) b = m_loads(a) c = pl_fc(b) print( sum(c) ) tw_users_limit = 10000 cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) sum( pl_fc( m_loads( pl_1 ( cursor_sqlite ) ) ) ) """ Explanation: A noter que toutes les fonctions cytoolz du package cytoolz.curry supportent les évaluations partielles, i.e. construire une fonction d'un argument à partir d'une fonction de deux arguments (ou plus généralement n-1 arguments à partir de n) End of explanation """ get_json_seq = ct.compose( m_loads, pl_1 ) count_nb_followers = ct.compose( sum, pl_fc, get_json_seq ) cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) count_nb_followers( cursor_sqlite ) """ Explanation: cytoolz.compose permet de créer une fonction par un chaînage de fonction. Le résultat de chaque fonction est donné en argument à la fonction suivante, chaque fonction doit donc ne prendre qu'un seul argument, d'où l'intérêt de l'évaluation partielle. Comme en mathématique, les fonctions sont évaluées de droite à gauche count_nb_followers( cursor_sqlite ) est donc équivalent à sum( pl_fc( get_json_seq( cursor_sqlite ) ) ) End of explanation """ ct.pipe( cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit), pl_1, m_loads, pl_fc, sum ) cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) print( count_nb_followers( ct.take_nth(2, cursor_sqlite ) ) ) # take_nth, prendre un élément sur n cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) print( count_nb_followers( ct.take_nth(2, ct.drop(1, cursor_sqlite ) ) ) ) # drop, enlève les n premiers éléments """ Explanation: cytoolz.pipe a un comportement similaire, avec une différence importante, l'ordre des fonctions est inversé (ce qui le rend plus lisible, à mon humble avis) End of explanation """ tw_users_limit """ Explanation: cytoolz.take_nth => prend un élément sur n cytoolz.drop => enlève n éléments End of explanation """ import collections from operator import ge, le cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) %timeit -n1 ct.countby(ctc.get("location"), get_json_seq( cursor_sqlite ) ) cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) %timeit -n1 ct.frequencies(ct.pluck("location", get_json_seq( cursor_sqlite ) ) ) def count_location_frequency(c): counter = collections.Counter() for it_json in c: it_json = json.loads( it_json[1] ) counter[ it_json["location"] ] += 1 return counter cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) %timeit -n1 count_location_frequency(cursor_sqlite) get_freq_by_loc = ct.compose( ct.frequencies, ctc.pluck("location"), get_json_seq ) cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) pprint.pprint( ct.frequencies( get_freq_by_loc(cursor_sqlite).values() ) ) cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) pprint.pprint( ct.valfilter( ct.curry(le,10), get_freq_by_loc(cursor_sqlite) ) ) memory_usage_psutil() """ Explanation: Il existe beaucoup de fonctions, dont un certain nombre peuvent faire double emploi. Par exemple countby prend une fonction et une séquence et compte le nombre de résultat de la fonction appliquée à chaque élément de la séquence, ce qui équivalent à appliquer une fonction à tous les éléments de la séquence, puis calculer la fréquence des résultats (opération effectuée avec frequencies et pluck) End of explanation """ liste_animaux = [ { "animal":"chat" , "age":15,"npm":"Roudy"}, { "animal":"chien" , "age": 5,"npm":"Medor"}, { "animal":"chien" , "age": 3,"npm":"Fluffy"}, { "animal":"chien" , "age": 2,"npm":"Max"}, { "animal":"chat" , "age":10,"npm":"Teemo"}, { "animal":"chat" , "age":25,"npm":"Garfied"} ] ct.groupby( "animal", liste_animaux ) tw_users_limit = 100000 cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) for i, (k, v) in enumerate( ct.valmap( ct.count, ct.groupby( "location", get_json_seq( cursor_sqlite ) ) ).items() ): print(repr(k) + " : " + repr(v)) if i == 50: break """ Explanation: A priori il est préférable de choisir l'ordre de fonctions qui sépare les plus les opérations. Ici countby fait les deux à la fois (appliquer la fonction et calculer le nombre d'occurences). Les deux derniers que nous allons voir sont reduce, reduceby et groupby. Attention à groupby, celle-ci crée un dictionnaire de liste des éléments donnés en entrées, elle forcera donc le chargement en mémoire de toutes les données. groupby prend en entrée une clé et une séquence, et groupe les objets pour lesquels cette clé a la même valeur. Son retour sera un dictionnaire dont les clés sont les valeurs prises par la clé (ci-dessous les différentes valeurs de "location" dans les utilisateurs) et les valeurs les listes des objets ayant cette valeur pour la clé. End of explanation """ from operator import add, mul print( ct.reduce( add, [1,2,3,4,5] ) ) ## calcule add(1,2), puis add(_, 3), add(_, 4), etc ... print( ct.reduce( mul, [1,2,3,4,5] ) ) """ Explanation: A noter que si vous voulez utiliser les opérateurs usuels (+, *, etc ...), vous pouvez les obtenir sous forme de fonctions dans le package operator reduce applique une fonction aux deux premiers éléments d'une séquence (ou au premier élément et une valeur initiale) et applique ensuite cette fonction au total et à l'élement suivant. End of explanation """ tw_users_limit = 10000 cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) ct.reduce((lambda total,elt: total + elt["followers_count"]), # Fonction pour faire la réduction get_json_seq( cursor_sqlite ), # séquence à réduire, 0 # Valeur initiale ) """ Explanation: Du coup si votre résultat n'est pas de même nature que vos éléments, la syntaxe ci-dessus ne fonctionnera pas. Dans ce cas, il faut rajouter une valeur initiale. Dans ce cas la fonction de réduction est appliquée à : f(valeur_initiale, premier_élément) f(résultat_précédent, deuxième_élément) f(résultat_précédent, troisième_élément) End of explanation """ from operator import le tw_users_limit = 10000 cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) %timeit -n1 ct.reduceby( "location", lambda x,y: x + y["followers_count"], get_json_seq( cursor_sqlite ), 0 ) cursor_sqlite.execute("SELECT id, content FROM tw_users LIMIT %s" % tw_users_limit) ct.valfilter(ct.curry(le,10000), ## Ne sélectionne que les éléments dont la valeur est supérieure à 10000 ct.reduceby( "location", lambda x,y: x + y["followers_count"], get_json_seq( cursor_sqlite ), 0 )) """ Explanation: reduceby fait la même chose, avec un groupement selon un critère en plus. Le code ci-dessous calcule la somme du nombre de followers par location, et filtre sur les valeurs supérieures à 10000. End of explanation """
Vincibean/machine-learning-with-tensorflow
advanced-mnist-with-tensorflow.ipynb
apache-2.0
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) """ Explanation: Advanced MNIST with TensorFlow Abstract Just like programming has "Hello World", machine learning has MNIST. MNIST is a simple computer vision dataset. It consists of images of handwritten digits, as well as labels for each image telling us which digit it is. In this tutorial, we're going to train a model to look at MNIST images and predict what digits they are. Introduction This tutorial is taken, with slight modification and different annotations, from TensorFlow's official documentation. This tutorial is intended for readers who are new to both machine learning and TensorFlow. Data Retrieval The MNIST dataset is hosted on Yann LeCun's website. The following two lines of code will take care of downloading and reading in the data automatically. mnist is a lightweight class which stores the training, validation, and testing sets as NumPy arrays, as well as providing a function for iterating through data minibatches. End of explanation """ import tensorflow as tf """ Explanation: Data Analysis First of all, we import the TensorFlow library. End of explanation """ x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) """ Explanation: We assign a shape of [None, 784], where 784 is the dimensionality of a single flattened 28 by 28 pixel MNIST image, and None indicates that the first dimension, corresponding to the batch size, can be of any size. The target output classes y_ will also consist of a 2d tensor, where each row is a one-hot 10-dimensional vector (a one-hot vector is a vector which is 0 in most dimensions and 1 in a single dimension) indicating which digit class (zero to nine) the corresponding MNIST image belongs to. Let's create some symbolic variables using TensorFlow's placeholder() operation. The result will not be a specific value; it will be a placeholder, a value that we'll input when we ask TensorFlow to run a computation. End of explanation """ x_image = tf.reshape(x, [-1,28,28,1]) """ Explanation: The input images x consists of a 2D tensor of floating point numbers. Here we assign it a shape of [None, 784], where 784 is the dimensionality of a single flattened 28 by 28 pixel MNIST image, and None indicates that the first dimension, corresponding to the batch size, can be of any size. The target output classes y_ also consists of a 2D tensor, where each row is a one-hot 10-dimensional vector indicating which digit class (zero through nine) the corresponding MNIST image belongs to. Flattening the data throws away information about the 2D structure of the image. This is bad! We are going to use Convolutional Neural Networks (CNN), which is great in exploiting the 2D structure of an image. So, let's reshape x into a 28 x 28 matrix (the final dimension corresponding to the number of color channels). End of explanation """ def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) """ Explanation: To create this model, we're going to need to create a lot of weights and biases. One should generally initialize weights with a small amount of noise for symmetry breaking, and to prevent 0 gradients. Instead of doing this repeatedly while we build the model, let's create two handy functions to do it for us. The resulting weights and biases will all be Variables. A Variable is a modifiable tensor that lives in TensorFlow's graph of interacting operations. It can be used and even modified by the computation. For machine learning applications, one generally has the model parameters be Variables. We create these Variables by giving tf.Variable() the initial value of the Variable End of explanation """ def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') """ Explanation: Our convolutions uses a stride of one and are zero padded so that the output is the same size as the input. Our pooling is plain old max pooling over 2x2 blocks. To keep our code cleaner, let's also abstract those operations into functions. End of explanation """ W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) """ Explanation: Build the Deep Learning architecture. End of explanation """ y_conv = tf.nn.softmax(tf.add(tf.matmul(h_fc1_drop, W_fc2), b_fc2)) """ Explanation: We know that every image in MNIST is of a handwritten digit between zero and nine, so we know there are only ten possible values that a given image can be. We want to be able to look at an image and give the probabilities for it being each digit. For example, our model might look at a picture of a nine and be 80% sure it's a nine, but give a 5% chance to it being an eight (because of the top loop) and a bit of probability to all the others because it isn't 100% sure. If you want to assign probabilities to an object being one of several different things, you want to use SoftMax: SoftMax gives us a list of values between 0 and 1 that add up to 1. A softmax regression has two steps: 1. we add up the evidence of our input being in certain classes (with a weighted sum of the pixel intensities) 2. we convert (normalize) that evidence into probabilities For this reason, we use SoftMax as our last layer. End of explanation """ cross_entropy = - tf.reduce_sum(y_ * tf.log(y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) """ Explanation: Our loss function is the cross-entropy between the target and the softmax activation function applied to the model's prediction. In some rough sense, the cross-entropy is measuring how inefficient our predictions are for describing the truth, how large is the discrepancy between two probability distributions. End of explanation """ correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) """ Explanation: How well does our model do? We have to figure out where we predicted the correct label. tf.argmax() is an extremely useful function which gives you the index of the highest entry in a tensor along some axis. tf.argmax(y,1) is the label our model thinks is most likely for each input, while tf.argmax(y_,1) is the correct label. We can use tf.equal to check if our prediction matches the truth. End of explanation """ accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) """ Explanation: That gives us a list of booleans. To determine what fraction are correct, we cast to floating point numbers and then take the mean. For example, [True, False, True, True] would become [1,0,1,1] which would become 0.75. End of explanation """ init = tf.initialize_all_variables() sess = tf.Session() with sess.as_default(): sess.run(init) for i in range(20000): batch = mnist.train.next_batch(50) if i % 100 == 0: train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g" % (i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) """ Explanation: Let's launch the graph! Each step of the inner loop, we get a "batch" of one hundred random data points from our training set. We run train_step feeding in the batches data to replace the placeholders. Ideally, we'd like to use all our data for every step of training because that would give us a better sense of what we should be doing, but that's expensive. So, instead, we use a different subset every time. Doing this is cheap and has much of the same benefit. End of explanation """
tensorflow/agents
docs/tutorials/8_networks_tutorial.ipynb
apache-2.0
#@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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2021 The TF-Agents Authors. End of explanation """ !pip install tf-agents from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import random_py_environment from tf_agents.environments import tf_py_environment from tf_agents.networks import encoding_network from tf_agents.networks import network from tf_agents.networks import utils from tf_agents.specs import array_spec from tf_agents.utils import common as common_utils from tf_agents.utils import nest_utils """ Explanation: Networks <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/agents/tutorials/8_networks_tutorial"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png" /> View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/8_networks_tutorial.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/agents/blob/master/docs/tutorials/8_networks_tutorial.ipynb"> <img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/agents/docs/tutorials/8_networks_tutorial.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> Introduction In this colab we will cover how to define custom networks for your agents. The networks help us define the model that is trained by agents. In TF-Agents you will find several different types of networks which are useful across agents: Main Networks QNetwork: Used in Qlearning for environments with discrete actions, this network maps an observation to value estimates for each possible action. CriticNetworks: Also referred to as ValueNetworks in literature, learns to estimate some version of a Value function mapping some state into an estimate for the expected return of a policy. These networks estimate how good the state the agent is currently in is. ActorNetworks: Learn a mapping from observations to actions. These networks are usually used by our policies to generate actions. ActorDistributionNetworks: Similar to ActorNetworks but these generate a distribution which a policy can then sample to generate actions. Helper Networks * EncodingNetwork: Allows users to easily define a mapping of pre-processing layers to apply to a network's input. * DynamicUnrollLayer: Automatically resets the network's state on episode boundaries as it is applied over a time sequence. * ProjectionNetwork: Networks like CategoricalProjectionNetwork or NormalProjectionNetwork take inputs and generate the required parameters to generate Categorical, or Normal distributions. All examples in TF-Agents come with pre-configured networks. However these networks are not setup to handle complex observations. If you have an environment which exposes more than one observation/action and you need to customize your networks then this tutorial is for you! Setup If you haven't installed tf-agents yet, run: End of explanation """ class ActorNetwork(network.Network): def __init__(self, observation_spec, action_spec, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, fc_layer_params=(75, 40), dropout_layer_params=None, activation_fn=tf.keras.activations.relu, enable_last_layer_zero_initializer=False, name='ActorNetwork'): super(ActorNetwork, self).__init__( input_tensor_spec=observation_spec, state_spec=(), name=name) # For simplicity we will only support a single action float output. self._action_spec = action_spec flat_action_spec = tf.nest.flatten(action_spec) if len(flat_action_spec) > 1: raise ValueError('Only a single action is supported by this network') self._single_action_spec = flat_action_spec[0] if self._single_action_spec.dtype not in [tf.float32, tf.float64]: raise ValueError('Only float actions are supported by this network.') kernel_initializer = tf.keras.initializers.VarianceScaling( scale=1. / 3., mode='fan_in', distribution='uniform') self._encoder = encoding_network.EncodingNetwork( observation_spec, preprocessing_layers=preprocessing_layers, preprocessing_combiner=preprocessing_combiner, conv_layer_params=conv_layer_params, fc_layer_params=fc_layer_params, dropout_layer_params=dropout_layer_params, activation_fn=activation_fn, kernel_initializer=kernel_initializer, batch_squash=False) initializer = tf.keras.initializers.RandomUniform( minval=-0.003, maxval=0.003) self._action_projection_layer = tf.keras.layers.Dense( flat_action_spec[0].shape.num_elements(), activation=tf.keras.activations.tanh, kernel_initializer=initializer, name='action') def call(self, observations, step_type=(), network_state=()): outer_rank = nest_utils.get_outer_rank(observations, self.input_tensor_spec) # We use batch_squash here in case the observations have a time sequence # compoment. batch_squash = utils.BatchSquash(outer_rank) observations = tf.nest.map_structure(batch_squash.flatten, observations) state, network_state = self._encoder( observations, step_type=step_type, network_state=network_state) actions = self._action_projection_layer(state) actions = common_utils.scale_to_spec(actions, self._single_action_spec) actions = batch_squash.unflatten(actions) return tf.nest.pack_sequence_as(self._action_spec, [actions]), network_state """ Explanation: Defining Networks Network API In TF-Agents we subclass from Keras Networks. With it we can: Simplify copy operations required when creating target networks. Perform automatic variable creation when calling network.variables(). Validate inputs based on network input_specs. EncodingNetwork As mentioned above the EncodingNetwork allows us to easily define a mapping of pre-processing layers to apply to a network's input to generate some encoding. The EncodingNetwork is composed of the following mostly optional layers: Preprocessing layers Preprocessing combiner Conv2D Flatten Dense The special thing about encoding networks is that input preprocessing is applied. Input preprocessing is possible via preprocessing_layers and preprocessing_combiner layers. Each of these can be specified as a nested structure. If the preprocessing_layers nest is shallower than input_tensor_spec, then the layers will get the subnests. For example, if: input_tensor_spec = ([TensorSpec(3)] * 2, [TensorSpec(3)] * 5) preprocessing_layers = (Layer1(), Layer2()) then preprocessing will call: preprocessed = [preprocessing_layers[0](observations[0]), preprocessing_layers[1](observations[1])] However if preprocessing_layers = ([Layer1() for _ in range(2)], [Layer2() for _ in range(5)]) then preprocessing will call: python preprocessed = [ layer(obs) for layer, obs in zip(flatten(preprocessing_layers), flatten(observations)) ] Custom Networks To create your own networks you will only have to override the __init__ and call methods. Let's create a custom network using what we learned about EncodingNetworks to create an ActorNetwork that takes observations which contain an image and a vector. End of explanation """ action_spec = array_spec.BoundedArraySpec((3,), np.float32, minimum=0, maximum=10) observation_spec = { 'image': array_spec.BoundedArraySpec((16, 16, 3), np.float32, minimum=0, maximum=255), 'vector': array_spec.BoundedArraySpec((5,), np.float32, minimum=-100, maximum=100)} random_env = random_py_environment.RandomPyEnvironment(observation_spec, action_spec=action_spec) # Convert the environment to a TFEnv to generate tensors. tf_env = tf_py_environment.TFPyEnvironment(random_env) """ Explanation: Let's create a RandomPyEnvironment to generate structured observations and validate our implementation. End of explanation """ preprocessing_layers = { 'image': tf.keras.models.Sequential([tf.keras.layers.Conv2D(8, 4), tf.keras.layers.Flatten()]), 'vector': tf.keras.layers.Dense(5) } preprocessing_combiner = tf.keras.layers.Concatenate(axis=-1) actor = ActorNetwork(tf_env.observation_spec(), tf_env.action_spec(), preprocessing_layers=preprocessing_layers, preprocessing_combiner=preprocessing_combiner) """ Explanation: Since we've defined the observations to be a dict we need to create preprocessing layers to handle these. End of explanation """ time_step = tf_env.reset() actor(time_step.observation, time_step.step_type) """ Explanation: Now that we have the actor network we can process observations from the environment. End of explanation """
TomAugspurger/engarde
examples/Trains.ipynb
mit
import pandas as pd import engarde.decorators as ed pd.set_option('display.max_rows', 10) dtypes = dict( price1=int, price2=int, time1=int, time2=int, change1=int, change2=int, comfort1=int, comfort2=int ) @ed.is_shape((-1, 11)) @ed.has_dtypes(items=dtypes) def unload(): url = "http://vincentarelbundock.github.io/Rdatasets/csv/Ecdat/Train.csv" trains = pd.read_csv(url, index_col=0) return trains df = unload() df.head() """ Explanation: We'll work with a data set of customer preferences on trains, available here. This is a static dataset and isn't being updated, but you could imagine that each month the Dutch authorities upload a new month's worth of data. We can start by making some very basic assertions, that the dataset is the correct shape, and that a few columns are the correct dtypes. Assertions are made as decorators to functions that return a DataFrame. End of explanation """ def rational(df): """ Check that at least one criteria is better. """ r = ((df.price1 < df.price2) | (df.time1 < df.time2) | (df.change1 < df.change2) | (df.comfort1 > df.comfort2)) return r @ed.is_shape((-1, 11)) @ed.has_dtypes(items=dtypes) @ed.verify_all(rational) def unload(): url = "http://vincentarelbundock.github.io/Rdatasets/csv/Ecdat/Train.csv" trains = pd.read_csv(url, index_col=0) return trains df = unload() """ Explanation: Notice two things: we only specified the dtypes for some of the columns, and we don't care about the length of the DataFrame (just its width), so we passed -1 for the first dimension of the shape. Since people are rational, their first choice is surely going to be better in at least one way than their second choice. This is fundamental to our analysis later on, so we'll explicilty state it in our code, and check it in our data. End of explanation """ @ed.verify_all(rational) def drop_silly_people(df): r = ((df.price1 < df.price2) | (df.time1 < df.time2) | (df.change1 < df.change2) | (df.comfort1 > df.comfort2)) return df[r] @ed.is_shape((-1, 11)) @ed.has_dtypes(items=dtypes) def unload(): url = "http://vincentarelbundock.github.io/Rdatasets/csv/Ecdat/Train.csv" trains = pd.read_csv(url, index_col=0) return trains def main(): df = (unload() .pipe(drop_silly_people) ) return df df = main() """ Explanation: OK, so apparently people aren't rational... We'll fix this problem by ignoring those people (why change your mind when you can change the data?). End of explanation """
aburgasser/splat
tutorials/spectral_database_query.ipynb
mit
# main splat import import splat import splat.database as spdb # other useful imports import astropy.units as u import copy import numpy as np import pandas import matplotlib.pyplot as plt # make sure this is at least 2021.07.22 splat.VERSION """ Explanation: SPLAT Tutorials: Database Query Tools Authors Adam Burgasser Version date 22 July 2021 Learning Goals Explore some of the data spreadsheet manipulation tools built into SPLAT (splat.database.prepDB) Learn how to use the astroquery wrapper for Vizier to get individual source information (splat.database.getPhotometry, splat.database.querySimbad) Learn how to use the astroquery wrapper for Simbad to get individual source information (splat.database.querySimbad) Learn how to use the astroquery wrapper for XMatch to get information for many sources (splat.database.queryXMatch) Keywords astroquery, databases Companion Content None Summary In this tutorial, we are going to see how to use the splat.database functions to manage source spreadsheets and query online databases for source informaiton. End of explanation """ # let's start with a folder of RA & DEC db = pandas.read_csv(splat.SPLAT_PATH+splat.TUTORIAL_FOLDER+'terrien2015_radec.csv') db # add in the necessary information for queries with prepDB # this adds in columns for designation and SkyCoord coordinates db = spdb.prepDB(db) db # alternately let's assume we have a file that contains only designations db = pandas.read_csv(splat.SPLAT_PATH+splat.TUTORIAL_FOLDER+'terrien2015_designations.csv') db # prepDB will adds in the columns for RA, Dec and SkyCoord coordinates db = spdb.prepDB(db) db """ Explanation: Prepping datasets SPLAT useds pandas as its default spreadsheet format. There is a simple tool called prepDB available to manage sets of data to assure one has sufficient informaiton to query online catalogs. We're going to explore a couple of cases based on the targets observed by Terrien et al. (2015), for which there are two .csv files in the SPLAT tutorial directory End of explanation """ # look at the docstring for this function spdb.getPhotometry? # look to see what input catalogs are available # the links point to the information page on this catalog in Vizier spdb.getPhotometry(_,info=True) # take the first coordinate and search for 2MASS photometry # this will search within 30" of the target and # return a pandas spreadsheet in order of separation from the original coordinate srch = spdb.getPhotometry(db['COORDINATES'].iloc[0],catalog='2MASS',radius=30*u.arcsec) srch # if we want to return only the nearest target, set nearest=True srch = spdb.getPhotometry(db['COORDINATES'].iloc[0],catalog='2MASS',radius=30*u.arcsec,nearest=True) srch # note that the duplicate function spdb.queryVizier does the same thing srch = spdb.queryVizier(db['COORDINATES'].iloc[0],catalog='2MASS',radius=30*u.arcsec,nearest=True) srch # let's add the 2MASS J, H, and K magnitudes and their uncertainties # to our original spreadsheet # first set up columns cstring = ['Jmag','e_Jmag','Hmag','e_Hmag','Kmag','e_Kmag','sep'] for c in cstring: db[c] = np.zeros(len(db)) # now add our measurement for the nearest source for c in cstring: db[c].iloc[0] = srch[c].iloc[0] db.iloc[0] # now let's repeat for the first 30 positions - this will take several seconds! for i,crd in enumerate(db['COORDINATES'].iloc[:30]): srch = spdb.getPhotometry(crd,catalog='2MASS',radius=30.*u.arcsec,nearest=True) # catch for case where nothing is returned if len(srch)>0: for c in cstring: db[c].iloc[i] = srch[c].iloc[0] db.iloc[:30] # you can search on other catalogs in Vizier as well by entering in the catalog reference # here's an example for TESS Input Catalog (TIC) of Stassun et al. 2019 # see https://cdsarc.unistra.fr/viz-bin/cat/IV/38 cat = 'IV/38/tic' srch = spdb.getPhotometry(db['COORDINATES'].iloc[0],catalog=cat,radius=30*u.arcsec,nearest=True) srch """ Explanation: Getting photometry with getPhotometry The splat.database.getPhotometry() is a wrapper for astroquery.Vizier, allowing you to query the Vizier network of catalogs to find relevant photometry and other information. This code is particularly well suited for searching on source at a time; for a large number of sources it is probably better to use splat.database.queryXMatch(). To start, let's find 2MASS, SDSS and WISE data for one of the sources in our catalog End of explanation """ # enter your code here! """ Explanation: Exercise Explore some of the other catalogs that are available in the getPhotometry code End of explanation """ # search for SIMBAD sources around the first coordinate in our table srch = spdb.querySimbad(db['COORDINATES'].iloc[0],radius=5*u.arcminute) srch # see what information we get from this srch.keys() # not all of these sources are what we want, so we can reject by object type srch = spdb.querySimbad(db['COORDINATES'].iloc[0],radius=5*u.arcminute,reject_type='Galaxy') srch # we can also return the nearest soruce to our coordinate srch = spdb.querySimbad(db['COORDINATES'].iloc[0],radius=5*u.arcminute,nearest=True) srch # we can also search by the name of the source srch = spdb.querySimbad('G 158-27',isname=True) srch # there is also a slightly reformated version of the output that can be returned srch = spdb.querySimbad(db['COORDINATES'].iloc[0],radius=5*u.arcminute,clean=True) srch """ Explanation: Querying SIMBAD The splat.database.querySimbad() function searches specifically on the Simbad database, and looks a lot like splat.database.getPhotometry() End of explanation """ # let's reload our catalog db = pandas.read_csv(splat.SPLAT_PATH+splat.TUTORIAL_FOLDER+'terrien2015_radec.csv') db = spdb.prepDB(db) db # let's get all the 2MASS data for this catalog - it's pretty fast! db2 = spdb.queryXMatch(db,radius=30.*u.arcsec,catalog='2MASS') db2 # maybe we want only a few select columns; we can use the pre-select versions db2 = spdb.queryXMatch(db,radius=30.*u.arcsec,catalog='2MASS',use_select_columns=True) db2 # we can also specific the columns we want to keep # as long as they are among the columns returned by the catalog # note that we've dropped the 2MASS prefix # one of these columns won't work and will throw up a warning select_columns = ['Jmag','e_Jmag','Hmag','e_Hmag','Kmag','e_Kmag','JUNK'] db2 = spdb.queryXMatch(db,radius=30.*u.arcsec,catalog='2MASS',select_columns=select_columns,use_select_columns=False) db2 # we can also query Simbad db2 = spdb.queryXMatch(db,radius=30.*u.arcsec,catalog='SIMBAD') db2 # we can also query other Vizier catalogs # let's again look at the TESS Input Catalog (TIC) of Stassun et al. 2019 # I've changed the name of the catalog prefix to make my columns cleaner cat = 'IV/38/tic' db2 = spdb.queryXMatch(db,radius=30.*u.arcsec,catalog=cat,prefix='TIC') db2 # the great thing about queryXMatch is that searches to multiple catalogs # can be strung together to produce an overall dataset db2 = copy.deepcopy(db) for cat in ['SDSS','2MASS','ALLWISE','GAIA-EDR3']: db2 = spdb.queryXMatch(db2,catalog=cat,radius=30*u.arcsec) db2 # lots of columns! print(list(db2.columns)) # now we can generate some absolute magnitudes and colors magnitudes = ['SDSS_gmag','SDSS_rmag','SDSS_imag','SDSS_zmag','GAIA-EDR3_phot_g_mean_mag','GAIA-EDR3_phot_bp_mean_mag','GAIA-EDR3_phot_rp_mean_mag','2MASS_Jmag','2MASS_Hmag','2MASS_Kmag','ALLWISE_W1mag','ALLWISE_W2mag','ALLWISE_W3mag','ALLWISE_W4mag'] for i,m in enumerate(magnitudes): db2['ABSOLUTE_{}'.format(m)] = db2[m]-5.*np.log10(db2['GAIA-EDR3_parallax']/100) for m2 in magnitudes[(i+1):]: db2['{}-{}'.format(m,m2)] = db2[m]-db2[m2] print(list(db2.columns[-100:])) # display some color-color and color-magnitude plots combinations = [ ['ABSOLUTE_GAIA-EDR3_phot_g_mean_mag','GAIA-EDR3_phot_bp_mean_mag-GAIA-EDR3_phot_rp_mean_mag'], ['ABSOLUTE_SDSS_imag','SDSS_imag-SDSS_zmag'], ['ABSOLUTE_2MASS_Jmag','2MASS_Jmag-2MASS_Kmag'], ['ABSOLUTE_ALLWISE_W2mag','2MASS_Jmag-ALLWISE_W2mag'], ['2MASS_Jmag-2MASS_Kmag','SDSS_imag-SDSS_zmag'], ['2MASS_Jmag-ALLWISE_W2mag','SDSS_rmag-2MASS_Kmag'], ] fig, axs = plt.subplots(6,figsize=[5,15]) for i,c in enumerate(combinations): axs[i].plot(db2[c[1]],db2[c[0]],'o',alpha=0.5) axs[i].set_xlabel(c[1]) axs[i].set_ylabel(c[0]) axs[i].set_xlim(np.nanquantile(db2[c[1]],[0.05,0.95])) axs[i].set_ylim(np.nanquantile(db2[c[0]],[0.95,0.05])) fig.tight_layout() """ Explanation: Query a large collection of sources: queryXMatch Each of these methods is fine for individual sources, but can be slow for a large list of objects (like our sample database!). Fortunately, the astroquery xmatch function is well suited to this case, and SPLAT as a wrapper for this called splat.database.queryXMatch(). In this case, you input the entire table, and as long as DESIGNATION or RA and DEC columns are provided, it will return the closest match to each source in the catalog End of explanation """
Xero-Hige/Notebooks
Algoritmos I/2018-1C/clase-09-04.ipynb
gpl-3.0
Image(filename='./clase-09-04_images/i1.jpg') """ Explanation: La Magia de la television Capitulo 1: La television argentina es un template gigante Parte 0: Repaso general de secuencias | |Cadenas|Tuplas|Listas| |:---|:---|:---|:---| |Acceso por indice|Si|Si|Si| |Recorrer por indices|Si|Si|Si| |Recorrer por elemento|Si|Si|Si| |Elementos|Caracteres|Cualquier cosa|Cualquier cosa| |Mutabilidad|Inmutables|Inmutables|Mutables| |Operador + (concatenacion)|Copia|Copia|Copia| |Slices|Copia|Copia|Copia| |Append|No existe|No existe|Agrega (Modifica)| |Buscar un elemento|Si|Si|Si| Parte 1: Simona y el narcisismo en tv End of explanation """ si_si_simona = """Si te vas yo voy con vos a algún lugar Si jugás yo tengo ganas de jugar Si te quedas yo me quedo Y si te alejas yo me muero Soy quien soy Si soy algo distraída que mas da Puede ser que sin querer me fui a soñar Si sonríes yo sonrío Si me miras yo suspiro Soy quien soy Si, si, si Simona si Simona es así Simona Si, si, si Simona si Simona es así Simona (Si, si, si) Simona (Si, si, si) Simona Si soy algo distraída que mas da Puede ser que sin querer me fui a soñar Si sonríes yo sonrío Si me miras yo suspiro Soy quien soy Si, si, si Simona si Simona es así Simona Si, si, si Simona si Simona es así Simona Simona Simona, si Si sonríes yo sonrío Si me mirras yo suspiro Soy quien soy Si, si, si Simona si Simona es así Simona Si, si, si Simona si Simona es así Simona Si, si, si Simona si Simona es así Simona Si, si, si Simona si Simona es así Simona (Simona, Simona) Simona (Simona, Simona) Simona""" """ Explanation: En psicologia probablemente se harian un festin analizando estas canciones, la protagonista se nombra a si misma tantas veces que no deja lugar a dudas de quien es el programa. Aplicando lo que sabemos de cadenas y secuencias en general, vamos a escribir un poco de codigo para poder ponerle numeros a esta afirmacion, contando cuantas veces dicen "Simona" los temas de Simona. Si Si Simona End of explanation """ simona_va = """Es un lindo día para pedir un deseo No me importa si se cumple o no Es un lindo día para jugarnos enteros Vamos a cantar una canción Amanece más temprano cuando quiero Porque dentro mío brilla el sol Al final siempre consigo lo que quiero Por que lo hago con amor Solo hay que cruzar bien los dedos Y desear que pase con todo el corazón Vamos a cubrirte los miedos Vamos que ya llega lo mejor Simona va, Simona va Andando se hace el camino Yo manejo mi destino Simona va, Simona va Si piso dejo mi huella Voy a alcanzar las estrellas Ella va, va, va, viene y va Es un lindo dia para hacer algo bien bueno Disfrutando de la sensacion De animarse aunque no te salga perfecto Cada vez ira mejor [?] cuando siento Que mañana voy a verte a vos Porque yo siempre consigo lo que quiero Nadie me dice que no Solo hay que cruzar bien los dedos Y desear que pase con todo el corazón Vamos sacudite los miedos Vamos que ya llega lo mejor Simona va, Simona va Andando se hace el camino Yo manejo mi destino Simona va, Simona va Si piso dejo mi huella Voy a alcanzar las estrellas Ella va, va, va, viene y va Ya va, yo tengo mi tiempo Are you ready for funky? Verás yo voy con lo puesto Como no? No da que no seas sincero Yo no, no le tengo miedo a na na na na na Simona va, Simona va Andando se hace el camino Yo manejo mi destino Simona va, Simona va Si piso dejo mi huella Voy a alcanzar las estrellas Ella va, va, va Simona va, Simona va Andando se hace el camino Yo manejo mi destino Simona va, Simona va Si piso dejo mi huella Voy a alcanzar las estrellas Ella va, va, va, viene y va""" """ Explanation: Simona Va End of explanation """ soy_como_soy = """Soy especial A veces no me entienden, es normal Yo digo siempre lo que pienso Aunque te caiga mal Ya vez mi personalidad Tengo la música en la sangre prefiero bailar No es necesario interpretar, adivinar Soy lo que siento Soy Simona Cantar mi corazón ilusiona Mi sueño voy de a poco alcanzando Y no puedo dejar de pensar en tu amor Cada vez que un recuerdo se asoma Intento al menos no ser tan obvia Y que no te des cuenta que muero por vos Soy como soy pero mi amor Es mas lindo cuando somos dos Vuelvo a empezar No se porque doy tantas vueltas Si en verdad Tu amor es todo lo que quiero Me cuesta tanto disimular Ya vez mi personalidad Tengo la música en la sangre prefiero bailar No es necesario interpretar, adivinar Soy lo que siento Soy Simona Cantar mi corazón ilusiona Mi sueño voy de a poco alcanzando Y no puedo dejar de pensar en tu amor Cada vez que un recuerdo se asoma Intento al menos no ser tan obvia Y que no te des cuenta que muero por vos Soy como soy, pero mi amor Es mas lindo cuando somos dos (Cuando somos dos) (Es mas lindo cuando somos dos) Soy Simona Cantar mi corazón ilusiona Mi sueño voy de a poco alcanzando Y no puedo dejar de pensar en tu amor Cada vez que un recuerdo se asoma (se asoma) Intento al menos no ser tan obvia Y que no te des cuenta que muero por vos Soy como soy, pero mi amor Es mas lindo cuando somos dos""" """ Explanation: Soy Como Soy End of explanation """ dir("") """ Explanation: Metodos del tipo cadena Por ahora los metodos son las funciones que puedo llamar para un tipo de datos dado, utilizando . . La forma de verlos todos es utilizando la funcion dir End of explanation """ help("".find) """ Explanation: OJO: Notar que hay cosas que arrancan con __, eso nos quiere decir que no debemos tocarlo por ningun motivo (Mas sobre esto algunas clases mas adelante) Ahora para saber ya la documentacion especifica del metodo que queremos usar, podemos usar help de la forma: End of explanation """ def buscar_todas(secuencia,sub_secuencia): """ Recibe una secuencia, devuelve una lista con los indices de todas las apariciones de la sub_secuencia dentro de la secuencia original. """ ocurrencias = [] anterior = secuencia.find(sub_secuencia) while anterior != -1: ocurrencias.append(anterior) anterior = secuencia.find(sub_secuencia , anterior+1) return ocurrencias # Podemos probar que la funcion se comporta como esperamos # Si algo de esto imprime False, claramente no anda print ("Buscar devuelve vacio si no encuentra :",buscar_todas("Hola","pp") == [] ) print ("Buscar devuelve a :",buscar_todas("Hola","Hola") == [0] ) print("\n"*2) # Ahora a contar print("Apariciones de Simona en 'Si Si Simona': ",len(buscar_todas(si_si_simona,"Simona"))) print("Apariciones de Simona en 'Simona va': ",len(buscar_todas(simona_va,"Simona"))) print("Apariciones de Simona en 'Soy como soy': ",len(buscar_todas(soy_como_soy,"Simona"))) """ Explanation: Si bien quiero solo contar las apariciones, podria hacer una funcion que me devuelva las apariciones y contar cuantos elementos me devolvio. De esa forma, tengo una funcion que sirve para mas de un contexto. Dado que todo lo que vamos a usar son operaciones de secuencias en gral, podemos nombrar la funcion de forma general[1] End of explanation """ palabras = si_si_simona.split(" ") for i in range(len (palabras)): if palabras[i] == "Simona": palabras[i] = "Ramona" print(" ".join(palabras)) """ Explanation: Discusiones importantes para recordar: * Por que find devuelve -1 y no otra cosa? * Devolver una lista o una tupla? * Usar internamente una lista o una tupla? Y si tengo que devolver una tupla? Tarea para el lector: * Probar la validez o no de la afirmacion [1] (Ayuda: probar usando listas) Cosas no tan importantes a modo de conclusion: * Notar que hasta en las canciones que no tienen su nombre en el titulo se nombra * Queda entonces demostrado lo que sea que se supone que haya querido demostrar con esto Parte 2: Que hacemos si nos cierran este antro? ¿Que pasa ahora si tienen que terminar la novela por problemas con los actores y hacer una nueva? Claramente alguien que escribe 34 veces el nombre de la protagonista en la letra de una cancion no tiene mucha imaginacion, asi que probablemente cambien los nombres de las personas y sigan con lo mismo. Hagamos algo que pueda reemplazar el nombre de Simona por el de una nueva protagonista en las canciones. Version usando Split + Join End of explanation """ partes_cancion = simona_va.split("Simona") cancion_nueva = "Ramona".join(partes_cancion) print(cancion_nueva) """ Explanation: Version abusando de Split y Join End of explanation """ print("Ramona".join(si_si_simona.split("Simona"))) """ Explanation: Ahora en una sola linea End of explanation """ template = si_si_simona.replace("Simona","{0}") print(template) """ Explanation: Version haciendo templates con format strings Supongamos que es bastante comun esto de solo cambiar el nombre, andar cortando y haciendo copias de listas, cadenas o lo que sea, no es como una idea muy copada. Usando cadenas con formato, se puede hacer mas amigable. Paso 1: Reemplazar todas las apariciones de Simona por '{0}' para generar el template (usamos replace porque ya viene en Python y no tengo ganas de hacerlo a mano) End of explanation """ print(template.format("Ramona")) """ Explanation: Usando el template que generamos, ahora podemos usar format para obtener nuestras multiples versiones de la cancion End of explanation """ "Cuando vengo digo {} y cuando me voy digo {}".format("hola","chau") "Cuando vengo digo {1} y cuando me voy digo {0}".format("hola","chau") "Cuando vengo digo {1} y cuando me voy digo {1}".format("hola","chau") """ Explanation: Format Strings (Cadenas con formato) Las cadenas con formato son de la forma blablabla {} blablabla donde {} luego se va a reemplazar por el/los valores que le pasamos como parametro al metodo format. En el ejemplo anterior, utilizamos {0}, porque si no especificamos nada, asume que cada {} corresponde a un parametro distinto. En este caso, el 0 representa al primer parametro. End of explanation """ def obtener_nueva_premisa( nombre_protagonista_femenino, barrio_del_conurbano, nombre_protagonista_masculino, razon_de_no_ser_rica, razon_de_ser_rico, razon_para_ahora_ser_rica): """Devuelve una cadena con la premisa para una nueva y exitosa novela argentina, dados los datos pasados como parametro.""" return """Ella es {}, una mucama que vive en {}, y esta enamorada de su jefe {}. Su amor no puede ser porque ella es {} y el es {}. Pero todo cambia cuando ella descubre que es {} y su amor florece (porque aparentemente no existe el amor en la clase media).""".format( nombre_protagonista_femenino, barrio_del_conurbano, nombre_protagonista_masculino, razon_de_no_ser_rica, razon_de_ser_rico, razon_para_ahora_ser_rica ) print(obtener_nueva_premisa("Ramona","Quilmes","Esteban","la hija del carnicero","el hijo de Barack Obama","una Rockefeller")) """ Explanation: Ahora con esto, podemos hasta hacer una funcion hermosa que nos genere premisas de novelas completamente ~~genericas~~ novedosas. End of explanation """ def obtener_nueva_premisa( nombre_protagonista_femenino, barrio_del_conurbano, nombre_protagonista_masculino, razon_de_no_ser_rica, razon_de_ser_rico, razon_para_ahora_ser_rica): """Devuelve una cadena con la premisa para una nueva y exitosa novela argentina, dados los datos pasados como parametro.""" return f"""Ella es {nombre_protagonista_femenino}, una mucama que vive en {barrio_del_conurbano}. Ella esta enamorada de su jefe {nombre_protagonista_masculino}, pero su amor no puede ser porque ella es {razon_de_no_ser_rica} y el es {razon_de_ser_rico}. Pero todo cambia cuando ella descubre que es {razon_para_ahora_ser_rica} y su amor florece (porque aparentemente no existe el amor en la clase media).""" print(obtener_nueva_premisa("Leona","Tigre","Alberto","una persona de bajos ingresos","mucho muy rico","la ganadora del gordo de navidad")) """ Explanation: Desde Python 3.6 en adelante, hay una forma mucho mas linda de hacer esto, ya que mejora bastante la legibilidad (notar que en el caso anterior no tengo idea de a que parametro representa cada {} a menos que vaya contando, y para mas de un parametro, poner todo con numeros es bastante molesto) End of explanation """ cantidad_a = 10 cantidad_b = 7 f"Si tengo {cantidad_a} manzanas, y me como {cantidad_b}, cuantas me queda? Rta:({cantidad_a - cantidad_b})" """ Explanation: Para poder lograr este efecto, las cadenas deben tener una letra f justo antes de las comillas al inicio y entre llaves expresiones. Y digo expresiones, porque esto vale: End of explanation """ Image(filename='./clase-09-04_images/i2.jpg') """ Explanation: Parte 3: Despues de las 12, azufre y queso tienen las mismas letras aparentemente End of explanation """ def imprimir_soluciones_posibles(incognita): largo = len(incognita) #Lo vamos a usar varias veces, lo "calculamos" una sola #Recorrido en sentido horario for i in range(largo): for j in range(i,i+largo): print(incognita[j % largo],end="") print() #Recorrido en sentido anti-horario for i in range(largo): for j in range( i , i-largo , -1 ): print(incognita[j % largo],end="") print() imprimir_soluciones_posibles("freazu") """ Explanation: Mas de uno se quedo estudiando hasta tarde y se topó con estos programas donde hay que adivinar que palabra se forma con esas letras. Si bien las reglas dicen que solo se pueden formar palabras conectando letras de celdas contiguas, el 90% de la gente que llama cree que la respuesta es "queso", "mozzarela" o "Estambul" por alguna razon. Es bastante evidente que la respuesta ~~es azufre~~ se encuentra en alguna rotacion de "freazu" en sentido horario o anti-horario. Escribamos codigo que nos imprima todas las posibles rotaciones de una cadena a ver si encontramos la respuesta End of explanation """
marfeljoergsen/crypto-trading-scripts
testing/single_stock_example.ipynb
mit
import pyfolio as pf %matplotlib inline # silence warnings import warnings warnings.filterwarnings('ignore') """ Explanation: Single stock analysis example in pyfolio Here's a simple example where we produce a set of plots, called a tear sheet, for a single stock. Import pyfolio and matplotlib End of explanation """ stock_rets = pf.utils.get_symbol_rets('FB') """ Explanation: Fetch the daily returns for a stock End of explanation """ pf.create_returns_tear_sheet(stock_rets, live_start_date='2015-12-1') """ Explanation: Create a returns tear sheet for the single stock This will show charts and analysis about returns of the single stock. End of explanation """
mnschmit/LMU-Syntax-nat-rlicher-Sprachen
04-notebook.ipynb
apache-2.0
grammar1 = """ S -> NP VP NP -> DET N DET -> "der" | "die" | "das" N -> "Mann" | "Frau" | "Buch" VP -> V NP NP V -> "gibt" | "schenkt" """ """ Explanation: Übungsblatt 4 Präsenzaufgaben Aufgabe 1 &nbsp;&nbsp;&nbsp; Eine erste (Phrasenstruktur-)Grammatik Werfen Sie einen Blick auf die folgende sehr einfache kontextfreie Grammatik und erklären Sie deren Funktionsweise. End of explanation """ test_sentences = [ "der Mann gibt der Frau das Buch" ] """ Explanation: Sammeln Sie Sätze, die als grammatisch erkannt werden sollten, am besten in einer Liste. End of explanation """ import nltk from IPython.display import display import sys def test_grammar(grammar, sentences): cfg = nltk.CFG.fromstring(grammar) rd_parser = nltk.RecursiveDescentParser(cfg) for i, sent in enumerate(sentences, 1): print("Satz {}: {}".format(i, sent)) results = rd_parser.parse(sent.split()) analyzed = False for tree in results: tree.pretty_print(unicodelines=True) # tree.draw() oder display(tree) analyzed = True if not analyzed: print("Keine Analyse möglich", file=sys.stderr) """ Explanation: Die folgende Funktion kann Ihnen helfen, eine Reihe von Sätzen zu analysieren. Je nach Ihrem Geschmack können Sie Zeile 14 ggf. anpassen. End of explanation """ test_grammar(grammar1, test_sentences) """ Explanation: Führen Sie den Test jetzt für grammar1 aus! End of explanation """ test_sentences.extend([ "der Mann schläft", "das Buch gefällt der Frau", "die Frau kennt das Buch" ]) grammar2 = """ S -> NP VP NP -> DET N DET -> "der" | "die" | "das" N -> "Mann" | "Frau" | "Buch" VP -> V NP NP V -> "gibt" | "schenkt" """ test_grammar(grammar2, test_sentences) """ Explanation: Aufgabe 2 &nbsp;&nbsp;&nbsp; Ein- und zweistellige Verben Bis jetzt akzeptiert die Grammatik in grammar1 lediglich dreistellige Verben. Erweitern Sie sie so, dass auch Verben mit weniger als zwei Objekten korrekte Verbalphrasen bilden können. Folgende Sätze sollten akzeptiert werden: End of explanation """ test_sentences.extend([ "die kluge schöne Frau kennt das Buch", "der schöne kluge Mann gibt der Frau das dicke Buch", "das dicke schöne kluge Buch schläft" ]) grammar3 = """ S -> NP VP NP -> DET N DET -> "der" | "die" | "das" N -> "Mann" | "Frau" | "Buch" VP -> V NP NP V -> "gibt" | "schenkt" """ test_grammar(grammar3, test_sentences) """ Explanation: Aufgabe 3 &nbsp;&nbsp;&nbsp; Beliebig lange Phrasen Erweitern Sie die Grammatik nun derart, dass Nominalphrasen auch Adjektive enthalten dürfen – und zwar beliebig viele. Beispiele: End of explanation """ test_sentences.extend([ "der Mann kennt Chomsky", "Marie gibt Fritz das Buch" ]) """ Explanation: Hausaufgaben Aufgabe 4 &nbsp;&nbsp;&nbsp; Eigennamen Eigennamen können auch ohne Artikel eine Nominalphrase bilden. Erweitern Sie die Grammatik entsprechend. Folgende Sätze sollten korrekt analysiert werden: End of explanation """ negative_examples = [ "Mann gibt Frau Buch", "Mann schläft" ] grammar4 = """ S -> NP VP NP -> DET N DET -> "der" | "die" | "das" N -> "Mann" | "Frau" | "Buch" VP -> V NP NP V -> "gibt" | "schenkt" """ test_grammar(grammar4, test_sentences) """ Explanation: Stellen Sie außerdem sicher, dass folgende Sätze KEINE Analyse liefern! End of explanation """ test_sentences.extend([ "der Mann schläft neben dem Buch", "die Frau kennt das dicke Buch über Chomsky", "die Frau schenkt dem Mann das Buch auf dem Tisch" ]) """ Explanation: Aufgabe 5 &nbsp;&nbsp;&nbsp; Präpositionalphrasen Erweitern Sie die Grammatik nun derart, dass sowohl Nominalphrasen als auch Verbalphrasen durch Präpositionalphrasen modifiziert werden können. Erkennen Sie die Ambiguität von Übungsblatt 1 wieder? Folgende Sätze sollten akzeptiert werden: End of explanation """ grammar5 = """ S -> NP VP NP -> DET N DET -> "der" | "die" | "das" N -> "Mann" | "Frau" | "Buch" VP -> V NP NP V -> "gibt" | "schenkt" """ test_grammar(grammar5, test_sentences) """ Explanation: Beachten Sie, dass die Form des Artikels dem und das Nomen Tisch auch noch als lexikalische Regeln ergänzt werden müssen. End of explanation """
tensorflow/docs-l10n
site/en-snapshot/lattice/tutorials/custom_estimators.ipynb
apache-2.0
#@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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2020 The TensorFlow Authors. End of explanation """ #@test {"skip": true} !pip install tensorflow-lattice """ Explanation: TF Lattice Custom Estimators <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/lattice/tutorials/custom_estimators"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/lattice/blob/master/docs/tutorials/custom_estimators.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/lattice/blob/master/docs/tutorials/custom_estimators.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/lattice/docs/tutorials/custom_estimators.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> Warning: Estimators are not recommended for new code. Estimators run v1. Session-style code which is more difficult to write correctly, and can behave unexpectedly, especially when combined with TF 2 code. Estimators do fall under our [compatibility guarantees] (https://tensorflow.org/guide/versions), but they will not receive any additional features, and there will be no fixes other than to security vulnerabilities. See the migration guide for details. Overview You can use custom estimators to create arbitrarily monotonic models using TFL layers. This guide outlines the steps needed to create such estimators. Setup Installing TF Lattice package: End of explanation """ import tensorflow as tf import logging import numpy as np import pandas as pd import sys import tensorflow_lattice as tfl from tensorflow import feature_column as fc from tensorflow_estimator.python.estimator.canned import optimizers from tensorflow_estimator.python.estimator.head import binary_class_head logging.disable(sys.maxsize) """ Explanation: Importing required packages: End of explanation """ csv_file = tf.keras.utils.get_file( 'heart.csv', 'http://storage.googleapis.com/download.tensorflow.org/data/heart.csv') df = pd.read_csv(csv_file) target = df.pop('target') train_size = int(len(df) * 0.8) train_x = df[:train_size] train_y = target[:train_size] test_x = df[train_size:] test_y = target[train_size:] df.head() """ Explanation: Downloading the UCI Statlog (Heart) dataset: End of explanation """ LEARNING_RATE = 0.1 BATCH_SIZE = 128 NUM_EPOCHS = 1000 """ Explanation: Setting the default values used for training in this guide: End of explanation """ # Feature columns. # - age # - sex # - ca number of major vessels (0-3) colored by flourosopy # - thal 3 = normal; 6 = fixed defect; 7 = reversable defect feature_columns = [ fc.numeric_column('age', default_value=-1), fc.categorical_column_with_vocabulary_list('sex', [0, 1]), fc.numeric_column('ca'), fc.categorical_column_with_vocabulary_list( 'thal', ['normal', 'fixed', 'reversible']), ] """ Explanation: Feature Columns As for any other TF estimator, data needs to be passed to the estimator, which is typically via an input_fn and parsed using FeatureColumns. End of explanation """ train_input_fn = tf.compat.v1.estimator.inputs.pandas_input_fn( x=train_x, y=train_y, shuffle=True, batch_size=BATCH_SIZE, num_epochs=NUM_EPOCHS, num_threads=1) test_input_fn = tf.compat.v1.estimator.inputs.pandas_input_fn( x=test_x, y=test_y, shuffle=False, batch_size=BATCH_SIZE, num_epochs=1, num_threads=1) """ Explanation: Note that categorical features do not need to be wrapped by a dense feature column, since tfl.laysers.CategoricalCalibration layer can directly consume category indices. Creating input_fn As for any other estimator, you can use input_fn to feed data to the model for training and evaluation. End of explanation """ def model_fn(features, labels, mode, config): """model_fn for the custom estimator.""" del config input_tensors = tfl.estimators.transform_features(features, feature_columns) inputs = { key: tf.keras.layers.Input(shape=(1,), name=key) for key in input_tensors } lattice_sizes = [3, 2, 2, 2] lattice_monotonicities = ['increasing', 'none', 'increasing', 'increasing'] lattice_input = tf.keras.layers.Concatenate(axis=1)([ tfl.layers.PWLCalibration( input_keypoints=np.linspace(10, 100, num=8, dtype=np.float32), # The output range of the calibrator should be the input range of # the following lattice dimension. output_min=0.0, output_max=lattice_sizes[0] - 1.0, monotonicity='increasing', )(inputs['age']), tfl.layers.CategoricalCalibration( # Number of categories including any missing/default category. num_buckets=2, output_min=0.0, output_max=lattice_sizes[1] - 1.0, )(inputs['sex']), tfl.layers.PWLCalibration( input_keypoints=[0.0, 1.0, 2.0, 3.0], output_min=0.0, output_max=lattice_sizes[0] - 1.0, # You can specify TFL regularizers as tuple # ('regularizer name', l1, l2). kernel_regularizer=('hessian', 0.0, 1e-4), monotonicity='increasing', )(inputs['ca']), tfl.layers.CategoricalCalibration( num_buckets=3, output_min=0.0, output_max=lattice_sizes[1] - 1.0, # Categorical monotonicity can be partial order. # (i, j) indicates that we must have output(i) <= output(j). # Make sure to set the lattice monotonicity to 'increasing' for this # dimension. monotonicities=[(0, 1), (0, 2)], )(inputs['thal']), ]) output = tfl.layers.Lattice( lattice_sizes=lattice_sizes, monotonicities=lattice_monotonicities)( lattice_input) training = (mode == tf.estimator.ModeKeys.TRAIN) model = tf.keras.Model(inputs=inputs, outputs=output) logits = model(input_tensors, training=training) if training: optimizer = optimizers.get_optimizer_instance_v2('Adagrad', LEARNING_RATE) else: optimizer = None head = binary_class_head.BinaryClassHead() return head.create_estimator_spec( features=features, mode=mode, labels=labels, optimizer=optimizer, logits=logits, trainable_variables=model.trainable_variables, update_ops=model.updates) """ Explanation: Creating model_fn There are several ways to create a custom estimator. Here we will construct a model_fn that calls a Keras model on the parsed input tensors. To parse the input features, you can use tf.feature_column.input_layer, tf.keras.layers.DenseFeatures, or tfl.estimators.transform_features. If you use the latter, you will not need to wrap categorical features with dense feature columns, and the resulting tensors will not be concatenated, which makes it easier to use the features in the calibration layers. To construct a model, you can mix and match TFL layers or any other Keras layers. Here we create a calibrated lattice Keras model out of TFL layers and impose several monotonicity constraints. We then use the Keras model to create the custom estimator. End of explanation """ estimator = tf.estimator.Estimator(model_fn=model_fn) estimator.train(input_fn=train_input_fn) results = estimator.evaluate(input_fn=test_input_fn) print('AUC: {}'.format(results['auc'])) """ Explanation: Training and Estimator Using the model_fn we can create and train the estimator. End of explanation """
tensorflow/docs-l10n
site/zh-cn/addons/tutorials/optimizers_conditionalgradient.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 # 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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2020 The TensorFlow Authors. End of explanation """ !pip install -U tensorflow-addons import tensorflow as tf import tensorflow_addons as tfa from matplotlib import pyplot as plt # Hyperparameters batch_size=64 epochs=10 """ Explanation: TensorFlow Addons 优化器:ConditionalGradient <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://tensorflow.google.cn/addons/tutorials/optimizers_conditionalgradient"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png">在 TensorFlow.org 上查看</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/addons/tutorials/optimizers_conditionalgradient.ipynb"><img src="https://tensorflow.google.cn/images/colab_logo_32px.png">在 Google Colab 中运行</a></td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/zh-cn/addons/tutorials/optimizers_conditionalgradient.ipynb"><img src="https://tensorflow.google.cn/images/GitHub-Mark-32px.png">在 GitHub 上查看源代码</a></td> <td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/zh-cn/addons/tutorials/optimizers_conditionalgradient.ipynb"><img src="https://tensorflow.google.cn/images/download_logo_32px.png">下载笔记本</a></td> </table> 概述 此笔记本将演示如何使用 Addons 软件包中的条件梯度优化器。 ConditionalGradient 由于潜在的正则化效果,约束神经网络的参数已被证明对训练有益。通常,参数通过软惩罚(从不保证约束满足)或通过投影运算(计算资源消耗大)进行约束。另一方面,条件梯度 (CG) 优化器可严格执行约束,而无需消耗资源的投影步骤。它通过最大程度减小约束集中目标的线性逼近来工作。在此笔记本中,我们通过 MNIST 数据集上的 CG 优化器演示弗罗宾尼斯范数约束的应用。CG 现在可以作为 Tensorflow API 提供。有关优化器的更多详细信息,请参阅 https://arxiv.org/pdf/1803.06453.pdf 设置 End of explanation """ model_1 = tf.keras.Sequential([ tf.keras.layers.Dense(64, input_shape=(784,), activation='relu', name='dense_1'), tf.keras.layers.Dense(64, activation='relu', name='dense_2'), tf.keras.layers.Dense(10, activation='softmax', name='predictions'), ]) """ Explanation: 构建模型 End of explanation """ # Load MNIST dataset as NumPy arrays dataset = {} num_validation = 10000 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # Preprocess the data x_train = x_train.reshape(-1, 784).astype('float32') / 255 x_test = x_test.reshape(-1, 784).astype('float32') / 255 """ Explanation: 准备数据 End of explanation """ def frobenius_norm(m): """This function is to calculate the frobenius norm of the matrix of all layer's weight. Args: m: is a list of weights param for each layers. """ total_reduce_sum = 0 for i in range(len(m)): total_reduce_sum = total_reduce_sum + tf.math.reduce_sum(m[i]**2) norm = total_reduce_sum**0.5 return norm CG_frobenius_norm_of_weight = [] CG_get_weight_norm = tf.keras.callbacks.LambdaCallback( on_epoch_end=lambda batch, logs: CG_frobenius_norm_of_weight.append( frobenius_norm(model_1.trainable_weights).numpy())) """ Explanation: 定义自定义回调函数 End of explanation """ # Compile the model model_1.compile( optimizer=tfa.optimizers.ConditionalGradient( learning_rate=0.99949, lambda_=203), # Utilize TFA optimizer loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) history_cg = model_1.fit( x_train, y_train, batch_size=batch_size, validation_data=(x_test, y_test), epochs=epochs, callbacks=[CG_get_weight_norm]) """ Explanation: 训练和评估:使用 CG 作为优化器 只需用新的 TFA 优化器替换典型的 Keras 优化器 End of explanation """ model_2 = tf.keras.Sequential([ tf.keras.layers.Dense(64, input_shape=(784,), activation='relu', name='dense_1'), tf.keras.layers.Dense(64, activation='relu', name='dense_2'), tf.keras.layers.Dense(10, activation='softmax', name='predictions'), ]) SGD_frobenius_norm_of_weight = [] SGD_get_weight_norm = tf.keras.callbacks.LambdaCallback( on_epoch_end=lambda batch, logs: SGD_frobenius_norm_of_weight.append( frobenius_norm(model_2.trainable_weights).numpy())) # Compile the model model_2.compile( optimizer=tf.keras.optimizers.SGD(0.01), # Utilize SGD optimizer loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) history_sgd = model_2.fit( x_train, y_train, batch_size=batch_size, validation_data=(x_test, y_test), epochs=epochs, callbacks=[SGD_get_weight_norm]) """ Explanation: 训练和评估:使用 SGD 作为优化器 End of explanation """ plt.plot( CG_frobenius_norm_of_weight, color='r', label='CG_frobenius_norm_of_weights') plt.plot( SGD_frobenius_norm_of_weight, color='b', label='SGD_frobenius_norm_of_weights') plt.xlabel('Epoch') plt.ylabel('Frobenius norm of weights') plt.legend(loc=1) """ Explanation: 权重的弗罗宾尼斯范数:CG 与 SGD CG 优化器的当前实现基于弗罗宾尼斯范数,并将弗罗宾尼斯范数视为目标函数中的正则化器。因此,我们将 CG 的正则化效果与尚未采用弗罗宾尼斯范数正则化器的 SGD 优化器进行了比较。 End of explanation """ plt.plot(history_cg.history['accuracy'], color='r', label='CG_train') plt.plot(history_cg.history['val_accuracy'], color='g', label='CG_test') plt.plot(history_sgd.history['accuracy'], color='pink', label='SGD_train') plt.plot(history_sgd.history['val_accuracy'], color='b', label='SGD_test') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend(loc=4) """ Explanation: 训练和验证准确率:CG 与 SGD End of explanation """
SamLau95/nbinteract
docs/notebooks/tutorial/tutorial_interact.ipynb
bsd-3-clause
from ipywidgets import interact """ Explanation: A Simple Webpage In this section, you will create and publish a simple interactive webpage! In Jupyter, create a notebook and name it tutorial.ipynb. Type or paste in the code from this tutorial into the notebook. Using Interact The ipywidgets library provides the simplest way to get started writing interactive documents. Although the library itself has its own documentation, we will provide a quick overview to let you get started as quickly as possible. We start by importing the interact function: End of explanation """ def square(x): return x * x """ Explanation: The interact function takes in a function and produces an interface to call the function with different parameters. End of explanation """ interact(square, x=10); """ Explanation: Pass the square function into interact and specify square's arguments as keyword arguments: End of explanation """ interact(square, x=(0, 100, 10)); """ Explanation: To control the range of values x can take, you can pass in a tuple of the same format as Python's range function: End of explanation """ def friends(name, number): return '{} has {} friends!'.format(name, number) interact(friends, name='Sam', number=(5, 10)); """ Explanation: Notice how dragging the slider changes the input to the square function and automatically updates the output. This is a powerful idea that we will build on for the rest of this tutorial. By using interact, you can build complex widget-based interfaces in a notebook. These widgets will appear in your resulting webpage, giving your page interactivity. Widget Types Notice that interact automatically generates a slider because the argument is numeric. Other types of arguments will generate different types of interfaces. For example, a string will generate a textbox. End of explanation """ interact(friends, name='Sam', number={'One': 1, 'Five': 5, 'Ten': 10}); """ Explanation: And a dictionary will generate a dropdown menu: End of explanation """
rishuatgithub/MLPy
torch/PYTORCH_NOTEBOOKS/00-Crash-Course-Topics/01-Crash-Course-Pandas/04-Groupby.ipynb
apache-2.0
import pandas as pd # Create dataframe data = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'], 'Person':['Sam','Charlie','Amy','Vanessa','Carl','Sarah'], 'Sales':[200,120,340,124,243,350]} df = pd.DataFrame(data) df """ Explanation: <a href='http://www.pieriandata.com'><img src='../Pierian_Data_Logo.png'/></a> <center><em>Copyright Pierian Data</em></center> <center><em>For more information, visit us at <a href='http://www.pieriandata.com'>www.pieriandata.com</a></em></center> Groupby The groupby method allows you to group rows of data together and call aggregate functions End of explanation """ df.groupby('Company') """ Explanation: <strong>Now you can use the .groupby() method to group rows together based off of a column name.<br>For instance let's group based off of Company. This will create a DataFrameGroupBy object:</strong> End of explanation """ by_comp = df.groupby("Company") """ Explanation: You can save this object as a new variable: End of explanation """ by_comp.mean() df.groupby('Company').mean() """ Explanation: And then call aggregate methods off the object: End of explanation """ by_comp.std() by_comp.min() by_comp.max() by_comp.count() by_comp.describe() by_comp.describe().transpose() by_comp.describe().transpose()['GOOG'] """ Explanation: More examples of aggregate methods: End of explanation """
mne-tools/mne-tools.github.io
0.14/_downloads/plot_label_from_stc.ipynb
bsd-3-clause
# Author: Luke Bloy <luke.bloy@gmail.com> # Alex Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.minimum_norm import read_inverse_operator, apply_inverse from mne.datasets import sample print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subjects' fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' subjects_dir = data_path + '/subjects' subject = 'sample' snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Compute a label/ROI based on the peak power between 80 and 120 ms. # The label bankssts-lh is used for the comparison. aparc_label_name = 'bankssts-lh' tmin, tmax = 0.080, 0.120 # Load data evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) src = inverse_operator['src'] # get the source space # Compute inverse solution stc = apply_inverse(evoked, inverse_operator, lambda2, method, pick_ori='normal') # Make an STC in the time interval of interest and take the mean stc_mean = stc.copy().crop(tmin, tmax).mean() # use the stc_mean to generate a functional label # region growing is halted at 60% of the peak value within the # anatomical label / ROI specified by aparc_label_name label = mne.read_labels_from_annot(subject, parc='aparc', subjects_dir=subjects_dir, regexp=aparc_label_name)[0] stc_mean_label = stc_mean.in_label(label) data = np.abs(stc_mean_label.data) stc_mean_label.data[data < 0.6 * np.max(data)] = 0. func_labels, _ = mne.stc_to_label(stc_mean_label, src=src, smooth=True, subjects_dir=subjects_dir, connected=True) # take first as func_labels are ordered based on maximum values in stc func_label = func_labels[0] # load the anatomical ROI for comparison anat_label = mne.read_labels_from_annot(subject, parc='aparc', subjects_dir=subjects_dir, regexp=aparc_label_name)[0] # extract the anatomical time course for each label stc_anat_label = stc.in_label(anat_label) pca_anat = stc.extract_label_time_course(anat_label, src, mode='pca_flip')[0] stc_func_label = stc.in_label(func_label) pca_func = stc.extract_label_time_course(func_label, src, mode='pca_flip')[0] # flip the pca so that the max power between tmin and tmax is positive pca_anat *= np.sign(pca_anat[np.argmax(np.abs(pca_anat))]) pca_func *= np.sign(pca_func[np.argmax(np.abs(pca_anat))]) """ Explanation: Generate a functional label from source estimates Threshold source estimates and produce a functional label. The label is typically the region of interest that contains high values. Here we compare the average time course in the anatomical label obtained by FreeSurfer segmentation and the average time course from the functional label. As expected the time course in the functional label yields higher values. End of explanation """ plt.figure() plt.plot(1e3 * stc_anat_label.times, pca_anat, 'k', label='Anatomical %s' % aparc_label_name) plt.plot(1e3 * stc_func_label.times, pca_func, 'b', label='Functional %s' % aparc_label_name) plt.legend() plt.show() """ Explanation: plot the time courses.... End of explanation """ brain = stc_mean.plot(hemi='lh', subjects_dir=subjects_dir) brain.show_view('lateral') # show both labels brain.add_label(anat_label, borders=True, color='k') brain.add_label(func_label, borders=True, color='b') """ Explanation: plot brain in 3D with PySurfer if available End of explanation """
ellisztamas/faps
docs/tutorials/03_paternity_arrays.ipynb
mit
import faps as fp import numpy as np print("Created using FAPS version {}.".format(fp.__version__)) """ Explanation: Paternity arrays Tom Ellis, March 2017, updated June 2020 End of explanation """ np.random.seed(27) # this ensures you get exactly the same answers as I do. allele_freqs = np.random.uniform(0.3,0.5, 50) mypop = fp.make_parents(4, allele_freqs, family_name='my_population') progeny = fp.make_sibships(mypop, 0, [1,2], 3, 'myprogeny') """ Explanation: Paternity arrays are the what sibship clustering is built on in FAPS. They contain information about the probability that each candidate male is the father of each individual offspring - this is what the FAPS paper refers to as matrix G. This information is stored in a paternityArray object, along with other related information. A paternityArray can either be imported directly, or created from genotype data. This notebook will examine how to: Create a paternityArray from marker data. Examine what information it contains. Read and write a paternityArray to disk, or import a custom paternityArray. Once you have made your paternityArray, the next step is to cluster the individuals in your array into full sibship groups. Note that this tutorial only deals with the case where you have a paternityArray object for a single maternal family. If you have multiple families, you can apply what is here to each one, but you'll have to iterate over those families. See the specific tutorial on that. Creating a paternityArray from genotype data To create a paternityArray from genotype data we need to specficy genotypeArrays for the offspring, mothers and candidate males. Currently only biallelic SNP data are supported. We will illustrate this with a small simulated example again with four adults and six offspring typed at 50 loci. End of explanation """ mum_index = progeny.parent_index('mother', mypop.names) # positions in the mothers in the array of adults mothers = mypop.subset(mum_index) # genotypeArray of the mothers """ Explanation: We need to supply a genotypeArray for the mothers. This needs to have an entry for for every offspring, i.e. six replicates of the mother. End of explanation """ error_rate = 0.0015 patlik = fp.paternity_array( offspring = progeny, mothers = mothers, males= mypop, mu=error_rate) """ Explanation: To create the paternityArray we also need to supply information on the genotyping error rate (mu). In this toy example we know the error rate to be zero. However, in reality this will almost never be true, and moreover, sibship clustering becomes unstable when errors are zero, so we will use a small number for the error rate. End of explanation """ print(patlik.candidates) print(patlik.mothers) print(patlik.offspring) """ Explanation: paternityArray structure Basic attributes A paternityArray inherits information about individuals from found in a genotypeArray. For example, labels of the candidates, mothers and offspring. End of explanation """ patlik.lik_array """ Explanation: Representation of matrix G The FAPS paper began with matrix G that gives probabilities that each individual is sired by each candidate father, or that the true father is absent from the sample. Recall that this matrix had a row for every offspring and a column for every candidate father, plus and additional column for the probability that the father was unsampled, and that these rows sum to one. The relative weight given to these two sections of G is determined by our prior expectation p about what proportion of true fathers were sampled. This section will examine how that is matrix is constructed. The most important part of the paternityArray is the likelihood array, which represent the log likelihood that each candidate male is the true father of each offspring individual. In this case it will be a 6x4 dimensional array with a row for each offspring and a column for each candidate. End of explanation """ patlik.lik_absent """ Explanation: You can see that the log likelihoods of paternity for the first individual are much lower than the other candidates. This individual is the mother, so this makes sense. You can also see that the highest log likelihoods are in the columns for the real fathers (the 2nd column in rows one to three, and the third column in rows four to six). The paternityArray also includes information that the true sire is not in the sample of candidate males. In this case this is not helpful, because we know sampling is complete, but in real examples is seldom the case. By default this is defined as the likelihood of generating the offspring genotypes given the known mothers genotype and alleles drawn from population allele frequencies. Here, values for the six offspring are higher than the likelihoods for the non-sires, indicating that they are no more likely to be the true sire than a random unrelated individual. End of explanation """ patlik.missing_parents = 0.1 """ Explanation: The numbers in the two previous cells are (log) likelihoods, either of paternity, or that the father was missing. These are estimated from the marker data and are not normalised to probabilities. To join these bits of information together, we also need to specify our prior belief about the proportion of fathers you think you sampled based on your domain expertise in the system, which should be a float between 0 and 1. Let's assume that we think we missed 10% of the fathers and set that as an attribute of the paternityArray object: End of explanation """ print(patlik.lik_array.shape) print(patlik.prob_array().shape) """ Explanation: The function prob_array creates the G matrix by multiplying lik_absent by 0.1 and lik_array by 0.9 (i.e. 1-0.1), then normalising the rows to sum to one. This returns a matrix with an extra column than lik_array had. End of explanation """ np.exp(patlik.prob_array()).sum(axis=1) """ Explanation: Note that FAPS is doing this on the log scale under the hood. To check its working, we can check that rows sum to one. End of explanation """ patlik.missing_parents = 0 patlik.prob_array() """ Explanation: If we were sure we really had sampled every single father, we could set the proportion of missing fathers to 0. This will throw a warning urging you to be cautious about that, but will run. We can see that the last column has been set to negative infinity, which is log(0). End of explanation """ patlik = fp.paternity_array( offspring = progeny, mothers = mothers, males= mypop, mu=error_rate, missing_parents=0.1) """ Explanation: You can also set the proportion of missing fathers directly when you create the paternity array. End of explanation """ patlik.selfing_rate=0 patlik.prob_array() """ Explanation: Modifying a paternityArray In the previous example we saw how to set the proportion of missing fathers by changing the attributes of the paternityArray object. There are a few other attributes that can be set that will modify the G matrix before passing this on to cluster offspring into sibships. Selfing rate Often the mother is included in the sample of candidate males, either because you are using the same array for multiple families, or self-fertilisation is a biological possibility. In a lot of cases though the mother cannot simultaneously be the sperm/pollen donor, and it is necessary to set the rate of self-fertilisation to zero (the natural logarithm of zero is negative infinity). This can be done simply by setting the attribute selfing_rate to zero: End of explanation """ patlik.selfing_rate=0.95 patlik.prob_array() """ Explanation: This has set the prior probability of paternity of the mother (column zero above) to negative infinity (i.e log(zero)). You can set any selfing rate between zero and one if you have a good idea of what the value should be and how much it varies. For example, Arabidopsis thaliana selfs most of the time, so we could set a selfing rate of 95%. End of explanation """ patlik.purge = 'my_population_3' patlik.prob_array() """ Explanation: However, notice that despite the strong prior favouring the mother, she still doesn't have the highest probablity of paternity for any offspring. That's because the signal from the genetic markers is so strong that the true fathers still come out on top. Removing individual candidates You can also set likelihoods for particular individuals to zero manually. You might want to do this if you wanted to test the effects of incomplete sampling on your results, or if you had a good reason to suspect that some candidates could not possibly be the sire (for example, if the data are multigenerational, and the candidate was born after the offspring). Let's remove candidate 3: End of explanation """ patlik.purge = ['my_population_0', 'my_population_3'] patlik.prob_array() """ Explanation: This also works using a list of candidates. End of explanation """ patlik.purge = 0.4 patlik.prob_array() """ Explanation: This has removed the first individual (notice that this is identical to the previous example, because in this case the first individual is the mother). Alternatively you can supply a float between zero and one, which will be interpreted as a proportion of the candidates to be removed at random, which can be useful for simulations. End of explanation """ patlik.max_clashes=3 """ Explanation: Reducing the number of candidates You might want to remove candidates who have an a priori very low probability of paternity, for example to reduce the memory requirements of the paternityArray. One simple rule is to exclude any candidates with more than some arbritray number of loci with opposing homozygous genotypes relative to the offspring (you want to allow for a small number, in case there are genotyping errors). This is done with max_clashes. End of explanation """ patlik.clashes """ Explanation: The option max_clashes refers back to a matrix that counts the number of such incompatibilities for each offspring-candidate pair. When you create a paternityArray from genotypeArray objects, this matrix is created automatically ad can be called with: End of explanation """ fp.incompatibilities(mypop, progeny) """ Explanation: If you import a paternityArray object, this isn't automatically generated, but you can recreate this manually with: End of explanation """ patlik = fp.paternity_array( offspring = progeny, mothers = mothers, males= mypop, mu=error_rate, missing_parents=0.1, purge = 'my_population_3', selfing_rate = 0 ) """ Explanation: Notice that this array has a row for each offspring, and a column for each candidate father. The first column is for the mother, which is why everything is zero. Modifying arrays on creation You can also set the attributes we just described by setting them when you create the paternityArray object. For example: End of explanation """ patlik.write('../../data/mypatlik.csv') """ Explanation: Importing a paternityArray Frequently you may wish to save an array and reload it. Otherwise, you may be working with a more exotic system than FAPS currently supports, such as microsatellite markers or a funky ploidy system. In this case you can create your own matrix of paternity likelihoods and import this directly as a paternityArray. Firstly, we can save the array we made before to disk by supplying a path to save to: End of explanation """ patlik = fp.read_paternity_array( path = '../../data/mypatlik.csv', mothers_col=1, likelihood_col=2) """ Explanation: We can reimport it again using read_paternity_array. This function is similar to the function for importing a genotypeArray, and the data need to have a specific structure: Offspring names should be given in the first column Names of the mothers are usually given in the second column. If known for some reason, names of fathers can be given as well. Likelihood information should be given to the right of columns indicating individual or parental names, with candidates' names in the column headers. The final column should specify a likelihood that the true sire of an individual has not been sampled. Usually this is given as the likelihood of drawing the paternal alleles from population allele frequencies. End of explanation """ fp.incompatibilities(mypop, progeny) """ Explanation: Of course, you can of course generate your own paternityArray and import it in the same way. This is especially useful if your study system has some specific marker type or genetic system not supported by FAPS. One caveat with importing data is that the array of opposing homozygous loci is not imported automatically. You can either import this as a separate text file, or you can recreate this as above: End of explanation """
google-research/google-research
graph_sampler/molecule_sampling_demo.ipynb
apache-2.0
# Install graph_sampler !git clone https://github.com/google-research/google-research.git !pip install google-research/graph_sampler from rdkit import Chem import rdkit.Chem.Draw from graph_sampler import molecule_sampler from graph_sampler import stoichiometry import numpy as np """ Explanation: <a href="https://colab.research.google.com/github/google-research/google-research/blob/master/graph_sampler/molecule_sampling_demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Copyright 2022 Google LLC 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 the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. End of explanation """ stoich = stoichiometry.Stoichiometry({'C': 10, 'O': 2, 'N': 3, 'H': 16, 'F': 2, 'O-': 1, 'N+': 1}) assert stoichiometry.is_valid(stoich), 'Cannot form a connected graph with this stoichiometry.' print('Number of heavy atoms:', sum(stoich.counts.values()) - stoich.counts['H']) %%time sampler = molecule_sampler.MoleculeSampler(stoich, relative_precision=0.03, rng_seed=2044365744) weighted_samples = [graph for graph in sampler] stats = sampler.stats() rejector = molecule_sampler.RejectToUniform(weighted_samples, max_importance=stats['max_final_importance'], rng_seed=265580748) uniform_samples = [graph for graph in rejector] print(f'generated {len(weighted_samples)}, kept {len(uniform_samples)}, ' f'estimated total: {stats["estimated_num_graphs"]:.2E} ± ' f'{stats["num_graphs_std_err"]:.2E}') #@title Draw some examples mols = [molecule_sampler.to_mol(g) for g in uniform_samples] Chem.Draw.MolsToGridImage(mols[:8], molsPerRow=4, subImgSize=(200, 140)) """ Explanation: Generating samples from a single stoichiometry End of explanation """ #@title Enumerate valid stoichiometries subject to the given constraint heavy_elements = ['C', 'N', 'O'] num_heavy = 5 # We'll dump stoichiometries, samples, and statistics into a big dictionary. all_data = {} for stoich in stoichiometry.enumerate_stoichiometries(num_heavy, heavy_elements): key = ''.join(stoich.to_element_list()) all_data[key] = {'stoich': stoich} max_key_size = max(len(k) for k in all_data.keys()) print(f'{len(all_data)} stoichiometries') #@title For each stoichiometry, generate samples and estimate the number of molecules for key, data in all_data.items(): sampler = molecule_sampler.MoleculeSampler(data['stoich'], relative_precision=0.2) data['weighted_samples'] = [graph for graph in sampler] stats = sampler.stats() data['stats'] = stats rejector = molecule_sampler.RejectToUniform(data['weighted_samples'], max_importance=stats['max_final_importance']) data['uniform_samples'] = [graph for graph in rejector] print(f'{key:>{max_key_size}}:\tgenerated {len(data["weighted_samples"])},\t' f'kept {len(data["uniform_samples"])},\t' f'estimated total {int(stats["estimated_num_graphs"])} ± {int(stats["num_graphs_std_err"])}') #@title Combine into one big uniform sampling of the whole space bucket_sizes = [data['stats']['estimated_num_graphs'] for data in all_data.values()] sample_sizes = [len(data['uniform_samples']) for data in all_data.values()] base_iters = [data['uniform_samples'] for data in all_data.values()] aggregator = molecule_sampler.AggregateUniformSamples(bucket_sizes, sample_sizes, base_iters) merged_uniform_samples = [graph for graph in aggregator] total_estimate = sum(data['stats']['estimated_num_graphs'] for data in all_data.values()) total_variance = sum(data['stats']['num_graphs_std_err']**2 for data in all_data.values()) total_std = np.sqrt(total_variance) print(f'{len(merged_uniform_samples)} samples after merging, of an estimated ' f'{total_estimate:.1f} ± {total_std:.1f}') #@title Draw some examples mols = [molecule_sampler.to_mol(g) for g in merged_uniform_samples] Chem.Draw.MolsToGridImage(np.random.choice(mols, size=16), molsPerRow=4, subImgSize=(200, 140)) """ Explanation: Combining samples from multiple stoichiometries Here we'll generate random molecules with 5 heavy atoms selected from C, N, and O. These small numbers are chosen just to illustrate the code. In this small an example, you could just enumerate all molecules. For large numbers of heavy atoms selected from a large set, you'd want to parallelize a lot of this. End of explanation """
cliburn/sta-663-2017
notebook/00_Jupyter.ipynb
mit
%lsmagic %%file hello.txt Hello, world This is thing number 1 This is thing number 2 This is thing number 3 %cat hello.txt """ Explanation: Notes on using Jupyter Keyboard Shortcuts General See Help menu for list of keyboard shortcuts For Windows users, the Ctrl key is the equivalent of the Cmd key Cmd-Shift-P: Brings up command palette (or use the toolbar icon) Most useful shortcuts. In EDIT mode ESC: switch to COMMAND mode Tab: auto-complete Shift-Tab: tooltip (e.g. to get function arguments) Cmd-/: toggle commenting of highlighted code In COMMAND mode Return: switch to EDIT mode F: Brings up Find and Replace dialog (toggle option to replace within selected cell or whole notebook) A: Create new cell above B: Create new cell below DD: Delete selected cell(s) M: Switch to Markdown cell Y: Switch to Code cell Shift-Down: Select multiple cells Shift-Up: Select multiple cells Shift-M: Merge selected cells Shift-Return: Execute selected cell(s) Alt-Return: Execute selected cell(s) and insert new cell below Magic commands End of explanation """ ! tail -n3 hello.txt | head -n2 %%bash for i in $(ls); do echo item: $i done """ Explanation: Using shell commands Use ! to run commands in the shell or %%bash to run multi-line commands. End of explanation """ %load_ext rpy2.ipython a, b = 2, 5 %%R -i a,b -o x x <- a:b x """ Explanation: Load extension for R This allows you to execute R code in a cell and pass variables in and out. End of explanation """
UWSEDS/LectureNotes
PreFall2018/07-Exceptions.ipynb
bsd-2-clause
X = [1, 2, 3 a = 4 y = 4*x + 3 def f(): return GARBAGE """ Explanation: When Things Go Wrong: Exceptions and Errors Today we'll cover perhaps one of the most important aspects of using Python: dealing with errors and bugs in code. Three Classes of Errors Types of bugs/errors in code, from the easiest to the most difficult to diagnose: Syntax Errors: Errors where the code is not valid Python (generally easy to fix) Runtime Errors: Errors where syntactically valid code fails to execute (sometimes easy to fix) Semantic Errors: Errors in logic (often very difficult to fix) Syntax Errors Syntax errors are when you write code which is not valid Python. For example: End of explanation """ f() """ Explanation: No error is generated by defining this function. The error doesn't occur until the function is called. End of explanation """ a = 4 something == is wrong print(a) """ Explanation: Note that if your code contains even a single syntax error, none of it will run: End of explanation """ print(Q) a = 'aaa' # blah blah blah x = 1 + int(a) print (x) X = 1 / 0 import numpy as np np.sum([1, 2, 3, 4]) np.sum? x = [1, 2, 3] print(x[100]) """ Explanation: Even though the syntax error appears below the (valid) variable definition, the valid code is not executed. Runtime Errors Runtime errors occur when the code is valid python code, but are errors within the context of the program execution. For example: End of explanation """ spam = "my all-time favorite" eggs = 1 / 0 print(spam) """ Explanation: Unlike Syntax errors, RunTime errors occur during code execution, which means that valid code occuring before the runtime error will execute: End of explanation """ total = 0 for k in ks: total += (-3.0) ** -k / (2 * k + 1) from math import sqrt def approx_pi(nterms=100): ks = np.arange(nterms) ans = sqrt(12) * np.sum([-3.0 ** -k / (2 * k + 1) for k in ks]) if ans < 1: import pdb; pdb.set_trace() return ans approx_pi(1000) """ Explanation: Semantic Errors Semantic errors are perhaps the most insidious errors, and are by far the ones that will take most of your time. Semantic errors occur when the code is syntactically correct, but produces the wrong result. By way of example, imagine you want to write a simple script to approximate the value of $\pi$ according to the following formula: $$ \pi = \sqrt{12} \sum_{k = 0}^{\infty} \frac{(-3)^{-k}}{2k + 1} $$ You might write a function something like this, using numpy's vectorized syntax: End of explanation """ approx_pi(1000) """ Explanation: Looks OK, yes? Let's try it out: End of explanation """ k = 2 (-3.0) ** -k / (2 * k + 1) approx_pi(1000) """ Explanation: Huh. That doesn't look like $\pi$. Maybe we need more terms? End of explanation """ try: print("this block gets executed first") GARBAGE except (ValueError, RuntimeError) as err: print("this block gets executed if there's an error") print (err) print ("I am done!") def f(x): if isinstance(x, int) or isinstance(x, float): return 1.0/x else: raise ValueError("argument must be an int.") f(0) def f(x): try: return 1.0/x except (TypeError, ZeroDivisionError): raise ValueError("Argument must be a non-zero number.") f(0) f('aa') try: print("this block gets executed first") x = 1 / 0 # ZeroDivisionError print("we never get here") except: print("this block gets executed if there's an error") """ Explanation: Nope... it looks like the algorithm simply gives the wrong result. This is a classic example of a semantic error. Question: can you spot the problem? Runtime Errors and Exception Handling Now we'll talk about how to handle RunTime errors (we skip Syntax Errors because they're pretty self-explanatory). Runtime errors can be handled through "exception catching" using try...except statements. Here's a basic example: End of explanation """ def safe_divide(a, b): try: return a / b except: # print("oops, dividing by zero. Returning None.") return None print(safe_divide(15, 3)) print(safe_divide(1, 0)) """ Explanation: Notice that the first block executes up until the point of the Runtime error. Once the error is hit, the except block is executed. One important note: the above clause catches any and all exceptions. It is not generally a good idea to catch-all. Better is to name the precise exception you expect: End of explanation """ safe_divide(15, 3) """ Explanation: But there's a problem here: this is a catch-all exception, and will sometimes give us misleading information. For example: End of explanation """ def better_safe_divide(a, b): try: return a / b except ZeroDivisionError: print("oops, dividing by zero. Returning None.") return None better_safe_divide(15, 0) better_safe_divide(15, 'three') """ Explanation: Our program tells us we're dividing by zero, but we aren't! This is one reason you should almost never use a catch-all try..except statement, but instead specify the errors you're trying to catch: End of explanation """ def even_better_safe_divide(a, b): try: return a / b except ZeroDivisionError: print("oops, dividing by zero. Returning None.") return None except TypeError: print("incompatible types. Returning None") return None even_better_safe_divide(15, 3) even_better_safe_divide(15, 0) even_better_safe_divide(15, 'three') """ Explanation: This also allows you to specify different behaviors for different exceptions: End of explanation """ import os # the "os" module has useful operating system stuff def read_file(filename): if not os.path.exists(filename): raise ValueError("'{0}' does not exist".format(filename)) f = open(filename) result = f.read() f.close() return result """ Explanation: Remember this lesson, and always specify your except statements! I once spent an entire day tracing down a bug in my code which amounted to this. Raising Your Own Exceptions When you write your own code, it's good practice to use the raise keyword to create your own exceptions when the situation calls for it: End of explanation """ %%file tmp.txt this is the contents of the file read_file('tmp.txt') read_file('file.which.does.not.exist') """ Explanation: We'll use IPython's %%file magic to quickly create a text file End of explanation """ class NonExistentFile(RuntimeError): # you can customize exception behavior by defining class methods. # we won't discuss that here. pass def read_file(filename): if not os.path.exists(filename): raise NonExistentFile(filename) f = open(filename) result = f.read() f.close() return result4o- read_file('tmp.txt') read_file('file.which.does.not.exist') """ Explanation: It is sometimes useful to define your own custom exceptions, which you can do easily via class inheritance: End of explanation """ try: print("doing something") except: print("this only happens if it fails") else: print("this only happens if it succeeds") try: print("doing something") raise ValueError() except: print("this only happens if it fails") else: print("this only happens if it succeeds") """ Explanation: Get used to throwing appropriate &mdash; and meaningful &mdash; exceptions in your code! It makes reading and debugging your code much, much easier. More Advanced Exception Handling There is also the possibility of adding else and finally clauses to your try statements. You'll probably not need these often, but in case you encounter them some time, it's good to know what they do. The behavior looks like this: End of explanation """ try: print("do something") except: print("this only happens if it fails") else: print("this only happens if it succeeds") finally: print("this happens no matter what.") try: print("do something") raise ValueError() except: print("this only happens if it fails") else: print("this only happens if it succeeds") finally: print("this happens no matter what.") """ Explanation: Why would you ever want to do this? Mainly, it prevents the code within the else block from being caught by the try block. Accidentally catching an exception you don't mean to catch can lead to confusing results. The last statement you might use is the finally statement, which looks like this: End of explanation """ try: print("do something") except: print("this only happens if it fails") else: print("this only happens if it succeeds") print("this happens no matter what.") """ Explanation: finally is generally used for some sort of cleanup (closing a file, etc.) It might seem a bit redundant, though. Why not write the following? End of explanation """ x = 0 excpt = None try: 1.0/x except Exception as err: if isinstance(err, ZeroDivisionError): pass else: raise Exception("Got error.") type(excpt) """ Explanation: Write exception code that handles all exceptions except ZeroDivideError End of explanation """ def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") return None else: print("result is", result) return result finally: print("some sort of cleanup") divide(15, 3) divide(15, 0) """ Explanation: The main difference is when the clause is used within a function: End of explanation """
geoscixyz/computation
docs/case-studies/PF/TKC_Mag.ipynb
mit
## First we need to load all the libraries and set up the path ## for the input files. Same files as used by the online tutorial %matplotlib notebook import scipy as sp import numpy as np import time as tm import os import shutil import matplotlib.colors as colors import matplotlib.pyplot as plt from SimPEG import Mesh, Utils, Maps, Regularization, DataMisfit, Optimization, InvProblem, Directives, Inversion, PF from SimPEG.Utils.io_utils import download psep = os.path.sep url = 'https://storage.googleapis.com/simpeg/tkc_synthetic/potential_fields/' cloudfiles = ['MagData.obs', 'Mesh.msh', 'Initm.sus', 'SimPEG_PF_Input.inp'] downloads = download([url+f for f in cloudfiles], folder='./MagTKC/', overwrite=True) downloads = dict(zip(cloudfiles, downloads)) input_file = downloads['SimPEG_PF_Input.inp'] # Read in the input file which included all parameters at once (mesh, topo, model, survey, inv param, etc.) driver = PF.MagneticsDriver.MagneticsDriver_Inv(input_file) # We already have created a mesh, model and survey for this example. # All the elements are stored in the driver, and can be accessed like this: mesh = driver.mesh survey = driver.survey """ Explanation: TKC Magnetics Where are the diamonds: Using Earth's Potential Fields (Magnetics) In this tutorial we will run a magnetic inverse problem from an input file. The synthetic example used is based on the TKC kimberlite deposit, Northwest Territories. We are attempting to use the magnetic field to image the various rock units making up the diamond deposit. We will skip the model creation for now, at it is quite involved and out of scope for this notebook. End of explanation """ # We did not include a topography file in this example as the information # about inactive cells is already captured in our starting model. # Line 6 of the input file specifies a VALUE to be used as inactive flag. # Get the active cells actv = driver.activeCells nC = len(actv) # Number of active cells ndv = -100 # Create active map to return to full space after the inversion actvMap = Maps.InjectActiveCells(mesh, actv, ndv) # Create a reduced identity map for the inverse problem idenMap = Maps.IdentityMap(nP=nC) """ Explanation: Setup We are using the integral form of the magnetostatic problem. In the absence of free-currents or changing magnetic field, magnetic material can give rise to a secondary magnetic field according to: $$\vec b = \frac{\mu_0}{4\pi} \int_{V} \vec M \cdot \nabla \nabla \left(\frac{1}{r}\right) \; dV $$ Where $\mu_0$ is the magnetic permealitity of free-space, $\vec M$ is the magnetization per unit volume and $r$ defines the distance between the observed field $\vec b$ and the magnetized object. Assuming a purely induced response, the strenght of magnetization can be written as: $$ \vec M = \mu_0 \kappa \vec H_0 $$ where $\vec H$ is an external inducing magnetic field, and $\kappa$ the magnetic susceptibility of matter. As derived by Sharma 1966, the integral can be evaluated for rectangular prisms such that: $$ \vec b(P) = \mathbf{T} \cdot \vec H_0 \; \kappa $$ Where the tensor matrix $\bf{T}$ relates the three components of magnetization $\vec M$ to the components of the field $\vec b$: $$\mathbf{T} = \begin{pmatrix} T_{xx} & T_{xy} & T_{xz} \ T_{yx} & T_{yy} & T_{yz} \ T_{zx} & T_{zy} & T_{zz} \end{pmatrix} $$ In general, we discretize the earth into a collection of cells, each contributing to the magnetic data such that: $$\vec b(P) = \sum_{j=1}^{nc} \mathbf{T}_j \cdot \vec H_0 \; \kappa_j$$ giving rise to a linear problem. End of explanation """ # Now that we have a model and a survey we can build the linear system ... # Create the forward model operator (the argument forwardOnly=False store the forward matrix to memory) prob = PF.Magnetics.MagneticIntegral(mesh, chiMap=idenMap, actInd=actv, forwardOnly=False) # Pair the survey and problem survey.pair(prob) # Fist time that we ask for predicted data, # the dense matrix T is calculated. # This is generally the bottleneck of the integral formulation in terms of cost d = prob.fields(driver.m0) # Add noise to the data and assign uncertainties data = d + np.random.randn(len(d)) # We add some random Gaussian noise (1nT) wd = np.ones(len(data))*1. # Assign flat uncertainties survey.dobs = data survey.std = wd # [OPTIONAL] You can write the observations to UBC format here #PF.Magnetics.writeUBCobs('MAG_Synthetic_data.obs',survey,data) fig = Utils.PlotUtils.plot2Ddata(survey.srcField.rxList[0].locs, data, contourOpts={"cmap":"Spectral_r"}) """ Explanation: Forward system: Now that we have all our spatial components, we can create our linear system. For a single location and single component of the data, the system would looks like this: $$ b_x = \begin{bmatrix} T_{xx}^1 &... &T_{xx}^{nc} & T_{xy}^1 & ... & T_{xy}^{nc} & T_{xz}^1 & ... & T_{xz}^{nc}\ \end{bmatrix} \begin{bmatrix} \mathbf{M}_x \ \mathbf{M}_y \ \mathbf{M}_z \end{bmatrix} \ $$ where each of $T_{xx},\;T_{xy},\;T_{xz}$ are [nc x 1] long. For the $y$ and $z$ component, we need the two other rows of the tensor $\mathbf{T}$. In our simple induced case, the magnetization direction $\mathbf{M_x,\;M_y\;,Mz}$ are known and assumed to be constant everywhere, so we can reduce the size of the system such that: $$ \vec{\mathbf{d}}_{\text{pred}} = (\mathbf{T\cdot M})\; \kappa$$ In most geophysical surveys, we are not collecting all three components, but rather the magnitude of the field, or $Total\;Magnetic\;Intensity$ (TMI) data. Because the inducing field is really large, we will assume that the anomalous fields are parallel to $H_0$: $$ d^{TMI} = \hat H_0 \cdot \vec d$$ We then end up with a much smaller system: $$ d^{TMI} = \mathbf{F\; \kappa}$$ where $\mathbf{F} \in \mathbb{R}^{nd \times nc}$ is our $forward$ operator. End of explanation """ # It is potential fields, so we will need to push the inverison down # Create distance weights from our linera forward operator wr = np.sum(prob.G**2.,axis=0)**0.5 wr = ( wr/np.max(wr) ) # Create a regularization reg = Regularization.Sparse(mesh, indActive=actv, mapping=idenMap, gradientType='total') reg.norms = np.c_[0.5,0,0,0] reg.cell_weights = wr dmis = DataMisfit.l2_DataMisfit(survey) dmis.W = 1/wd # Add directives to the inversion opt = Optimization.ProjectedGNCG(maxIter=100 ,lower=0.,upper=1., maxIterLS = 20, maxIterCG= 10, tolCG = 1e-3) invProb = InvProblem.BaseInvProblem(dmis, reg, opt) betaest = Directives.BetaEstimate_ByEig(beta0_ratio=1) # Here is where the norms are applied # Use pick a treshold parameter empirically based on the distribution of model # parameters (run last cell to see the histogram before and after IRLS) IRLS = Directives.Update_IRLS(f_min_change = 1e-4, minGNiter=1, betaSearch=False) update_Jacobi = Directives.UpdatePreconditioner() inv = Inversion.BaseInversion(invProb, directiveList=[betaest,IRLS,update_Jacobi]) m0 = np.ones(idenMap.nP)*1e-4 # Run inversion... mrec = inv.run(m0) # Get the final model back to full space and plot!! m_lp = actvMap*mrec m_lp[m_lp==ndv] = np.nan # Get the smooth model aslo m_l2 = actvMap*invProb.l2model m_l2[m_l2==ndv] = np.nan m_true = actvMap*driver.m0 m_true[m_true==ndv] = np.nan #[OPTIONAL] Save both models to file #Mesh.TensorMesh.writeModelUBC(mesh,'SimPEG_MAG_l2l2.sus',m_l2) #Mesh.TensorMesh.writeModelUBC(mesh,'SimPEG_MAG_lplq.sus',m_lp) # Plot the recoverd models vmin, vmax = 0., 0.015 mesh.plot_3d_slicer(m_true, pcolorOpts={"vmax":0.025, "cmap":"CMRmap_r"}) mesh.plot_3d_slicer(m_lp, pcolorOpts={"vmax":0.025, "cmap":"CMRmap_r"}) mesh.plot_3d_slicer(m_l2, pcolorOpts={"vmax":0.01, "cmap":"CMRmap_r"}) # Lets compare the distribution of model parameters and model gradients plt.figure(figsize=[15,5]) ax = plt.subplot(121) plt.hist(invProb.l2model,100) plt.plot((reg.eps_p,reg.eps_p),(0,mesh.nC),'r--') plt.yscale('log', nonposy='clip') plt.title('Hist model - l2-norm') plt.legend(['$\epsilon_p$']) ax = plt.subplot(122) plt.hist(reg.regmesh.cellDiffxStencil*invProb.l2model,100) plt.plot((reg.eps_q,reg.eps_q),(0,mesh.nC),'r--') plt.yscale('log', nonposy='clip') plt.title('Hist model gradient - l2-norm') plt.legend(['$\epsilon_q$']) # Lets look at the distribution of model parameters and model gradients plt.figure(figsize=[15,5]) ax = plt.subplot(121) plt.hist(mrec,100) plt.plot((reg.eps_p,reg.eps_p),(0,mesh.nC),'r--') plt.yscale('log', nonposy='clip') plt.title('Hist model - lp-norm') plt.legend(['$\epsilon_p$']) ax = plt.subplot(122) plt.hist(reg.regmesh.cellDiffxStencil*mrec,100) plt.plot((reg.eps_q,reg.eps_q),(0,mesh.nC),'r--') plt.yscale('log', nonposy='clip') plt.title('Hist model gradient - lp-norm') plt.legend(['$\epsilon_q$']) """ Explanation: Inverse problem We have generated synthetic data, we now what to see if we can solve the inverse. Using the usual formulation, we seek a model that can reproduce the data, let’s say a least-squares measure of the form: \begin{equation} \phi_d = \|\mathbf{W}_d \left( \mathbb{F}[\mathbf{m}] - \mathbf{d}^{obs} \right)\|_2^2 \end{equation} The inverse problem is hard because we don’t have great data coverage, and the Earth is big, and there is usually noise in the data. So we need to add something to regularize it. The simplest way to do it is to penalize solutions that won’t make sense geologically, for example to assume that the model is small. The usual smooth inversion function use an l2-norm measure: \begin{equation} \phi_d = \|\mathbf{W}d \left( \mathbb{F}[\mathbf{m}] - \mathbf{d}^{obs} \right)\|_2^2 \ \phi_m = \beta \Big [ {\| \mathbf{W}_s \;( \mathbf{m - m^{ref}})\|}^2_2 + \sum{i = x,y,z} {\| \mathbf{W}_i \; \mathbf{G}_i \; \mathbf{m}\|}^2_2 \Big ]\;, \end{equation} The full objective function to be minimized can be written as: \begin{equation} \phi(m) = \phi_d + \beta \phi_m\;, \end{equation} which will yield our usual small and smooth models. We propose a fancier regularization function that can allow to recover sparse and blocky solutions. Starting with the well known Ekblom norm: \begin{equation} \phi_m = \sum_{i=1}^{nc} {(x_i^2 + \epsilon^2)}^{p/2} \;, \end{equation} where $x_i$ denotes some function of the model parameter, and $\epsilon$ is a small value to avoid singularity as $m\rightarrow0$. For p=2, we get the usual least-squares measure and we recover the regularization presented above. For $p \leq 1$, the function becomes non-linear which requires some tweaking. We can linearize the function by updating the penality function iteratively, commonly known as an Iterative Re-weighted Least-Squares (IRLS) method: \begin{equation} \phi_m^{(k)} = \frac{1}{2}\sum_{i=1}^{nc} r_i \; x_i^2 \end{equation} where we added the superscript $\square^{(k)}$ to denote the IRLS iterations. The weights $r(x)$ are computed from model values obtained at a previous iteration such that: \begin{equation} {r}_i ={\Big( {({x_i}^{(k-1)})}^{2} + \epsilon^2 \Big)}^{p/2 - 1} \;, \end{equation} where ${r}(x) \in \mathbb{R}^{nc}$. In matrix form, our objective function simply becomes: \begin{equation} \phi(m) = \|\mathbf{W}d \left( \mathbb{F}[\mathbf{m}] - \mathbf{d}^{obs} \right)\|_2^2 + \beta \Big [ {\| \mathbf{W}_s \;\mathbf{R}_s\;( \mathbf{m - m^{ref}})\|}^2_2 + \sum{i = x,y,z} {\| \mathbf{W}i\; \mathbf{R}_i \; \mathbf{G}_i \; \mathbf{m}\|}^2_2 \Big ]\;, \end{equation} where the IRLS weights $\mathbf{R}_s$ and $\mathbf{R}_i$ are diagonal matrices defined as: \begin{equation} \begin{split} {R}{s_{jj}} &= \sqrt{\eta_p}{\Big[ {({m_j}^{(k-1)})}^{2} + \epsilon_p^2 \Big]}^{(p/2 - 1)/2} \ {R}{i{jj}} &= \sqrt{\eta_q}{\Big[ {\left ({{(G_i\;m^{(k-1)})}_j }\right)}^{2} + \epsilon_q^2 \Big]}^{(q/2 - 1)/2} \ \eta_p &= {\epsilon_p}^{(1-p/2)} \ \eta_q &= {\epsilon_q}^{(1-q/2)} \;, \end{split} \end{equation} we added two scaling parameters $\eta_p$ and $\eta_q$ for reasons that we won't dicuss here, but turn out to be important to get stable solves. In order to initialize the IRLS and get an estimate for the stabilizing parameters $\epsilon_p$ and $\epsilon_q$, we first invert with the smooth $l_2$-norm. The whole IRLS process is implemented with a directive added to the inversion workflow (see below). End of explanation """
raschuetz/foundations-homework
05/.ipynb_checkpoints/Spotify-API-checkpoint.ipynb
mit
import requests response = requests.get('https://api.spotify.com/v1/search?query=artist:lil&type=artist&market=us&limit=50') data = response.json() artists = data['artists']['items'] for artist in artists: print(artist['name'], artist['popularity']) """ Explanation: 1) With "Lil Wayne" and "Lil Kim" there are a lot of "Lil" musicians. Do a search and print a list of 50 that are playable in the USA (or the country of your choice), along with their popularity score. <br /> End of explanation """ for artist in artists: if not artist['genres']: print(artist['name'], artist['popularity'], 'No genres listed') else: print(artist['name'], artist['popularity'], ', '.join(artist['genres'])) genre_list = [] for artist in artists: for genre in artist['genres']: genre_list.append(genre) sorted_genre = sorted(genre_list) genre_list_number = range(len(sorted_genre)) genre_count = 0 for number in genre_list_number: if not sorted_genre[number] == sorted_genre[number - 1]: print((sorted_genre[number]), genre_list.count(sorted_genre[number])) if genre_count < genre_list.count(sorted_genre[number]): genre_count = genre_list.count(sorted_genre[number]) freq_genre = sorted_genre[number] print('') print('With', genre_count, 'artists,', freq_genre, 'is the most represented in search results.') numbers = [72, 3, 0, 72, 34, 72, 3] """ Explanation: 2) What genres are most represented in the search results? Edit your previous printout to also display a list of their genres in the format "GENRE_1, GENRE_2, GENRE_3". If there are no genres, print "No genres listed". <br /> End of explanation """ highest_pop = 0 for artist in artists: if artist['name'] != 'Lil Wayne' and highest_pop < artist['popularity']: highest_pop = artist['popularity'] highest_pop_artist = artist['name'] print(highest_pop_artist, 'is the second-most-popular artist with \"Lil\" in his/her name.') most_followers = 0 for artist in artists: if most_followers < artist['followers']['total']: most_followers = artist['followers']['total'] most_followers_artist = artist['name'] print(most_followers_artist, 'has', most_followers, 'followers.') if highest_pop_artist == most_followers_artist: print('The second-most-popular \'Lil\' artist is also the one with the most followers.') else: print('The second-most-popular \'Lil\' artist and the one with the most followers are different people.') """ Explanation: Tip: "how to join a list Python" might be a helpful search <br /> 3) Use a for loop to determine who BESIDES Lil Wayne has the highest popularity rating. Is it the same artist who has the largest number of followers? <br /> End of explanation """ for artist in artists: if artist['name'] == 'Lil\' Kim': more_popular = artist['popularity'] for artist in artists: if more_popular < artist ['popularity']: print(artist['name'], 'is more popular than Lil\' Kim with a popularity score of', artist['popularity']) """ Explanation: 4) Print a list of Lil's that are more popular than Lil' Kim. <br /> End of explanation """ wayne_id = '55Aa2cqylxrFIXC767Z865' wayne_response = requests.get('https://api.spotify.com/v1/artists/' + wayne_id + '/top-tracks?country=us') wayne_data = wayne_response.json() print('Lil Wayne\'s top tracks:') wayne_tracks = wayne_data['tracks'] for track in wayne_tracks: print(track['name']) print('') kim_id = '5tth2a3v0sWwV1C7bApBdX' kim_response = requests.get('https://api.spotify.com/v1/artists/' + kim_id + '/top-tracks?country=us') kim_data = kim_response.json() print('Lil\' Kim\'s top tracks:') kim_tracks = kim_data['tracks'] for track in kim_tracks: print(track['name']) """ Explanation: 5) Pick two of your favorite Lils to fight it out, and use their IDs to print out their top tracks. <br /> End of explanation """ print('Lil Wayne\'s explicit top tracks:') ew_total_pop = 0 ew_total_tracks = 0 ew_playtime = 0 for track in wayne_tracks: if track['explicit']: ew_total_pop = ew_total_pop + track['popularity'] ew_total_tracks = ew_total_tracks + 1 ew_playtime = ew_playtime + track['duration_ms']/60000 if ew_total_tracks == 0: print('There are no explicit tracks.') else: print('The average popularity is', ew_total_pop / ew_total_tracks) print('He has', ew_playtime, 'minutes of explicit music in his top tracks.') print('') print('Lil Wayne\'s non-explicit top tracks:') nw_total_pop = 0 nw_total_tracks = 0 nw_playtime = 0 for track in wayne_tracks: if not track['explicit']: nw_total_pop = nw_total_pop + track ['popularity'] nw_total_tracks = nw_total_tracks + 1 nw_playtime = nw_playtime + track['duration_ms']/60000 if nw_total_tracks == 0: print('There are no non-explicit tracks.') else: print('The average popularity is', nw_total_pop / nw_total_tracks) print('He has', nw_playtime, 'minutes of non-explicit music in his top tracks.') print('') print('Lil\' Kim\'s explicit top tracks:') ek_total_pop = 0 ek_total_tracks = 0 ek_playtime = 0 for track in kim_tracks: if track['explicit']: ek_total_pop = ek_total_pop + track ['popularity'] ek_total_tracks = ek_total_tracks + 1 ek_playtime = ek_playtime + track['duration_ms']/60000 if ek_total_tracks == 0: print('There are no explicit tracks.') else: print('The average popularity is', ek_total_pop / ek_total_tracks) print('She has', ek_playtime, 'minutes of explicit music in her top tracks.') print('') print('Lil\' Kim\'s non-explicit top tracks:') nk_total_pop = 0 nk_total_tracks = 0 nk_playtime = 0 for track in kim_tracks: if not track['explicit']: nk_total_pop = nk_total_pop + track ['popularity'] nk_total_tracks = nk_total_tracks + 1 nk_playtime = nk_playtime + track['duration_ms']/60000 if nk_total_tracks == 0: print('There are no non-explicit tracks.') else: print('The average popularity is', nk_total_pop / nk_total_tracks) print('She has', nk_playtime, 'minutes of non-explicit music in her top tracks.') """ Explanation: Tip: You're going to be making two separate requests, be sure you DO NOT save them into the same variable. <br /> 6) Will the world explode if a musicians swears? Get an average popularity for their explicit songs vs. their non-explicit songs. How many minutes of explicit songs do they have? Non-explicit? <br /> End of explanation """ biggie_response = requests.get('https://api.spotify.com/v1/search?query=artist:biggie&type=artist&market=us&limit=50') biggie_data = biggie_response.json() biggie_artists = biggie_data['artists']['items'] total_biggies = 0 for artist in biggie_artists: total_biggies = total_biggies + 1 print('There are', total_biggies, 'Biggies on Spotify.') print('It would take', total_biggies * 5, 'seconds to request all of the Biggies if you were requesting one every five seconds.') print('') pages = range(90) total_lils = 0 for page in pages: lil_response = requests.get('https://api.spotify.com/v1/search?query=artist:lil&type=artist&market=us&limit=50&offset=' + str(page * 50)) lil_data = lil_response.json() lil_artists = lil_data['artists']['items'] for artist in lil_artists: total_lils = total_lils + 1 print('There are', total_lils, 'Lils on Spotify.') print('It would take', round(total_lils / 12), 'minutes to request all of the Lils if you were requesting one every five seconds.') """ Explanation: 7) Since we're talking about Lils, what about Biggies? How many total "Biggie" artists are there? How many total "Lil"s? If you made 1 request every 5 seconds, how long would it take to download information on all the Lils vs the Biggies? <br /> End of explanation """ biggie_total_pop = 0 for artist in biggie_artists: biggie_total_pop = biggie_total_pop + artist['popularity'] biggie_avg_pop = biggie_total_pop / 50 lil_response_pg1 = requests.get('https://api.spotify.com/v1/search?query=artist:lil&type=artist&market=us&limit=50') lil_data_pg1 = lil_response_pg1.json() lil_artists_pg1 = lil_data_pg1['artists']['items'] lil_total_pop = 0 for artist in lil_artists_pg1: lil_total_pop = lil_total_pop + artist['popularity'] lil_avg_pop = lil_total_pop / 50 if biggie_avg_pop > lil_avg_pop: print('The top 50 biggies are more popular.') elif biggie_avg_pop < lil_avg_pop: print('The top 50 lils are more popular.') else: print('They are equally popular.') """ Explanation: 8) Out of the top 50 "Lil"s and the top 50 "Biggie"s, who is more popular on average? <br /> End of explanation """
drphilmarshall/SpaceWarps
analysis/make_lens_catalog.ipynb
mit
import pandas as pd import swap base_collection_path = '/nfs/slac/g/ki/ki18/cpd/swap/pickles/15.09.02/' base_directory = '/nfs/slac/g/ki/ki18/cpd/swap_catalog_diagnostics/' annotated_catalog_path = base_directory + 'annotated_catalog.csv' cut_empty = True stages = [1, 2] categories = ['ID', 'ZooID', 'location', 'mean_probability', 'category', 'kind', 'flavor', 'state', 'status', 'truth', 'stage', 'line'] annotation_categories = ['At_X', 'At_Y', 'PD', 'PL'] catalog = [] for stage in stages: print(stage) collection_path = base_collection_path + 'stage{0}'.format(stage) + '/CFHTLS_collection.pickle' collection = swap.read_pickle(collection_path, 'collection') for ID in collection.list(): subject = collection.member[ID] catalog_i = [] # for stage1 we shall skip the tests for now if (stage == 1) * (subject.category == 'test'): continue # flatten out x and y. also cut out empty entries annotationhistory = subject.annotationhistory x_unflat = annotationhistory['At_X'] x = np.array([xi for xj in x_unflat for xi in xj]) # cut out catalogs with no clicks if (len(x) < 1) and (cut_empty): continue # oh yeah there's that absolutely nutso entry with 50k clicks if len(x) > 10000: continue for category in categories: if category == 'stage': catalog_i.append(stage) elif category == 'line': catalog_i.append(line) else: catalog_i.append(subject.__dict__[category]) for category in annotation_categories: catalog_i.append(list(annotationhistory[category])) catalog.append(catalog_i) catalog = pd.DataFrame(catalog, columns=categories + annotation_categories) # save catalog catalog.to_csv(annotated_catalog_path) """ Explanation: Run this notebook to produce the cutout catalogs! Potential TODO: Write code for creating the pickles? Potential TODO: Write code for downloading all the fields in advance? Create the annotated csv catalog End of explanation """ knownlens_dir = '/nfs/slac/g/ki/ki18/cpd/code/strongcnn/catalog/knownlens/' knownlensID = pd.read_csv(knownlens_dir + 'knownlensID', sep=' ') listfiles_d1_d11 = pd.read_csv(knownlens_dir + 'listfiles_d1_d11.txt', sep=' ') knownlenspath = knownlens_dir + 'knownlens.csv' X2 = listfiles_d1_d11[listfiles_d1_d11['CFHTID'].isin(knownlensID['CFHTID'])] # cuts down to like 212 entries. ZooID = [] for i in range(len(Y)): ZooID.append(X2['ZooID'][X2['CFHTID'] == knownlensID['CFHTID'][i]].values[0]) knownlensID['ZooID'] = ZooID knownlensID.to_csv(knownlenspath) """ Explanation: Create the knownlens catalog End of explanation """ # code to regenerate the catalogs base_directory = '/nfs/slac/g/ki/ki18/cpd/swap_catalog_diagnostics/' cluster_directory = base_directory ## uncomment this line when updating the shared catalog! # base_directory = '/nfs/slac/g/ki/ki18/cpd/swap_catalog/' # cluster_directory = base_directory + 'clusters/' field_directory = base_directory knownlens_path = base_directory + 'knownlens.csv' collection_path = base_directory + 'annotated_catalog.csv' catalog_path = cluster_directory + 'catalog.csv' # if we're rerunning this code, we should remove the old cluster pngs, # all of which have *_*.png from glob import glob files_to_delete = glob(cluster_directory + '*_*.png') from os import remove for delete_this_file in files_to_delete: remove(delete_this_file) # run create catalog code. This can take a while. from subprocess import call command = ['python', '/nfs/slac/g/ki/ki18/cpd/code/strongcnn/code/create_catalogs.py', '--collection', collection_path, '--knownlens', knownlens_path, '--clusters', cluster_directory, '--fields', field_directory, #'--augment', augmented_directory, #'--do_a_few', '100', ] call(command) """ Explanation: Convert the annotated catalog and knownlens catalog into cluster catalogs and cutouts End of explanation """
lwahedi/CurrentPresentation
talks/MDI5/Scraping+Lecture (5).ipynb
mit
import pandas as pd import numpy as np import pickle import statsmodels.api as sm from sklearn import cluster import matplotlib.pyplot as plt %matplotlib inline from bs4 import BeautifulSoup as bs import requests import time # from ggplot import * """ Explanation: Collecting and Using Data in Python Laila A. Wahedi, PhD Massive Data Institute Postdoctoral Fellow <br>McCourt School of Public Policy<br> Follow along: Wahedi.us, Current Presentation Follow Along Go to https://notebooks.azure.com/Laila/libraries/MDI-workshopFA18 Clone the directory <img src='step1.png'> Follow Along Sign in with any Microsoft Account (Hotmail, Outlook, Azure, etc.) Create a folder to put it in, mark as private or public <img src='step2.png'> Follow Along Open a notebook Open this notebook to have the code to play with Data_collection_Analysis2.ipynb Open a blank notebook to follow along and try on your own. <img src='step4.png'> Do you get this error? (Or any other error) HTTP Error 400. The size of the request headers is too long Clear your cookies then refresh the browser. Your Environment Jupyter Notebook Hosted in Azure Want to install it at home? Install the Anaconda distribution of Python https://www.anaconda.com/download/ Install Jupyter Notebooks http://jupyter.org/install Your Environment ctrl/apple+ enter runs a cell <img src='notebook.png'> Your Environment Persistent memory If you run a cell, results remain as long as the kernel ORDER MATTERS! <img src='persist.png'> Agenda for today: Collect data from APIs Scrape data Merge data into a data frame Statsmodels package SKLearn package Packages to Import For Today Should all be included with your Anaconda Python Distribution Raise your hand for help if you have trouble Our plots will use matplotlib, similar to plotting in matlab %matplotlib inline tells Jupyter Notebooks to display your plots from allows you to import part of a package End of explanation """ base_url = "http://www.mywebsite.com/data/api?" attributes = ["key1=value1", "key2=value2", "API_KEY=39DC3727-09BD-XXXX-XXXX-XXXXXXXXXXXX" ] post_url = '&'.join(attributes) print(base_url+post_url) """ Explanation: Other Useful Packages (not used today) ggplot: the familiar ggplot2 you know and love from R seaborn: Makes your plots prettier plotly: makes interactive visualizations, similar to shiny gensim: package for doing natural language processing scipy: used with numpy to do math. Generates random numbers from distributions, does matrix operations, etc. Scraping How the Internet Works Code is stored on servers Web addresses point to the location of that code Going to an address or clicking a button sends requests to the server for data, The server returns the requested content Your web browser interprets the code to render the web page <img src='Internet.png'> Scraping: Collect the website code by emulating the process: Can haz cheezburger? <img src='burger.png'> Extract the useful information from the scraped code: Where's the beef? <img src='beef.png'> API Application Programming Interface The set of rules that govern communication between two pieces of code Code requires clear expected inputs and outputs APIs define required inputs to get the outputs in a format you can expect. Easier than scraping a website because gives you exactly what you ask for <img src="beef_direct.png"> API Keys APIs often require identification Go to https://docs.airnowapi.org Register and get a key Log in to the site Select web services DO NOT SHARE YOUR KEY It will get stolen and used for malicious activity Do Not Share Your Key Make your notebook private: <img src='settings.png'> Do Not Share Your Key Make your notebook private: <img src='private.png'> Requests to a Server <div style="float: left;width:50%"> <h3> GET</h3> <ul><li>Requests data from the server</li> <li> Encoded into the URL</li></ul> <img src='get.png'> </div> <div style="float: left;width:50%"> <h3>POST</h3> <ul><li>Submits data to be processed by the server</li> <li>For example, filter the data</li> <li>Can attach additional data not directly in the url</li></ul> <img src='post.png'> </div> Using an API Change the parameters. What changes? <img src='api.png'> Requests encoded in the URL Parsing a URL <font color="blue">http://www.airnowapi.org/aq/observation/zipCode/historical/</font><font color="red">?</font><br><font color="green">format</font>=<font color="purple">application/json</font><font color="orange">&<br></font><font color="green">zipCode</font>=<font color="purple">20007</font><font color="orange">&</font><br><font color="green">date</font>=<font color="purple">2017-09-05T00-0000</font><font color="orange">&</font><br><font color="green">distance</font>=<font color="purple">25</font><font color="orange">&</font><br><font color="green">API_KEY</font>=<font color="purple">D9AA91E7-070D-4221-867CC-XXXXXXXXXXX</font> The base URL or endpoint is:<br> <font color="blue">http://www.airnowapi.org/aq/observation/zipCode/historical/</font> <font color="red">?</font> tells us that this is a query. <font color="orange">&</font> separates name, value pairs within the request. Five <font color="green"><strong>name</strong></font>, <font color="purple"><strong>value</strong></font> pairs POSTED format, zipCode, date, distance, API_KEY Request from Python prepare the url List of attributes Join them with "&" to form a string End of explanation """ base_url = "http://www.airnowapi.org/aq/observation/zipCode/historical/" attributes = ["format=application/json", "zipCode=20007", "date=2017-09-05T00-0000", "distance=25", "API_KEY=39DC3727-09BD-48C4-BBD8-XXXXXXXXXXXX" ] post_url = '&'.join(attributes) print(base_url+post_url) """ Explanation: Prepare another URL on your own End of explanation """ ingredients=requests.get(base_url, post_url) ingredients = ingredients.json() print(ingredients[0]) """ Explanation: Where did the ? go? Requests from Python Use requests package .get(url,post) for get and post requests First parameter: url for get request Optional second parameter: post data if doing a post request Requests posts the data to the url, so you don't need to add a ? to the base url Leave the post data out for a get request instead of a post request Requested json format Returns list of dictionaries Look at the returned keys End of explanation """ for item in ingredients: AQIType = item['ParameterName'] City=item['ReportingArea'] AQIValue=item['AQI'] print("For Location ", City, " the AQI for ", AQIType, "is ", AQIValue) """ Explanation: View Returned Data: Each list gives a different parameter for zip code and date we searched End of explanation """ time.sleep(1) """ Explanation: Ethics Check the websites terms of use <strong>Don't hit too hard:</strong> Insert pauses in your code to act more like a human Scraping can look like an attack Server will block you without pauses APIs often have rate limits Use the time package to pause for a second between hits End of explanation """ asthma_data = pd.read_csv('asthma-emergency-department-visit-rates-by-zip-code.csv') asthma_data.head(2) """ Explanation: Collect Our Data Python helps us automate repetitive tasks. Don't download each datapoint you want separately Get a list of zip codes we want take a subset to demo, so it doesn't take too long and so we don't all hit too hard from the same ip California zip codes from asthma emergency room visits Review from last week: Asthma Data Load asthma data from csv Display a few rows Fix the zip codes Pivot to have one row per zip code (repeated rows for children, adults, all) Load from csv, display End of explanation """ asthma_data[['zip','coordinates']] = asthma_data.loc[:,'ZIP code'].str.split( pat='\n',expand=True) asthma_data.drop('ZIP code', axis=1,inplace=True) asthma_data.head(2) """ Explanation: Fix the zip codes Fix zip codes End of explanation """ asthma_unstacked = asthma_data.pivot_table(index = ['Year', 'zip', 'County', 'coordinates', 'County Fips code'], columns = 'Age Group', values = 'Number of Visits') asthma_unstacked.reset_index(drop=False,inplace=True) asthma_unstacked.head(2) """ Explanation: Pivot the data so age group are columns End of explanation """ base_url = "http://www.airnowapi.org/aq/observation/zipCode/historical/" zips = asthma_unstacked.zip.unique() zips = zips[:450] date ="date=2015-09-01T00-0000" api_key = "API_KEY=39DC3727-09BD-48C4-BBD8-XXXXXXXXXXXX" return_format = "format=application/json" zip_str = "zipCode=" post_url = "&".join([date,api_key,return_format,zip_str]) data_dict = {} for zipcode in zips: time.sleep(1) zip_post = post_url + str(zipcode) ingredients = requests.get(base_url, zip_post) ingredients = ingredients.json() zip_data = {} for data_point in ingredients: AQIType = data_point['ParameterName'] AQIVal = data_point['AQI'] zip_data[AQIType] = AQIVal data_dict[zipcode]= zip_data base_url = "http://www.airnowapi.org/aq/observation/zipCode/historical/" zips = asthma_unstacked.zip.unique() date ="date=2015-09-{}T00-0000" api_key = "API_KEY=XXX" return_format = "format=application/json" zip_str = "zipCode=" post_url = "&".join([date,api_key,return_format,zip_str]) # data_dict = {} time.sleep(3600) for d in ['01','05','10','15','20','25','30',]: if d =='01': ziplist = zips[449:] else: ziplist = zips for zipcode in ziplist: time.sleep(1) zip_post = post_url.format(d) + str(zipcode) ingredients = requests.get(base_url, zip_post) try: ingredients = ingredients.json() except: if ingredients.text[0:26]=='<WebServiceError><Message>': time.sleep(3605) else: print(zipcode) zip_data = {} for data_point in ingredients: AQIType = data_point['ParameterName'] AQIVal = data_point['AQI'] zip_data[AQIType] = AQIVal zip_data['day'] = int(d) data_dict[zipcode]= zip_data pickle.dump(data_dict,open('ca_aqi_data.p','wb')) for i, z in enumerate(zips): if z==zipcode: print(i) len(data_dict) pickle.dump(data_dict,open('AQI_data_raw.p','wb')) """ Explanation: Now we have some zip codes! Automate Data Collection Request the data for those zipcodes on a day in 2015 (you pick, fire season July-Oct) Be sure to sleep between requests Store that data as you go into a dictionary Key: zip code Value: Dictionary of the air quality parameters and their value End of explanation """ ingredients = requests.get("https://en.wikipedia.org/wiki/Data_science") soup = bs(ingredients.text) print(soup.body.p) """ Explanation: Scraping: Parsing HTML What about when you don't have an API that returns dictionaries? HTML is a markup language that displays data (text, images, etc) Puts content within nested tags to tell your browser how to display it &lt;Section_tag> &emsp; &lt;tag> Content &lt;/tag> &emsp; &lt;tag> Content &lt;/tag> &lt; /Section_tag> &lt;Section_tag> &emsp; &lt;tag> <font color="red">Beef</font> &lt;/tag> &lt; /Section_tag> Find the tags that identify the content you want: First paragraph of wikipedia article: https://en.wikipedia.org/wiki/Data_science Inspect the webpage: Windows: ctrl+shift+i Mac: ctrl+alt+i <img src="wikipedia_scrape.png"> Parsing HTML with Beautiful Soup Beautiful Soup takes the raw html and parses the tags so you can search through them. text attribute returns raw html text from requests Ignore the warning, default parser is fine We know it's the first paragraph tag in the body tag, so: Can find first tag of a type using <strong>.</strong> What went wrong? End of explanation """ parser_div = soup.find("div", class_="mw-parser-output") wiki_content = parser_div.find_all('p') print(wiki_content[1]) print('*****************************************') print(wiki_content[1].text) """ Explanation: Use Find Feature to Narrow Your Search Find the unique div we identified Remember the underscore: "class_" Find the p tag within the resulting html Use an index to return just the first paragraph tag Use the text attribute to ignore all the formatting and link tags End of explanation """ parser_div = soup.find("div", id="toc") wiki_content = parser_div.find_all('ul') for item in wiki_content: print(item.text) """ Explanation: 1. List the contents 2. Get all links in the history section Hint: chrome's inspect replaces "&" with "&amp;" in links List Contents End of explanation """ wiki_content = soup.find_all('a',href=True) in_hist = False links = [] for l in wiki_content: link = l['href'] if link == '/w/index.php?title=Data_science&action=edit&section=2': in_hist = False if in_hist: links.append(link) if link =="/w/index.php?title=Data_science&action=edit&section=1": in_hist = True print(links) """ Explanation: Get All Links in the History Section Hint: chrome's inspect replaces "&" with "&amp;" in links End of explanation """ topics = ['Data_scraping','Machine_learning','Statistics','Linear_algebra', 'Cluster_analysis','Scientific_modelling','Analysis','Linear_regression'] base_url = 'https://en.wikipedia.org/wiki/' paragraphs = [] for topic in topics: url = base_url.format(topic) ingredients = requests.get(base_url+topic) soup = bs(ingredients.text) parser_div = soup.find("div", class_="mw-parser-output") wiki_content = parser_div.find_all('p') for p in range(10): if len(wiki_content[p].text)>10: paragraphs.append(wiki_content[p].text) break time.sleep(1) print(dict(zip(topics,paragraphs))) """ Explanation: Use a for loop and scrape the first paragraph from a bunch of wikipedia articles Add your own subjects End of explanation """ pickle.dump(data_dict,open('AQI_data_raw.p','wb')) """ Explanation: Back To Our Data If it's still running, go ahead and stop it by pushing the square at the top of the notebook: <img src="interrupt.png"> Save what you collected, don't want to hit them twice! End of explanation """ collected = list(data_dict.keys()) asthma_2015_sub = asthma_unstacked.loc[(asthma_unstacked.zip.isin(collected))& (asthma_unstacked.Year == 2015),:] """ Explanation: Subset down to the data we have: use the isin() method to include only those zip codes we've already collected End of explanation """ aqi_data = pd.DataFrame.from_dict(data_dict, orient='index') aqi_data.reset_index(drop=False,inplace=True) aqi_data.rename(columns={'index':'zip'},inplace=True) aqi_data.head() """ Explanation: Create a dataframe from the new AQI data End of explanation """ asthma_aqi = asthma_2015_sub.merge(aqi_data,how='outer',on='zip') asthma_aqi.rename(columns = {'Adults (18+)':'Adults', 'All Ages':'Incidents', 'Children (0-17)':'Children'},inplace=True) asthma_aqi.head(2) """ Explanation: Combine The Data https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html * Types of merges: * Left: Use only rows from the dataframe you are merging into * Right: use only rows from the dataframe you are inserting, (the one in the parentheses) * Inner: Use only rows that match between both * Outer: Use all rows, even if they only appear in one of the dataframes * On: The variables you want to compare * Specify right_on and left_on if they have different names End of explanation """ asthma_aqi.Incidents.plot.hist(20) """ Explanation: Look At The Data: Histogram 20 bins End of explanation """ asthma_aqi.loc[:,['Incidents','OZONE']].plot.density() """ Explanation: Look At The Data: Smoothed Distribution End of explanation """ asthma_aqi.loc[:,['PM2.5','PM10']].plot.hist() """ Explanation: Look at particulates There is a lot of missingness in 2015 Try other variables, such as comparing children and adults End of explanation """ asthma_aqi.plot.scatter('OZONE','PM2.5') """ Explanation: Scatter Plot Try some other combinations Our data look clustered, but we'll ignore that for now End of explanation """ y =asthma_aqi.loc[:,'Incidents'] x =asthma_aqi.loc[:,['OZONE','PM2.5']] x['c'] = 1 ols_model1 = sm.OLS(y,x,missing='drop') results = ols_model1.fit() print(results.summary()) pickle.dump([results,ols_model1],open('ols_model_results.p','wb')) """ Explanation: Run a regression: Note: statsmodels supports equation format like R <br> http://www.statsmodels.org/dev/example_formulas.html End of explanation """ fig = plt.figure(figsize=(12,8)) fig = sm.graphics.plot_partregress_grid(results, fig=fig) """ Explanation: Evaluate the model with some regression plots Learn more here: <br> https://www.statsmodels.org/dev/examples/notebooks/generated/regression_plots.html Partial Regressions to see effect of each variable End of explanation """ ingredients = requests.get('https://www.california-demographics.com/zip_codes_by_population') soup = bs(ingredients.text) table = soup.find("table") population = pd.read_html(str(table),flavor='html5lib')[0] population.rename(columns=population.iloc[0],inplace=True) population.drop(index=0,inplace=True) population.head(2) """ Explanation: Population confound Fires spread in less populated areas Fewer people to have asthma attacks in less populated areas Collect population data Use pandas to read the html table directly End of explanation """ population[['zip','zip2']]=population.loc[:,'Zip Code'].str.split( pat =' and ', expand=True) population.Population = population.Population.astype(np.float) population.loc[population.zip2!=None,'Population']=population.loc[population.zip2!=None,'Population']/2 temp_pop = population.loc[population.zip!=None,['Population','zip2']].copy() temp_pop.rename(columns={'zip2':'zip'},inplace=True) population = pd.concat([population.loc[:,['Population','zip']], temp_pop],axis=0) population.head(2) """ Explanation: Fix zipcode column Split doubled up zip codes into separate lines End of explanation """ asthma_aqi = asthma_aqi.merge(population,how='left',on='zip') y =asthma_aqi.loc[:,'Adults'] x =asthma_aqi.loc[:,['OZONE','Population']] x['c'] = 1 glm_model = sm.GLM(y,x,missing='drop',family=sm.families.Poisson()) ols_model2 = sm.OLS(y,x,missing='drop') glm_results = glm_model.fit() results = ols_model2.fit() print(glm_results.summary()) pickle.dump([glm_results,glm_model],open('glm_model_pop_results.p','wb')) """ Explanation: Re-run Regression With population Without PM2.5 End of explanation """ fig = plt.figure(figsize=(12,8)) fig = sm.graphics.plot_partregress_grid(results, fig=fig) """ Explanation: Poisson Regression Summary above was a Poisson regression instead of ols. Use GLM() to run a generalized linear model instead of an ols Specify the type of regression with family. We have count data, so: sm.GLM(y,x,missing='drop',sm.families.Poisson()) GLMs don't have all the fancy diagnostic plots, so we'll continue with ols results for now. Partial Regressions End of explanation """ fig, ax = plt.subplots(figsize=(12,8)) fig = sm.graphics.influence_plot(results, ax=ax, criterion="cooks") """ Explanation: Influence plot for outsized-effect of any observations End of explanation """ fig = plt.figure(figsize=(12,8)) fig = sm.graphics.plot_regress_exog(results, "OZONE", fig=fig) """ Explanation: Diagnostic plots End of explanation """ model_df = asthma_aqi.loc[:,['OZONE','PM2.5','Incidents',]] model_df.dropna(axis=0,inplace=True) model_df = (model_df - model_df.mean()) / (model_df.max() - model_df.min()) """ Explanation: SciKitLearn Package for machine learning models Structured like statsmodels: Create a model Train on data Output results object Very good documentation: http://scikit-learn.org Clustering Learn more about clustering here: <br> http://scikit-learn.org/stable/modules/clustering.html Many algorithms, each good in different contexts <img src="http://scikit-learn.org/stable/_images/sphx_glr_plot_cluster_comparison_0011.png"> <h1>K-Means</h1> <img src="rand.png"> <br> <h3> Randomly pick k initial centroids </h3> <h1>K-Means</h1> <img src="agg1.png" style="height:60%"> <br> <h3> Assign all points to nearest centroids</h3> <h1>K-Means</h1> <img src="new_cent.png" style="height:60%"><br> <h3> Calculate new centroids for each set</h3> <h1>K-Means</h1> <img src="agg2.png" style="height:60%"><br> <h3> Assign all points to nearest centroid</h3> <h1>K-Means</h1> <img src="cent2.png" style="height:60%"><br> <h3>Calculate new centroids, assign points, continue until no change</h3> Prepare data Statsmodels default drops null values Drop rows with missing values first Standardize the data so they're all on the same scale End of explanation """ asthma_air_clusters=cluster.KMeans(n_clusters = 3) asthma_air_clusters.fit(model_df) model_df['clusters3']=asthma_air_clusters.labels_ """ Explanation: Create and train the model Initialize a model with three clusters fit the model extract the labels End of explanation """ from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(4, 3)) ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) labels = asthma_air_clusters.labels_ ax.scatter(model_df.loc[:, 'PM2.5'], model_df.loc[:, 'OZONE'], model_df.loc[:, 'Incidents'], c=labels.astype(np.float), edgecolor='k') ax.set_xlabel('Particulates') ax.set_ylabel('Ozone') ax.set_zlabel('Incidents') """ Explanation: Look At Clusters Our data are very closely clustered, OLS was probably not appropriate. End of explanation """
zzsza/Datascience_School
15. 선형 회귀 분석/01. 회귀 분석용 가상 데이터 생성 방법.ipynb
mit
from sklearn.datasets import make_regression X, y, c = make_regression(n_samples=10, n_features=1, bias=0, noise=0, coef=True, random_state=0) print("X\n", X) print("y\n", y) print("c\n", c) plt.scatter(X, y, s=100) plt.show() """ Explanation: 회귀 분석용 가상 데이터 생성 방법 Scikit-learn 의 datasets 서브 패키지에는 회귀 분석 시험용 가상 데이터를 생성하는 명령어인 make_regression() 이 있다. http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html 입출력 요소 make_regression()는 다음과 같은 입출력 요소를 가진다. 입력 n_samples : 정수 (옵션, 디폴트 100) 표본의 갯수 n_features : 정수 (옵션, 디폴트 100) 독립 변수(feature)의 수(차원) n_targets : 정수 (옵션, 디폴트 1) 종속 변수(target)의 수(차원) n_informative : 정수 (옵션, 디폴트 10) 독립 변수(feature) 중 실제로 종속 변수와 상관 관계가 있는 독립 변수의 수(차원) effective_rank: 정수 또는 None (옵션, 디폴트 None) 독립 변수(feature) 중 서로 독립인 독립 변수의 수. 만약 None이면 모두 독립 tail_strength : 0부터 1사이의 실수 (옵션, 디폴트 0.5) effective_rank가 None이 아닌 경우 독립 변수간의 상관 관계 형태를 결정하는 변수 bias : 실수 (옵션, 디폴트 0.0) 절편 noise : 실수 (옵션, 디폴트 0.0) 출력 즉, 종속 변수에 더해지는 정규 분포의 표준 편차 coef : 불리언 (옵션, 디폴트 False) True 이면 선형 모형의 계수도 출력 random_state : 정수 (옵션, 디폴트 None) 난수 발생용 시작값 출력 X : [n_samples, n_features] 형상의 2차원 배열 독립 변수의 표본 데이터 y : [n_samples] 형상의 1차원 배열 또는 [n_samples, n_targets] 형상의 2차원 배열 종속 변수의 표본 데이터 coef : [n_features] 형상의 1차원 배열 또는 [n_features, n_targets] 형상의 2차원 배열 (옵션) 선형 모형의 계수, 입력 인수 coef가 True 인 경우에만 출력됨 예를 들어 독립 변수가 1개, 종속 변수가 1개 즉, 선형 모형이 다음과 같은 수식은 경우 $$ y = C_0 + C_1 x + e $$ 이러한 관계를 만족하는 표본 데이터는 다음과 같이 생성한다. End of explanation """ X, y, c = make_regression(n_samples=50, n_features=1, bias=100, noise=10, coef=True, random_state=0) plt.scatter(X, y, s=100) plt.show() """ Explanation: 위 선형 모형은 다음과 같다. $$ y = 100 + 79.1725 x $$ noise 인수를 증가시키면 $\text{Var}[e]$가 증가하고 bias 인수를 증가시키면 y 절편이 증가한다. End of explanation """ X, y, c = make_regression(n_samples=300, n_features=2, noise=10, coef=True, random_state=0) plt.scatter(X[:,0], X[:,1], c=y, s=100) plt.xlabel("x1") plt.ylabel("x2") plt.axis("equal") plt.show() """ Explanation: 이번에는 n_features 즉, 독립 변수가 2개인 표본 데이터를 생성하여 스캐터 플롯을 그리면 다음과 같다. 종속 변수 값은 점의 명암으로 표시하였다. End of explanation """ X, y, c = make_regression(n_samples=300, n_features=2, n_informative=1, noise=0, coef=True, random_state=0) plt.scatter(X[:,0], X[:,1], c=y, s=100) plt.xlabel("x1") plt.ylabel("x2") plt.axis("equal") plt.show() """ Explanation: 만약 실제로 y값에 영향을 미치는 독립 변수는 하나 뿐이라면 다음과 같이 사용한다. End of explanation """ X, y, c = make_regression(n_samples=300, n_features=2, effective_rank=1, noise=0, tail_strength=0, coef=True, random_state=0) plt.scatter(X[:,0], X[:,1], c=y, s=100) plt.xlabel("x1") plt.ylabel("x2") plt.axis("equal") plt.show() X, y, c = make_regression(n_samples=300, n_features=2, effective_rank=1, noise=0, tail_strength=1, coef=True, random_state=0) plt.scatter(X[:,0], X[:,1], c=y, s=100) plt.xlabel("x1") plt.ylabel("x2") plt.axis("equal") plt.show() """ Explanation: 만약 두 독립 변수가 상관관계가 있다면 다음과 같이 생성하고 스캐터 플롯에서도 이를 알아볼 수 있다. End of explanation """
carichte/pyasf
pyasf/examples/GeTe switching.ipynb
gpl-3.0
%matplotlib notebook import pylab as pl import pyasf import sympy as sp # symbolic computing from IPython.display import display, Math print_latex = lambda x: display(Math(sp.latex(x))) # sp.init_printing() ls GeTe = pyasf.unit_cell("ICSD_188458.cif") # initialize crystal structure object """ Explanation: Germanium telluride ferroelectric switching contrast This is an example script to show how to use pyasf to calculate the switching contrast of several Bragg reflections as a function of energy, e.g., near an absorption edge. End of explanation """ print_latex(GeTe.AU_positions) """ Explanation: Let's look at the positions in the asymmetric unit cell... End of explanation """ delta = sp.Symbol("delta") # Just a symbol delta_val = 0.0097 # The initial value of the symbol GeTe.subs[delta] = delta_val # needed later GeTe.AU_positions["Ge1"][2] = sp.S("1/4") - delta # redefine the positions GeTe.AU_positions["Te1"][2] = sp.S("3/4") + delta # redefine the positions """ Explanation: Comparing with the high-temperature cubic unit cell one can see that the atoms are displaced away from the high symmetry positions (1/4 and 3/4) by the same amount ($\delta = 0.0097$ in z direction). In Practice, this displacement may change significantly (piezo- or pyroelectricity?) or inverted (ferroelectric switching). Therefore, it is useful to define a variable which describes this displacement: End of explanation """ GeTe.get_tensor_symmetry() GeTe.build_unit_cell() """ Explanation: Yes, 1/4 is more precise than 0.25. There is a numerical limit to the precision so 0.2499999999999 = 0.25. Using sympy Symbols is more precise and in crystallography it is important especially when describing special (high symmetry) Wyckoff positions. The subs dictionary contains the numerical values used as substitute for final evaluation. Let's calculate the site symmetry and build the unit cell: End of explanation """ print_latex(GeTe.positions) GeTe.multiplicity """ Explanation: Now we have a positions dictionary containing the whole unit cell and some other stuff: End of explanation """ E = pl.linspace(7000, 30000, 1001) fig, ax = pl.subplots(1,2, figsize=(9.5,3)) GeTe.subs[delta] = delta_val F = GeTe.DAFS(E, (0,0,3), Uaniso=False) # because no anisotropic Uij is defined... ax[0].plot(E, abs(F)**2) GeTe.subs[delta] = -delta_val F = GeTe.DAFS(E, (0,0,3), Uaniso=False) ax[0].plot(E, abs(F)**2) GeTe.subs[delta] = delta_val F = GeTe.DAFS(E, (3,3,6), Uaniso=False) ax[1].plot(E, abs(F)**2) GeTe.subs[delta] = -delta_val F = GeTe.DAFS(E, (3,3,6), Uaniso=False) ax[1].plot(E, abs(F)**2) print_latex(GeTe.F_0) """ Explanation: Now we define an energy range in eV an play around a bit... End of explanation """ results = [] # some container to store results GeTe.calc_structure_factor(Temp = False, DD=False, DQ=False) # calculate (`cache`) all structure factors qmax = 1.5 # q=2*sin(theta)/lambda for R in GeTe.iter_rec_space(qmax): # iterate over all reflections in Ewald sphere #print R, GeTe.subs[delta] = delta_val F1 = GeTe.DAFS(E, R, force_refresh=False, fwhm_ev=1) GeTe.subs[delta] = -delta_val F2 = GeTe.DAFS(E, R, force_refresh=False, fwhm_ev=1) # minimum energy necessary to reach reflection: ## .theta is a symbolic expression ## .energy is just a symbol as well Emin = float(sp.sin(GeTe.theta.subs(GeTe.subs)) * GeTe.energy) if Emin>20000.: continue # skip if energy too high ind = E>Emin I1 = abs(F1)**2 # calculate intensity I2 = abs(F2)**2 I1 = I1[ind] I2 = I2[ind] if I1.max()<1e-2 and I2.max()<1e-2: # Intensity too small? continue c = abs(pl.log10(I1/I2)) # relative contrast idx_max = c.argmax() cmax = 10**c[idx_max] # get the maximum contrast Imax = 0.5 * (I1+I2)[idx_max] # ... and its intensity Emax = E[ind][idx_max] # ... and its energy theta_max = GeTe.theta_degrees(Emax) # ... as well as the theta value h,k,l = R results.append([h, k, l, cmax, Imax, Emax, theta_max]) print(results[-1]) results = pl.array(results) isort = results[:,3].argsort() results = results[isort[::-1]] # sort after contrast columns=("h", "k", "l", "contrast", "intensity", "energy", "theta") pl.savetxt("switch_contrast.txt", results, fmt=" %5i %5i %5i %10.3f %10.1f %10.1f %10.2f", header = "%5s %5s %5s %10s %10s %10s %10s"%columns) results """ Explanation: So we see already there is a significant contrast when switching the ferroelectric domains (inverting the displaecment). In practice, a strong relative change in intensity is easier to measure which is why weak reflections are often better... Let's now do a proper calculation of switching contrast for all reflections in a certain range of Q (momentum transfter). To increase speed, we don't recalculate the structure factor each time (is done in .DAFS). The crystal is not modified except for the numerical value of $\delta$, so no refreshing is needed... End of explanation """
rhiever/scipy_2015_sklearn_tutorial
notebooks/04.2 Model Complexity and GridSearchCV.ipynb
cc0-1.0
from figures import plot_kneighbors_regularization plot_kneighbors_regularization() """ Explanation: Parameter selection, Validation & Testing Most models have parameters that influence how complex a model they can learn. Remember using KNeighborsRegressor. If we change the number of neighbors we consider, we get a smoother and smoother prediction: End of explanation """ from sklearn.cross_validation import cross_val_score, KFold from sklearn.neighbors import KNeighborsRegressor # generate toy dataset: x = np.linspace(-3, 3, 100) rng = np.random.RandomState(42) y = np.sin(4 * x) + x + rng.normal(size=len(x)) X = x[:, np.newaxis] cv = KFold(n=len(x), shuffle=True) # for each parameter setting do cross_validation: for n_neighbors in [1, 3, 5, 10, 20]: scores = cross_val_score(KNeighborsRegressor(n_neighbors=n_neighbors), X, y, cv=cv) print("n_neighbors: %d, average score: %f" % (n_neighbors, np.mean(scores))) """ Explanation: In the above figure, we see fits for three different values of n_neighbors. For n_neighbors=2, the data is overfit, the model is too flexible and can adjust too much to the noise in the training data. For n_neighbors=20, the model is not flexible enough, and can not model the variation in the data appropriately. In the middle, for n_neighbors = 5, we have found a good mid-point. It fits the data fairly well, and does not suffer from the overfit or underfit problems seen in the figures on either side. What we would like is a way to quantitatively identify overfit and underfit, and optimize the hyperparameters (in this case, the polynomial degree d) in order to determine the best algorithm. We trade off remembering too much about the particularities and noise of the training data vs. not modeling enough of the variability. This is a trade-off that needs to be made in basically every machine learning application and is a central concept, called bias-variance-tradeoff or "overfitting vs underfitting". <img src="figures/overfitting_underfitting_cartoon.svg" width="100%"> Hyperparameters, Over-fitting, and Under-fitting Unfortunately, there is no general rule how to find the sweet spot, and so machine learning practitioners have to find the best trade-off of model-complexity and generalization by trying several parameter settings. Most commonly this is done using a brute force search, for example over multiple values of n_neighbors: End of explanation """ from sklearn.learning_curve import validation_curve n_neighbors = [1, 3, 5, 10, 20, 50] train_errors, test_errors = validation_curve(KNeighborsRegressor(), X, y, param_name="n_neighbors", param_range=n_neighbors, cv=cv) plt.plot(n_neighbors, train_errors.mean(axis=1), label="train error") plt.plot(n_neighbors, test_errors.mean(axis=1), label="test error") plt.legend(loc="best") """ Explanation: There is a function in scikit-learn, called validation_plot to reproduce the cartoon figure above. It plots one parameter, such as the number of neighbors, against training and validation error (using cross-validation): End of explanation """ from sklearn.cross_validation import cross_val_score, KFold from sklearn.svm import SVR # each parameter setting do cross_validation: for C in [0.001, 0.01, 0.1, 1, 10]: for gamma in [0.001, 0.01, 0.1, 1]: scores = cross_val_score(SVR(C=C, gamma=gamma), X, y, cv=cv) print("C: %f, gamma: %f, average score: %f" % (C, gamma, np.mean(scores))) """ Explanation: Note that many neighbors mean a "smooth" or "simple" model, so the plot is the mirror image of the diagram above. If multiple parameters are important, like the parameters C and gamma in an SVM (more about that later), all possible combinations are tried: End of explanation """ from sklearn.grid_search import GridSearchCV param_grid = {'C': [0.001, 0.01, 0.1, 1, 10], 'gamma': [0.001, 0.01, 0.1, 1]} grid = GridSearchCV(SVR(), param_grid=param_grid, cv=cv, verbose=3) """ Explanation: As this is such a very common pattern, there is a built-in class for this in scikit-learn, GridSearchCV. GridSearchCV takes a dictionary that describes the parameters that should be tried and a model to train. The grid of parameters is defined as a dictionary, where the keys are the parameters and the values are the settings to be tested. End of explanation """ grid.fit(X, y) """ Explanation: One of the great things about GridSearchCV is that it is a meta-estimator. It takes an estimator like SVR above, and creates a new estimator, that behaves exactly the same - in this case, like a regressor. So we can call fit on it, to train it: End of explanation """ grid.predict(X) """ Explanation: What fit does is a bit more involved then what we did above. First, it runs the same loop with cross-validation, to find the best parameter combination. Once it has the best combination, it runs fit again on all data passed to fit (without cross-validation), to built a single new model using the best parameter setting. Then, as with all models, we can use predict or score: End of explanation """ print(grid.best_score_) print(grid.best_params_) """ Explanation: You can inspect the best parameters found by GridSearchCV in the best_params_ attribute, and the best score in the best_score_ attribute: End of explanation """ from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) param_grid = {'C': [0.001, 0.01, 0.1, 1, 10], 'gamma': [0.001, 0.01, 0.1, 1]} cv = KFold(n=len(X_train), n_folds=10, shuffle=True) grid = GridSearchCV(SVR(), param_grid=param_grid, cv=cv) grid.fit(X_train, y_train) grid.score(X_test, y_test) """ Explanation: There is a problem with using this score for evaluation, however. You might be making what is called a multiple hypothesis testing error. If you try very many parameter settings, some of them will work better just by chance, and the score that you obtained might not reflect how your model would perform on new unseen data. Therefore, it is good to split off a separate test-set before performing grid-search. This pattern can be seen as a training-validation-test split, and is common in machine learning: <img src="figures/grid_search_cross_validation.svg" width="100%"> We can do this very easily by splitting of some test data using train_test_split, training GridSearchCV on the training set, and applying the score method to the test set: End of explanation """ from sklearn.cross_validation import train_test_split, ShuffleSplit X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) param_grid = {'C': [0.001, 0.01, 0.1, 1, 10], 'gamma': [0.001, 0.01, 0.1, 1]} single_split_cv = ShuffleSplit(len(X_train), 1) grid = GridSearchCV(SVR(), param_grid=param_grid, cv=single_split_cv, verbose=3) grid.fit(X_train, y_train) grid.score(X_test, y_test) """ Explanation: Some practitioners go for an easier scheme, splitting the data simply into three parts, training, validation and testing. This is a possible alternative if your training set is very large, or it is infeasible to train many models using cross-validation because training a model takes very long. You can do this with scikit-learn for example by splitting of a test-set and then applying GridSearchCV with ShuffleSplit cross-validation with a single iteration: <img src="figures/train_validation_test2.svg" width="100%"> End of explanation """ clf = GridSearchCV(SVR(), param_grid=param_grid) cross_val_score(clf, X, y) """ Explanation: This is much faster, but will likely result worse hyperparameters and therefore worse results. End of explanation """
kabrapratik28/Stanford_courses
cs231n/assignment3/StyleTransfer-TensorFlow.ipynb
apache-2.0
%load_ext autoreload %autoreload 2 from scipy.misc import imread, imresize import numpy as np from scipy.misc import imread import matplotlib.pyplot as plt # Helper functions to deal with image preprocessing from cs231n.image_utils import load_image, preprocess_image, deprocess_image %matplotlib inline def get_session(): """Create a session that dynamically allocates memory.""" # See: https://www.tensorflow.org/tutorials/using_gpu#allowing_gpu_memory_growth config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) return session def rel_error(x,y): return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Older versions of scipy.misc.imresize yield different results # from newer versions, so we check to make sure scipy is up to date. def check_scipy(): import scipy vnum = int(scipy.__version__.split('.')[1]) assert vnum >= 16, "You must install SciPy >= 0.16.0 to complete this notebook." check_scipy() """ Explanation: Style Transfer In this notebook we will implement the style transfer technique from "Image Style Transfer Using Convolutional Neural Networks" (Gatys et al., CVPR 2015). The general idea is to take two images, and produce a new image that reflects the content of one but the artistic "style" of the other. We will do this by first formulating a loss function that matches the content and style of each respective image in the feature space of a deep network, and then performing gradient descent on the pixels of the image itself. The deep network we use as a feature extractor is SqueezeNet, a small model that has been trained on ImageNet. You could use any network, but we chose SqueezeNet here for its small size and efficiency. Here's an example of the images you'll be able to produce by the end of this notebook: Setup End of explanation """ from cs231n.classifiers.squeezenet import SqueezeNet import tensorflow as tf tf.reset_default_graph() # remove all existing variables in the graph sess = get_session() # start a new Session # Load pretrained SqueezeNet model SAVE_PATH = 'cs231n/datasets/squeezenet.ckpt' if not os.path.exists(SAVE_PATH): raise ValueError("You need to download SqueezeNet!") model = SqueezeNet(save_path=SAVE_PATH, sess=sess) # Load data for testing content_img_test = preprocess_image(load_image('styles/tubingen.jpg', size=192))[None] style_img_test = preprocess_image(load_image('styles/starry_night.jpg', size=192))[None] answers = np.load('style-transfer-checks-tf.npz') """ Explanation: Load the pretrained SqueezeNet model. This model has been ported from PyTorch, see cs231n/classifiers/squeezenet.py for the model architecture. To use SqueezeNet, you will need to first download the weights by changing into the cs231n/datasets directory and running get_squeezenet_tf.sh . Note that if you ran get_assignment3_data.sh then SqueezeNet will already be downloaded. End of explanation """ def content_loss(content_weight, content_current, content_original): """ Compute the content loss for style transfer. Inputs: - content_weight: scalar constant we multiply the content_loss by. - content_current: features of the current image, Tensor with shape [1, height, width, channels] - content_target: features of the content image, Tensor with shape [1, height, width, channels] Returns: - scalar content loss """ pass """ Explanation: Computing Loss We're going to compute the three components of our loss function now. The loss function is a weighted sum of three terms: content loss + style loss + total variation loss. You'll fill in the functions that compute these weighted terms below. Content loss We can generate an image that reflects the content of one image and the style of another by incorporating both in our loss function. We want to penalize deviations from the content of the content image and deviations from the style of the style image. We can then use this hybrid loss function to perform gradient descent not on the parameters of the model, but instead on the pixel values of our original image. Let's first write the content loss function. Content loss measures how much the feature map of the generated image differs from the feature map of the source image. We only care about the content representation of one layer of the network (say, layer $\ell$), that has feature maps $A^\ell \in \mathbb{R}^{1 \times C_\ell \times H_\ell \times W_\ell}$. $C_\ell$ is the number of filters/channels in layer $\ell$, $H_\ell$ and $W_\ell$ are the height and width. We will work with reshaped versions of these feature maps that combine all spatial positions into one dimension. Let $F^\ell \in \mathbb{R}^{N_\ell \times M_\ell}$ be the feature map for the current image and $P^\ell \in \mathbb{R}^{N_\ell \times M_\ell}$ be the feature map for the content source image where $M_\ell=H_\ell\times W_\ell$ is the number of elements in each feature map. Each row of $F^\ell$ or $P^\ell$ represents the vectorized activations of a particular filter, convolved over all positions of the image. Finally, let $w_c$ be the weight of the content loss term in the loss function. Then the content loss is given by: $L_c = w_c \times \sum_{i,j} (F_{ij}^{\ell} - P_{ij}^{\ell})^2$ End of explanation """ def content_loss_test(correct): content_layer = 3 content_weight = 6e-2 c_feats = sess.run(model.extract_features()[content_layer], {model.image: content_img_test}) bad_img = tf.zeros(content_img_test.shape) feats = model.extract_features(bad_img)[content_layer] student_output = sess.run(content_loss(content_weight, c_feats, feats)) error = rel_error(correct, student_output) print('Maximum error is {:.3f}'.format(error)) content_loss_test(answers['cl_out']) """ Explanation: Test your content loss. You should see errors less than 0.001. End of explanation """ def gram_matrix(features, normalize=True): """ Compute the Gram matrix from features. Inputs: - features: Tensor of shape (1, H, W, C) giving features for a single image. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram matrix by the number of neurons (H * W * C) Returns: - gram: Tensor of shape (C, C) giving the (optionally normalized) Gram matrices for the input image. """ pass """ Explanation: Style loss Now we can tackle the style loss. For a given layer $\ell$, the style loss is defined as follows: First, compute the Gram matrix G which represents the correlations between the responses of each filter, where F is as above. The Gram matrix is an approximation to the covariance matrix -- we want the activation statistics of our generated image to match the activation statistics of our style image, and matching the (approximate) covariance is one way to do that. There are a variety of ways you could do this, but the Gram matrix is nice because it's easy to compute and in practice shows good results. Given a feature map $F^\ell$ of shape $(1, C_\ell, M_\ell)$, the Gram matrix has shape $(1, C_\ell, C_\ell)$ and its elements are given by: $$G_{ij}^\ell = \sum_k F^{\ell}{ik} F^{\ell}{jk}$$ Assuming $G^\ell$ is the Gram matrix from the feature map of the current image, $A^\ell$ is the Gram Matrix from the feature map of the source style image, and $w_\ell$ a scalar weight term, then the style loss for the layer $\ell$ is simply the weighted Euclidean distance between the two Gram matrices: $$L_s^\ell = w_\ell \sum_{i, j} \left(G^\ell_{ij} - A^\ell_{ij}\right)^2$$ In practice we usually compute the style loss at a set of layers $\mathcal{L}$ rather than just a single layer $\ell$; then the total style loss is the sum of style losses at each layer: $$L_s = \sum_{\ell \in \mathcal{L}} L_s^\ell$$ Begin by implementing the Gram matrix computation below: End of explanation """ def gram_matrix_test(correct): gram = gram_matrix(model.extract_features()[5]) student_output = sess.run(gram, {model.image: style_img_test}) error = rel_error(correct, student_output) print('Maximum error is {:.3f}'.format(error)) gram_matrix_test(answers['gm_out']) """ Explanation: Test your Gram matrix code. You should see errors less than 0.001. End of explanation """ def style_loss(feats, style_layers, style_targets, style_weights): """ Computes the style loss at a set of layers. Inputs: - feats: list of the features at every layer of the current image, as produced by the extract_features function. - style_layers: List of layer indices into feats giving the layers to include in the style loss. - style_targets: List of the same length as style_layers, where style_targets[i] is a Tensor giving the Gram matrix the source style image computed at layer style_layers[i]. - style_weights: List of the same length as style_layers, where style_weights[i] is a scalar giving the weight for the style loss at layer style_layers[i]. Returns: - style_loss: A Tensor contataining the scalar style loss. """ # Hint: you can do this with one for loop over the style layers, and should # not be very much code (~5 lines). You will need to use your gram_matrix function. pass """ Explanation: Next, implement the style loss: End of explanation """ def style_loss_test(correct): style_layers = [1, 4, 6, 7] style_weights = [300000, 1000, 15, 3] feats = model.extract_features() style_target_vars = [] for idx in style_layers: style_target_vars.append(gram_matrix(feats[idx])) style_targets = sess.run(style_target_vars, {model.image: style_img_test}) s_loss = style_loss(feats, style_layers, style_targets, style_weights) student_output = sess.run(s_loss, {model.image: content_img_test}) error = rel_error(correct, student_output) print('Error is {:.3f}'.format(error)) style_loss_test(answers['sl_out']) """ Explanation: Test your style loss implementation. The error should be less than 0.001. End of explanation """ def tv_loss(img, tv_weight): """ Compute total variation loss. Inputs: - img: Tensor of shape (1, H, W, 3) holding an input image. - tv_weight: Scalar giving the weight w_t to use for the TV loss. Returns: - loss: Tensor holding a scalar giving the total variation loss for img weighted by tv_weight. """ # Your implementation should be vectorized and not require any loops! pass """ Explanation: Total-variation regularization It turns out that it's helpful to also encourage smoothness in the image. We can do this by adding another term to our loss that penalizes wiggles or "total variation" in the pixel values. You can compute the "total variation" as the sum of the squares of differences in the pixel values for all pairs of pixels that are next to each other (horizontally or vertically). Here we sum the total-variation regualarization for each of the 3 input channels (RGB), and weight the total summed loss by the total variation weight, $w_t$: $L_{tv} = w_t \times \sum_{c=1}^3\sum_{i=1}^{H-1} \sum_{j=1}^{W-1} \left( (x_{i,j+1, c} - x_{i,j,c})^2 + (x_{i+1, j,c} - x_{i,j,c})^2 \right)$ In the next cell, fill in the definition for the TV loss term. To receive full credit, your implementation should not have any loops. End of explanation """ def tv_loss_test(correct): tv_weight = 2e-2 t_loss = tv_loss(model.image, tv_weight) student_output = sess.run(t_loss, {model.image: content_img_test}) error = rel_error(correct, student_output) print('Error is {:.3f}'.format(error)) tv_loss_test(answers['tv_out']) """ Explanation: Test your TV loss implementation. Error should be less than 0.001. End of explanation """ def style_transfer(content_image, style_image, image_size, style_size, content_layer, content_weight, style_layers, style_weights, tv_weight, init_random = False): """Run style transfer! Inputs: - content_image: filename of content image - style_image: filename of style image - image_size: size of smallest image dimension (used for content loss and generated image) - style_size: size of smallest style image dimension - content_layer: layer to use for content loss - content_weight: weighting on content loss - style_layers: list of layers to use for style loss - style_weights: list of weights to use for each layer in style_layers - tv_weight: weight of total variation regularization term - init_random: initialize the starting image to uniform random noise """ # Extract features from the content image content_img = preprocess_image(load_image(content_image, size=image_size)) feats = model.extract_features(model.image) content_target = sess.run(feats[content_layer], {model.image: content_img[None]}) # Extract features from the style image style_img = preprocess_image(load_image(style_image, size=style_size)) style_feat_vars = [feats[idx] for idx in style_layers] style_target_vars = [] # Compute list of TensorFlow Gram matrices for style_feat_var in style_feat_vars: style_target_vars.append(gram_matrix(style_feat_var)) # Compute list of NumPy Gram matrices by evaluating the TensorFlow graph on the style image style_targets = sess.run(style_target_vars, {model.image: style_img[None]}) # Initialize generated image to content image if init_random: img_var = tf.Variable(tf.random_uniform(content_img[None].shape, 0, 1), name="image") else: img_var = tf.Variable(content_img[None], name="image") # Extract features on generated image feats = model.extract_features(img_var) # Compute loss c_loss = content_loss(content_weight, feats[content_layer], content_target) s_loss = style_loss(feats, style_layers, style_targets, style_weights) t_loss = tv_loss(img_var, tv_weight) loss = c_loss + s_loss + t_loss # Set up optimization hyperparameters initial_lr = 3.0 decayed_lr = 0.1 decay_lr_at = 180 max_iter = 200 # Create and initialize the Adam optimizer lr_var = tf.Variable(initial_lr, name="lr") # Create train_op that updates the generated image when run with tf.variable_scope("optimizer") as opt_scope: train_op = tf.train.AdamOptimizer(lr_var).minimize(loss, var_list=[img_var]) # Initialize the generated image and optimization variables opt_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=opt_scope.name) sess.run(tf.variables_initializer([lr_var, img_var] + opt_vars)) # Create an op that will clamp the image values when run clamp_image_op = tf.assign(img_var, tf.clip_by_value(img_var, -1.5, 1.5)) f, axarr = plt.subplots(1,2) axarr[0].axis('off') axarr[1].axis('off') axarr[0].set_title('Content Source Img.') axarr[1].set_title('Style Source Img.') axarr[0].imshow(deprocess_image(content_img)) axarr[1].imshow(deprocess_image(style_img)) plt.show() plt.figure() # Hardcoded handcrafted for t in range(max_iter): # Take an optimization step to update img_var sess.run(train_op) if t < decay_lr_at: sess.run(clamp_image_op) if t == decay_lr_at: sess.run(tf.assign(lr_var, decayed_lr)) if t % 100 == 0: print('Iteration {}'.format(t)) img = sess.run(img_var) plt.imshow(deprocess_image(img[0], rescale=True)) plt.axis('off') plt.show() print('Iteration {}'.format(t)) img = sess.run(img_var) plt.imshow(deprocess_image(img[0], rescale=True)) plt.axis('off') plt.show() """ Explanation: Style Transfer Lets put it all together and make some beautiful images! The style_transfer function below combines all the losses you coded up above and optimizes for an image that minimizes the total loss. End of explanation """ # Composition VII + Tubingen params1 = { 'content_image' : 'styles/tubingen.jpg', 'style_image' : 'styles/composition_vii.jpg', 'image_size' : 192, 'style_size' : 512, 'content_layer' : 3, 'content_weight' : 5e-2, 'style_layers' : (1, 4, 6, 7), 'style_weights' : (20000, 500, 12, 1), 'tv_weight' : 5e-2 } style_transfer(**params1) # Scream + Tubingen params2 = { 'content_image':'styles/tubingen.jpg', 'style_image':'styles/the_scream.jpg', 'image_size':192, 'style_size':224, 'content_layer':3, 'content_weight':3e-2, 'style_layers':[1, 4, 6, 7], 'style_weights':[200000, 800, 12, 1], 'tv_weight':2e-2 } style_transfer(**params2) # Starry Night + Tubingen params3 = { 'content_image' : 'styles/tubingen.jpg', 'style_image' : 'styles/starry_night.jpg', 'image_size' : 192, 'style_size' : 192, 'content_layer' : 3, 'content_weight' : 6e-2, 'style_layers' : [1, 4, 6, 7], 'style_weights' : [300000, 1000, 15, 3], 'tv_weight' : 2e-2 } style_transfer(**params3) """ Explanation: Generate some pretty pictures! Try out style_transfer on the three different parameter sets below. Make sure to run all three cells. Feel free to add your own, but make sure to include the results of style transfer on the third parameter set (starry night) in your submitted notebook. The content_image is the filename of content image. The style_image is the filename of style image. The image_size is the size of smallest image dimension of the content image (used for content loss and generated image). The style_size is the size of smallest style image dimension. The content_layer specifies which layer to use for content loss. The content_weight gives weighting on content loss in the overall loss function. Increasing the value of this parameter will make the final image look more realistic (closer to the original content). style_layers specifies a list of which layers to use for style loss. style_weights specifies a list of weights to use for each layer in style_layers (each of which will contribute a term to the overall style loss). We generally use higher weights for the earlier style layers because they describe more local/smaller scale features, which are more important to texture than features over larger receptive fields. In general, increasing these weights will make the resulting image look less like the original content and more distorted towards the appearance of the style image. tv_weight specifies the weighting of total variation regularization in the overall loss function. Increasing this value makes the resulting image look smoother and less jagged, at the cost of lower fidelity to style and content. Below the next three cells of code (in which you shouldn't change the hyperparameters), feel free to copy and paste the parameters to play around them and see how the resulting image changes. End of explanation """ # Feature Inversion -- Starry Night + Tubingen params_inv = { 'content_image' : 'styles/tubingen.jpg', 'style_image' : 'styles/starry_night.jpg', 'image_size' : 192, 'style_size' : 192, 'content_layer' : 3, 'content_weight' : 6e-2, 'style_layers' : [1, 4, 6, 7], 'style_weights' : [0, 0, 0, 0], # we discard any contributions from style to the loss 'tv_weight' : 2e-2, 'init_random': True # we want to initialize our image to be random } style_transfer(**params_inv) """ Explanation: Feature Inversion The code you've written can do another cool thing. In an attempt to understand the types of features that convolutional networks learn to recognize, a recent paper [1] attempts to reconstruct an image from its feature representation. We can easily implement this idea using image gradients from the pretrained network, which is exactly what we did above (but with two different feature representations). Now, if you set the style weights to all be 0 and initialize the starting image to random noise instead of the content source image, you'll reconstruct an image from the feature representation of the content source image. You're starting with total noise, but you should end up with something that looks quite a bit like your original image. (Similarly, you could do "texture synthesis" from scratch if you set the content weight to 0 and initialize the starting image to random noise, but we won't ask you to do that here.) [1] Aravindh Mahendran, Andrea Vedaldi, "Understanding Deep Image Representations by Inverting them", CVPR 2015 End of explanation """
jrmontag/Data-Science-45min-Intros
concurrency/enriching_the_enricher.ipynb
unlicense
DT_FORMAT_STR = "%Y-%m-%dT%H:%M:%S.%f" def stream_of_tweets(n=10): # generator function to generate sequential tweets for i in range(n): time.sleep(0.01) tweet = { 'body':'I am tweet #' + str(i), 'postedTime':datetime.datetime.now().strftime(DT_FORMAT_STR) } yield json.dumps(tweet) for tweet in stream_of_tweets(2): print(tweet) for tweet in stream_of_tweets(): print(tweet) """ Explanation: Introduction We're going to improve the tweet_enricher.py script from Gnip-Analysis-Pipeline. We'll make a simplified version and create variations that improve it in various ways. To enrich tweets, we will need: * a tweet source * a version of the enricher script (we'll use a function) * one or more enrichment classes See the README for an explanation of these components. A stream of tweets The enrichment step of the analysis pipeline is designed to work on a potentially infinite stream of tweets. A generator will simulate this nicely. End of explanation """ def enrich_tweets_1(istream,enrichment_class_list): """ simplified copy of tweet_enricher.py """ enrichment_instance_list = [enrichment_class() for enrichment_class in enrichment_class_list] for tweet_str in istream: try: tweet = json.loads(tweet_str) except ValueError: continue for instance in enrichment_instance_list: instance.enrich(tweet) sys.stdout.write( json.dumps(tweet) + '\n') """ Explanation: The tweet enricher End of explanation """ class TestEnrichment(): value = 42 def enrich(self,tweet): if 'enrichments' not in tweet: tweet['enrichments'] = {} tweet['enrichments']['TestEnrichment'] = self.value class TestEnrichment2(): value = 48 def enrich(self,tweet): if 'enrichments' not in tweet: tweet['enrichments'] = {} tweet['enrichments']['TestEnrichment2'] = self.value enrich_tweets_1(stream_of_tweets(5),[TestEnrichment,TestEnrichment2]) """ Explanation: Enrichment classes End of explanation """ DT_FORMAT_STR = "%Y-%m-%dT%H:%M:%S.%f" def stream_of_tweets(n=10): # generator function to generate sequential tweets for i in range(n): time.sleep(0.01) tweet = { 'body':'I am tweet #' + str(i), 'postedTime':datetime.datetime.now().strftime(DT_FORMAT_STR) } yield tweet # <<-- this is the only change from above class EnrichmentBase(): def enrich(self,tweet): if 'enrichments' not in tweet: tweet['enrichments'] = {} tweet['enrichments'][type(self).__name__] = self.enrichment_value(tweet) class TestEnrichment(EnrichmentBase): def enrichment_value(self,tweet): return 42 def enrich_tweets_2(istream,enrichment_class,**kwargs): """ simplify `enrich_tweets_1 : only one enrichment generator function leave tweets as dict objects """ enrichment_instance = enrichment_class() for tweet in istream: enrichment_instance.enrich(tweet) sys.stdout.write( str(tweet) + '\n') %%time enrich_tweets_2( istream=stream_of_tweets(5), enrichment_class=TestEnrichment ) """ Explanation: Convenience and simplification remove JSON-(de)serialization use only one enrichment class, derived from a base class End of explanation """ class SlowEnrichment(EnrichmentBase): def enrichment_value(self,tweet): # get the tweet number from body # and sleep accordingly seconds = int(tweet['body'][-1]) + 1 time.sleep(seconds) return str(seconds) + ' second nap' %%time enrich_tweets_2( istream=stream_of_tweets(5), enrichment_class=SlowEnrichment ) """ Explanation: The problem End of explanation """ import threading def enrich_tweets_3(istream,enrichment_class): """ use threads to run `enrich` """ enrichment_instance = enrichment_class() # we need to hang onto the threads spawned threads = [] # ...and the tweets enriched_tweets = [] for tweet in istream: # run `enrich` in a new thread thread = threading.Thread( target=enrichment_instance.enrich, args=(tweet,) ) thread.start() # runs the function in a new thread threads.append(thread) enriched_tweets.append(tweet) sys.stderr.write('submitted all tweets to threads' + '\n') for thread in threads: thread.join() # blocks until thread finishes sys.stderr.write('all threads finished' + '\n') for enriched_tweet in enriched_tweets: sys.stdout.write( str(enriched_tweet) + '\n') %%time enrich_tweets_3( istream=stream_of_tweets(5), enrichment_class=SlowEnrichment ) """ Explanation: commentary tweets are run sequentially tweet dictionary is mutated by enrich yield enriched tweet when ready problems there's no reason for subsequent enrichment operations to be blocked by a sleep call (imagine the sleep is a web request). Threads Despite what you make have heard about Python's Global Interpreter Lock (GIL), core library (read: those written in C) routines can release the GIL while they are waiting on the operating system. The time.sleep function is a good example of this, but extends to things like the requests package. End of explanation """ def enrich_tweets_4(istream,enrichment_class,**kwargs): """ better use of threads """ enrichment_instance = enrichment_class() queue = [] # queue of (thread,tweet) tuples max_threads = kwargs['max_threads'] for tweet in istream: # run `enrich` in a new thread thread = threading.Thread( target=enrichment_instance.enrich, args=(tweet,) ) thread.start() queue.append((thread,tweet)) # don't accept more tweets until a thread is free while len(queue) >= max_threads: # iterate through all threads # when threads are dead, remove from queue and yield tweet new_queue = [] for thread,tweet in queue: if thread.is_alive(): new_queue.append((thread,tweet)) else: sys.stdout.write( str(tweet) + '\n') # print enriched tweet queue = new_queue time.sleep(0.1) sys.stderr.write('submitted all tweets to threads' + '\n') # cleanup threads that didn't finish while iterating through tweets for thread,tweet in queue: thread.join() time.sleep(0.01) sys.stdout.write( str(tweet) + '\n') %%time enrich_tweets_4( istream=stream_of_tweets(5), enrichment_class=SlowEnrichment, max_threads = 1 # play with this number ) """ Explanation: commentary run each enrich call in a separate thread memory is shared between threads execution takes roughly as long as the slowest enrichment problems we had to maintain lists of threads and enriched tweets no limitation on number of threads store all enriched tweets in memory End of explanation """ from concurrent import futures def enrich_tweets_5(istream,enrichment_class,**kwargs): """ use concurrent.futures instead of bare Threads """ enrichment_instance = enrichment_class() with futures.ThreadPoolExecutor(max_workers=kwargs['max_workers']) as executor: future_to_tweet = {} for tweet in istream: # run `enrich` in a new thread, via a Future future = executor.submit( enrichment_instance.enrich, tweet ) future_to_tweet[future] = tweet sys.stderr.write('submitted all tweets as futures' + '\n') for future in futures.as_completed(future_to_tweet): sys.stdout.write( str(future_to_tweet[future]) + '\n') %%time enrich_tweets_5( istream=stream_of_tweets(5), enrichment_class=SlowEnrichment, max_workers = 5 ) """ Explanation: commentary we limited the number of alive threads we store no more than max_threads tweets in memory problems awkward queue length management have to manage individual threads Futures A Future is an object that represents a deferred computation that may or may not have completed. That computation might be run on a separate thread but the Future itself doesn't care where the operation is run. End of explanation """ class NewEnrichmentBase(): def enrich(self,tweet): if 'enrichments' not in tweet: tweet['enrichments'] = {} tweet['enrichments'][type(self).__name__] = self.enrichment_value(tweet) return tweet # <<-- the only new piece class NewSlowEnrichment(NewEnrichmentBase): def enrichment_value(self,tweet): # get the tweet number from body # and sleep accordingly seconds = int(tweet['body'].split('#')[-1]) + 1 if seconds > 9: seconds = 1 time.sleep(seconds) return str(seconds) + ' second nap' from concurrent import futures def enrich_tweets_6(istream,enrichment_class,**kwargs): """ new enrichment protocol """ enrichment_instance = enrichment_class() with futures.ThreadPoolExecutor(max_workers=kwargs['max_workers']) as executor: futures_list = [] # <<-- this is now just a list of futures for tweet in istream: # run `enrich` in a new thread, via a Future future = executor.submit( enrichment_instance.enrich, tweet ) futures_list.append(future) sys.stderr.write('submitted all tweets as futures' + '\n') for future in futures.as_completed(futures_list): sys.stdout.write( str(future.result()) + '\n') %%time enrich_tweets_6( istream=stream_of_tweets(5), enrichment_class=NewSlowEnrichment, max_workers = 5 ) """ Explanation: commentary futures.as_completed yields results as execution finishes this is better than sequentially join-ing threads, as above, because results are yielded as soon as they become available problems we haven't limited the number of concurrent workers we can't yield any results until we've finished looping through the tweet we have to maintain a dict of all tweets and futures Change the enrichment protocol Currently, classes follow the enrichment protocol by defining an enrich method with the appropriate signature. Nothing is specififed regarding the return type or value. We will now change this protocol such that the enrich method returns the enriched tweet dictionary, rather than relying on the mutability of the tweet dictionary passed to enrich. This allows us: * to "store" tweets in the Future and retrieve the enriched versions, obviating the need to maintain a record of all observed tweets * to generalize the submission interface such that we don't rely on the assumption of shared memory between the threads End of explanation """ from concurrent import futures def enrich_tweets_7(istream,enrichment_class,**kwargs): """ """ def print_the_tweet(future): sys.stdout.write( str(future.result()) + '\n') enrichment_instance = enrichment_class() with futures.ThreadPoolExecutor(max_workers=kwargs['max_workers']) as executor: for tweet in istream: # run `enrich` in a new thread, via a Future future = executor.submit( enrichment_instance.enrich, tweet ) future.add_done_callback(print_the_tweet) sys.stderr.write('submitted all tweets as futures' + '\n') %%time enrich_tweets_7( istream=stream_of_tweets(5), enrichment_class=NewSlowEnrichment, max_workers = 5 ) """ Explanation: commentary as before, results are yielded as soon as they are ready we keep no explicit record of all tweets problems we don't get any results until we've iterated through all tweets, so we still keep an implicit list of all tweets we have no limitation on the number of concurrent Future objects End of explanation """ from concurrent import futures def enrich_tweets_8(istream,enrichment_class,**kwargs): """ """ max_workers = kwargs['max_workers'] def print_the_tweet(future): sys.stdout.write( str(future.result()) + '\n') enrichment_instance = enrichment_class() with futures.ThreadPoolExecutor(max_workers=max_workers) as executor: futures_list = [] for tweet in istream: # run `enrich` in a new thread, via a Future future = executor.submit( enrichment_instance.enrich, tweet ) future.add_done_callback(print_the_tweet) futures_list.append(future) futures_list[:] = [future for future in futures_list if future.running()] while len(futures_list) >= max_workers: futures_list[:] = [future for future in futures_list if future.running()] time.sleep(0.5) sys.stderr.write('submitted all tweets as futures' + '\n') %%time enrich_tweets_8( istream=stream_of_tweets(50), enrichment_class=NewSlowEnrichment, max_workers = 5 ) """ Explanation: commentary no explicit list of futures callback function is run in the main thread putting the print statement in the callback function allows the output to run asynchronously problems we haven't limited the number of queued operations in the executor End of explanation """ import queue def enrich_tweets_9(istream,enrichment_class,**kwargs): """ use a pool of threads, each running a worker reading from a common queue """ max_workers = kwargs['max_workers'] queue_size = kwargs['queue_size'] enrichment_instance = enrichment_class() def worker(): """ this function runs on new threads and reads from a common queue """ time.sleep(0.5) while True: tweet = q.get() if tweet is None: # this is the signal to exit break enriched_tweet = enrichment_instance.enrich(tweet) sys.stdout.write(str(enriched_tweet) + '\n') q.task_done() time.sleep(0.1) thread_pool = [threading.Thread(target=worker) for _ in range(max_workers)] [thread.start() for thread in thread_pool] q = queue.Queue(maxsize=queue_size) for tweet in istream: q.put(tweet) sys.stderr.write('submitted all tweets to threads' + '\n') # block until queue is empty q.join() # kill the threads for _ in range(len(thread_pool)): q.put(None) for thread in thread_pool: thread.join() %%time enrich_tweets_9( istream=stream_of_tweets(10), enrichment_class=NewSlowEnrichment, max_workers = 1, queue_size=5 ) """ Explanation: commentary we can now safely stream tweets into the enrich function, without queueing every tweet in the executor problems the buffering of calls to submit is still a bit of a hack, and potentially slow End of explanation """ from random import randrange import hashlib class CPUBoundEnrichment(NewEnrichmentBase): def enrichment_value(self,tweet): # make a SHA-256 hash of random byte arrays data = bytearray(randrange(256) for i in range(2**21)) algo = hashlib.new('sha256') algo.update(data) return algo.hexdigest() def enrich_tweets_10(istream,enrichment_class,**kwargs): """ use a `ProcessPoolExecutor` to manage processes """ max_workers=kwargs['max_workers'] executor_name=kwargs['executor_name'] def print_the_tweet(future): sys.stdout.write( str(future.result()) + '\n') enrichment_instance = enrichment_class() with getattr(futures,executor_name)(max_workers=max_workers) as executor: # <- this is the only change from #8 futures_list = [] for tweet in istream: # run `enrich` in a new thread, via a Future future = executor.submit( enrichment_instance.enrich, tweet ) future.add_done_callback(print_the_tweet) futures_list.append(future) # have to throttle with this hack futures_list[:] = [future for future in futures_list if future.running()] while len(futures_list) >= max_workers: futures_list[:] = [future for future in futures_list if future.running()] time.sleep(0.5) sys.stderr.write('submitted all tweets as futures' + '\n') %%time enrich_tweets_10( istream=stream_of_tweets(10), enrichment_class=CPUBoundEnrichment, executor_name='ProcessPoolExecutor', max_workers = 2, ) """ Explanation: commentary tweets are proccessed and returned fully asynchronously on a fixed pool of threads the queue throttles the incoming tweet stream problems what about CPU-bound tasks? End of explanation """
nickkunz/smogn
examples/smogn_example_1_beg.ipynb
gpl-3.0
## suppress install output %%capture ## install pypi release # !pip install smogn ## install developer version !pip install git+https://github.com/nickkunz/smogn.git """ Explanation: SMOGN (0.1.0): Usage Example 1: Beginner Installation First, we install SMOGN from the Github repository. Alternatively, we could install from the official PyPI distribution. However, the developer version is utilized here for the latest release. End of explanation """ ## load dependencies import smogn import pandas import seaborn """ Explanation: Dependencies Next, we load the required dependencies. Here we import smogn to later apply Synthetic Minority Over-Sampling Technique for Regression with Gaussian Noise. In addition, we use pandas for data handling, and seaborn to visualize our results. End of explanation """ ## load data housing = pandas.read_csv( ## http://jse.amstat.org/v19n3/decock.pdf 'https://raw.githubusercontent.com/nickkunz/smogn/master/data/housing.csv' ) """ Explanation: Data After, we load our data. In this example, we use the Ames Housing Dataset training split retreived from Kaggle, originally complied by Dean De Cock. In this case, we name our training set housing End of explanation """ ## conduct smogn housing_smogn = smogn.smoter( data = housing, ## pandas dataframe y = 'SalePrice' ## string ('header name') ) """ Explanation: Synthetic Minority Over-Sampling Technique for Regression with Gaussian Noise Here we cover the focus of this example. We call the smoter function from this package (smogn.smoter) and satisfy the minimum required arguments: data and y. The data argument takes a Pandas DataFrame, which contains the training set split. In this example, we input the previously loaded housing training set with follow input: data = housing The y argument takes a string, which specifies a continuous reponse variable by header name. In this example, we input 'SalePrice' in the interest of predicting the sale price of homes in Ames, Iowa with the following input: y = 'SalePrice' End of explanation """ ## dimensions - original data housing.shape ## dimensions - modified data housing_smogn.shape """ Explanation: Note: In this example, the regions of interest within the response variable y are automatically determined by the box plot extremes. The extreme values are considered rare "minorty" values are over-sampled. The values closer the median are considered "majority" values and are under-sampled. If there are no box plot extremes contained in the reponse variable y, the argument rel_method = manual must be specified, and an input matrix must be placed into the argument rel_ctrl_pts_rg indicating the regions of rarity in y. More information regarding the matrix input to the rel_ctrl_pts_rg argument and manual over-sampling can be found within the function's doc string, as well as in Example 3: Advanced. It is also important to mention that by default, smogn.smoter will first automatically remove columns containing missing values and then remove rows, as it cannot input data containing missing values. This feature can be changed with the boolean arguments drop_na_col = False and drop_na_rows = False. Results After conducting Synthetic Minority Over-Sampling Technique for Regression with Gaussian Noise, we briefly examine the results. We can see that the number of observations (rows) in the original training set decreased from 1460 to 1244, while the number of features (columns) also decreased from 81 to 62. Recall that smogn.smoter automatically removes features containing missing values. In this case, 19 features contained missing values and were therefore omitted. The reduction in observations were a result of under-sampling. More detailed information in this regard can be found in the original paper cited in the References section. End of explanation """ ## box plot stats - original data smogn.box_plot_stats(housing['SalePrice'])['stats'] ## box plot stats - modified data smogn.box_plot_stats(housing_smogn['SalePrice'])['stats'] """ Explanation: Further examining the results, we can see that the distribution of the response variable has changed. By calling the box_plot_stats function from this package (smogn.box_plot_stats) we quickly verify. Notice that the modified training set's box plot five number summary has changed, where the distribution of the response variable has skewed right when compared to the original training set. End of explanation """ ## plot y distribution seaborn.kdeplot(housing['SalePrice'], label = "Original") seaborn.kdeplot(housing_smogn['SalePrice'], label = "Modified") """ Explanation: Plotting the results of both the original and modified training sets, the skewed right distribution of the response variable in the modified training set becomes more evident. In this example, SMOGN over-sampled observations whose 'SalePrice' was found to be extremely high according to the box plot (those considered "minority") and under-sampled observations that were closer to the median (those considered "majority"). This is the quickest implementation when the y values of interest in predicting may be unclear within a given dataset. End of explanation """
tata-antares/tagging_LHCb
Stefania_files/track-based-tagging-OS.ipynb
apache-2.0
import pandas import numpy from folding_group import FoldingGroupClassifier from rep.data import LabeledDataStorage from rep.report import ClassificationReport from rep.report.metrics import RocAuc from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_curve, roc_auc_score from utils import get_N_B_events, get_events_number, get_events_statistics """ Explanation: Import End of explanation """ import root_numpy data_nan = pandas.DataFrame(root_numpy.root2array('datasets/tracks.root', 'tracks')) data_nan.head() event_id_column = 'event_id' event_id = data_nan.run.apply(str) + '_' + data_nan.event.apply(str) data_nan['group_column'] = numpy.unique(event_id, return_inverse=True)[1] data_nan[event_id_column] = event_id get_events_statistics(data_nan) get_N_B_events() """ Explanation: Reading initial data End of explanation """ data = data_nan.dropna() len(data_nan), len(data), get_events_statistics(data) """ Explanation: Remove rows with NAN from data End of explanation """ # add different between max pt in event and pt for each track def add_diff_pt(data): max_pt = group_max(data[event_id_column].values.astype(str), data.partPt.values) data.loc[:, 'diff_pt'] = max_pt - data['partPt'].values # max is computing max over tracks in the same event for saome data def group_max(groups, data): # computing unique integer id for each group assert len(groups) == len(data) _, event_id = numpy.unique(groups, return_inverse=True) max_over_event = numpy.zeros(max(event_id) + 1) - numpy.inf numpy.maximum.at(max_over_event, event_id, data) return max_over_event[event_id] # add diff pt add_diff_pt(data) # add cos(diff_phi) data.loc[:, 'cos_diff_phi'] = numpy.cos(data.diff_phi.values) """ Explanation: Add diff_pt and cos(diff_phi) End of explanation """ from itertools import combinations PIDs = {'k': data.PIDNNk.values, 'e': data.PIDNNe.values, 'mu': data.PIDNNm.values, } for (pid_name1, pid_values1), (pid_name2, pid_values2) in combinations(PIDs.items(), 2): data.loc[:, 'max_PID_{}_{}'.format(pid_name1, pid_name2)] = numpy.maximum(pid_values1, pid_values2) data.loc[:, 'sum_PID_{}_{}'.format(pid_name1, pid_name2)] = pid_values1 + pid_values2 """ Explanation: Add max, sum among PIDs End of explanation """ data.loc[:, 'label'] = (data.signB.values * data.signTrack.values > 0) * 1 ','.join(data.columns) """ Explanation: define label = signB * signTrack if > 0 (same sign) - label 1 if < 0 (different sign) - label 0 End of explanation """ initial_cut = '(ghostProb < 0.4)' data = data.query(initial_cut) os_selection = (data.IPs.values > 3) * ((abs(data.diff_eta.values) > 0.6) | (abs(data.diff_phi.values) > 0.825)) data = data[os_selection] get_events_statistics(data) """ Explanation: Apply ghost prob cut End of explanation """ threshold_kaon = 0. threshold_muon = 0. threshold_electron = 0. threshold_pion = 0.5 threshold_proton = 0.5 cut_pid = " ((PIDNNk > {trk}) | (PIDNNm > {trm}) | (PIDNNe > {tre})) & (PIDNNpi < {trpi}) & (PIDNNp < {trp}) " cut_pid = cut_pid.format(trk=threshold_kaon, trm=threshold_muon, tre=threshold_electron, trpi=threshold_pion, trp=threshold_proton) data = data.query(cut_pid) get_events_statistics(data) """ Explanation: Leave not muons, kaons, electrons; Filter pions, protons End of explanation """ N_B_passed = float(get_events_number(data)) tagging_efficiency = N_B_passed / get_N_B_events() tagging_efficiency_delta = sqrt(N_B_passed) / get_N_B_events() tagging_efficiency, tagging_efficiency_delta hist(data.diff_pt.values, bins=100) pass """ Explanation: Calculating tagging efficiency ($\epsilon_{tag}$) $$N (\text{passed selection}) = \sum_{\text{passed selection}} sw_i$$ $$N (\text{all events}) = \sum_{\text{all events}} sw_i,$$ where $sw_i$ - sPLot weight (sWeight for signal) $$\epsilon_{tag} = \frac{N (\text{passed selection})} {N (\text{all events})}$$ $$\Delta\epsilon_{tag} = \frac{\sqrt{N (\text{passed selection})}} {N (\text{all events})}$$ End of explanation """ _, take_indices = numpy.unique(data[event_id_column], return_index=True) figure(figsize=[15, 5]) subplot(1, 2, 1) hist(data.Bmass.values[take_indices], bins=100) title('B mass hist') xlabel('mass') subplot(1, 2, 2) hist(data.N_sig_sw.values[take_indices], bins=100, normed=True) title('sWeights hist') xlabel('signal sWeights') plt.savefig('img/Bmass_OS.png' , format='png') """ Explanation: Choose most probable B-events End of explanation """ sweight_threshold = 1. data_sw_passed = data[data.N_sig_sw > sweight_threshold] data_sw_not_passed = data[data.N_sig_sw <= sweight_threshold] get_events_statistics(data_sw_passed) _, take_indices = numpy.unique(data_sw_passed[event_id_column], return_index=True) figure(figsize=[15, 5]) subplot(1, 2, 1) hist(data_sw_passed.Bmass.values[take_indices], bins=100) title('B mass hist for sWeight > 1 selection') xlabel('mass') subplot(1, 2, 2) hist(data_sw_passed.N_sig_sw.values[take_indices], bins=100, normed=True) title('sWeights hist for sWeight > 1 selection') xlabel('signal sWeights') plt.savefig('img/Bmass_selected_OS.png' , format='png') hist(data_sw_passed.diff_pt.values, bins=100) pass """ Explanation: Define B-like events for training Events with low sWeight still will be used only to test quality. End of explanation """ features = list(set(data.columns) - {'index', 'run', 'event', 'i', 'signB', 'signTrack', 'N_sig_sw', 'Bmass', 'mult', 'PIDNNp', 'PIDNNpi', 'label', 'thetaMin', 'Dist_phi', event_id_column, 'mu_cut', 'e_cut', 'K_cut', 'ID', 'diff_phi', 'group_column'}) features """ Explanation: Main idea: find tracks, which can help reconstruct the sign of B if you know track sign. label = signB * signTrack * the highest output means that this is same sign B as track * the lowest output means that this is opposite sign B than track Define features End of explanation """ figure(figsize=[15, 16]) bins = 60 step = 3 for i, (feature1, feature2) in enumerate(combinations(['PIDNNk', 'PIDNNm', 'PIDNNe', 'PIDNNp', 'PIDNNpi'], 2)): subplot(4, 3, i + 1) Z, (x, y) = numpy.histogramdd(data_sw_passed[[feature1, feature2]].values, bins=bins, range=([0, 1], [0, 1])) pcolor(numpy.log(Z).T, vmin=0) xlabel(feature1) ylabel(feature2) xticks(numpy.arange(bins, step), x[::step]), yticks(numpy.arange(bins, step), y[::step]) plt.savefig('img/PID_selected_OS.png' , format='png') """ Explanation: PID pairs scatters End of explanation """ hist(data_sw_passed.diff_pt.values, bins=60, normed=True) pass """ Explanation: pt End of explanation """ _, n_tracks = numpy.unique(data_sw_passed[event_id_column], return_counts=True) hist(n_tracks, bins=max(n_tracks), range=(1, max(n_tracks))) title('Number of tracks') plt.savefig('img/tracks_number_OS.png' , format='png') """ Explanation: count of tracks End of explanation """ figure(figsize=[15, 4]) for i, column in enumerate(['PIDNNm', 'PIDNNe', 'PIDNNk']): subplot(1, 3, i + 1) hist(data_sw_passed[column].values, bins=60, range=(0, 1), label=column) legend() """ Explanation: PIDs histograms End of explanation """ from hep_ml.decisiontrain import DecisionTrainClassifier from hep_ml.losses import LogLossFunction from rep.estimators import SklearnClassifier data_sw_passed_lds = LabeledDataStorage(data_sw_passed, data_sw_passed.label, data_sw_passed.N_sig_sw.values) """ Explanation: Train to distinguish same sign vs opposite sign End of explanation """ tt_base = DecisionTrainClassifier(learning_rate=0.02, n_estimators=3000, depth=6, max_features=15, loss=LogLossFunction(regularization=100)) tt_folding = FoldingGroupClassifier(SklearnClassifier(tt_base), n_folds=2, random_state=11, train_features=features, group_feature='group_column', parallel_profile = 'threads-2') %time tt_folding.fit_lds(data_sw_passed_lds) pass import cPickle with open('models/dt_OS.pkl', 'w') as f: cPickle.dump(tt_folding, f) comparison_report = ClassificationReport({'tt': tt_folding}, data_sw_passed_lds) comparison_report.compute_metric(RocAuc()) comparison_report.roc() lc = comparison_report.learning_curve(RocAuc(), steps=1) lc for est in tt_folding.estimators: est.estimators = est.estimators[:1000] comparison_report.feature_importance() """ Explanation: DT End of explanation """ from utils import get_result_with_bootstrap_for_given_part models = [] models.append(get_result_with_bootstrap_for_given_part(tagging_efficiency, tagging_efficiency_delta, tt_folding, [data_sw_passed, data_sw_not_passed], 'tt-iso', logistic=False)) models.append(get_result_with_bootstrap_for_given_part(tagging_efficiency, tagging_efficiency_delta, tt_folding, [data_sw_passed, data_sw_not_passed], 'tt-log', logistic=True)) """ Explanation: Calibration End of explanation """ pandas.set_option('display.precision', 8) result = pandas.concat(models) result.index = result.name result.drop('name', axis=1) """ Explanation: Comparison table of different models End of explanation """ from utils import prepare_B_data_for_given_part Bdata_prepared = prepare_B_data_for_given_part(tt_folding, [data_sw_passed, data_sw_not_passed], logistic=True) Bdata_prepared.to_csv('models/Bdata_tracks_OS.csv', header=True, index=False) """ Explanation: Implementing best tracking End of explanation """
sarvex/PythonMachineLearning
Chapter 2/Support Vector Machines.ipynb
isc
from sklearn.datasets import load_digits from sklearn.cross_validation import train_test_split digits = load_digits() X_train, X_test, y_train, y_test = train_test_split(digits.data / 16., digits.target % 2, random_state=2) from sklearn.svm import LinearSVC, SVC linear_svc = LinearSVC(loss="hinge").fit(X_train, y_train) svc = SVC(kernel="linear").fit(X_train, y_train) np.mean(linear_svc.predict(X_test) == svc.predict(X_test)) """ Explanation: Support Vector Machines End of explanation """ from sklearn.metrics.pairwise import rbf_kernel line = np.linspace(-3, 3, 100)[:, np.newaxis] kernel_value = rbf_kernel([[0]], line, gamma=1) plt.plot(line, kernel_value.T) from figures import plot_svm_interactive plot_svm_interactive() svc = SVC().fit(X_train, y_train) svc.score(X_test, y_test) Cs = [0.001, 0.01, 0.1, 1, 10, 100] gammas = [0.001, 0.01, 0.1, 1, 10, 100] from sklearn.grid_search import GridSearchCV param_grid = {'C': Cs, 'gamma' : gammas} grid_search = GridSearchCV(SVC(), param_grid, cv=5) grid_search.fit(X_train, y_train) grid_search.score(X_test, y_test) # We extract just the scores scores = [x[1] for x in grid_search.grid_scores_] scores = np.array(scores).reshape(6, 6) plt.matshow(scores) plt.xlabel('gamma') plt.ylabel('C') plt.colorbar() plt.xticks(np.arange(6), param_grid['gamma']) plt.yticks(np.arange(6), param_grid['C']); """ Explanation: Kernel SVMs Predictions in a kernel-SVM are made using the formular $$ \hat{y} = \alpha_0 + \alpha_1 y_1 k(\mathbf{x^{(1)}}, \mathbf{x}) + ... + \alpha_n y_n k(\mathbf{x^{(n)}}, \mathbf{x})> 0 $$ $$ 0 \leq \alpha_i \leq C $$ Radial basis function (Gaussian) kernel: $$k(\mathbf{x}, \mathbf{x'}) = \exp(-\gamma ||\mathbf{x} - \mathbf{x'}||^2)$$ End of explanation """
mspieg/principals-appmath
PCA_EOF_example.ipynb
cc0-1.0
%matplotlib inline import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt import csv """ Explanation: <table> <tr align=left><td><img align=left src="./images/CC-BY.png"> <td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Marc Spiegelman</td> </table> End of explanation """ # read the data from the csv file data = np.genfromtxt('m80.csv', delimiter='') data_mean = np.mean(data,0) # and plot out a few profiles and the mean depth. plt.figure() rows = [ 9,59,99] labels = [ 'slow','medium','fast'] for i,row in enumerate(rows): plt.plot(data[row,:],label=labels[i]) plt.hold(True) plt.plot(data_mean,'k--',label='mean') plt.xlabel('Distance across axis (km)') plt.ylabel('Relative Elevation (m)') plt.legend(loc='best') plt.title('Example cross-axis topography of mid-ocean ridges') plt.show() """ Explanation: Principal Component/EOF analysis GOAL: Demonstrate the use of the SVD to calculate principal components or "Empirical Orthogonal Functions" in a geophysical data set. This example is modified from a paper by Chris Small (LDEO) Small, C., 1994. A global analysis of mid-ocean ridge axial topography. Geophys J Int 116, 64–84. doi:10.1111/j.1365-246X.1994.tb02128.x The Data Here we will consider a set of topography profiles taken across the global mid-ocean ridge system where the Earth's tectonic plates are spreading apart. <table> <tr align=center><td><img align=center src="./images/World_OceanFloor_topo_green_brown_1440x720.jpg"><td> </table> The data consists of 156 profiles from a range of spreading rates. Each profile contains 80 samples so is in effect a vector in $R^{80}$ End of explanation """ plt.figure() X = data - data_mean plt.imshow(X) plt.xlabel('Distance across axis (Km)') plt.ylabel('Relative Spreading Rate') plt.colorbar() plt.show() """ Explanation: EOF analysis While each profile lives in an 80 dimensional space, we would like to see if we can classify the variability in fewer components. To begin we form a de-meaned data matrix $X$ where each row is a profile. End of explanation """ # now calculate the SVD of the de-meaned data matrix U,S,Vt = la.svd(X,full_matrices=False) """ Explanation: Applying the SVD We now use the SVD to factor the data matrix as $X = U\Sigma V^T$ End of explanation """ # plot the singular values plt.figure() plt.semilogy(S,'bo') plt.grid() plt.title('Singular Values') plt.show() # and cumulative percent of variance g = np.cumsum(S*S)/np.sum(S*S) plt.figure() plt.plot(g,'bx-') plt.title('% cumulative percent variance explained') plt.grid() plt.show() """ Explanation: And begin by looking at the spectrum of singular values $\Sigma$. Defining the variance as $\Sigma^2$ then we can also calculate the cumulative contribution to the total variance as $$ g_k = \frac{\sum_{i=0}^k \sigma_i^2}{\sum_{i=0}^n \sigma_i^2} $$ Plotting both $\Sigma$ and $g$ shows that $\sim$ 80% of the total variance can be explained by the first 4-5 Components End of explanation """ plt.figure() num_EOFs=3 for row in range(num_EOFs): plt.plot(Vt[row,:],label='EOF{}'.format(row+1)) plt.grid() plt.xlabel('Distance (km)') plt.title('First {} EOFs '.format(num_EOFs)) plt.legend(loc='best') plt.show() """ Explanation: Plotting the first 4 Singular Vectors in $V$, shows them to reflect some commonly occuring patterns in the data End of explanation """ # recontruct the data using the first 5 EOF's k=5 Ck = np.dot(U[:,:k],np.diag(S[:k])) Vtk = Vt[:k,:] data_k = data_mean + np.dot(Ck,Vtk) plt.figure() plt.imshow(data_k) plt.colorbar() plt.title('reconstructed data') plt.show() """ Explanation: For example, the first EOF pattern is primarily a symmetric pattern with an axial high surrounded by two off axis troughs (or an axial low with two flanking highs, the EOF's are just unit vector bases for the row-space and can be added with any positive or negative coefficient). The Second EOF is broader and all of one sign while the third EOF encodes assymetry. Reconstruction Using the SVD we can also decompose each profile into a weighted linear combination of EOF's i.e. $$ X = U\Sigma V^T = C V^T $$ where $C = U\Sigma$ is a matrix of coefficients that describes the how each data row is decomposed into the relevant basis vectors. We can then produce a k-rank truncated representation of the data by $$ X_k = C_k V_k^T $$ where $C_k$ is the first $k$ columns of $C$ and $V_k$ is the first $k$ EOF's. Here we show the original data and the reconstructed data using the first 5 EOF's End of explanation """ # show the original 3 profiles and their recontructed values using the first k EOF's for i,row in enumerate(rows): plt.figure() plt.plot(data_k[row,:],label='k={}'.format(k)) plt.hold(True) plt.plot(data[row,:],label='original data') Cstring = [ '{:3.0f}, '.format(Ck[row,i]) for i in range(k) ] plt.title('Reconstruction profile {}:\n C_{}='.format(row,k)+''.join(Cstring)) plt.legend(loc='best') plt.show() """ Explanation: And we can consider a few reconstructed profiles compared with the original data End of explanation """ # plot the data in the plane defined by the first two principal components plt.figure() plt.scatter(Ck[:,0],Ck[:,1]) plt.xlabel('$V_1$') plt.ylabel('$V_2$') plt.grid() plt.title('Projection onto the first two principal components') plt.show() # Or consider the degree of assymetry (EOF 3) as a function of spreading rate plt.figure() plt.plot(Ck[:,2],'bo') plt.xlabel('Spreading rate') plt.ylabel('$C_3$') plt.grid() plt.title('Degree of assymetry') plt.show() """ Explanation: projection of data onto a subspace We can also use the Principal Components to look at the projection of the data onto a lower dimensional space as the coefficients $C$, are simply the coordinates of our data along each principal component. For example we can view the data in the 2-Dimensional space defined by the first 2 EOF's by simply plotting C_1 against C_2. End of explanation """
kdestasio/online_brain_intensive
nipype_tutorial/notebooks/basic_workflow.ipynb
gpl-2.0
%pylab inline import nibabel as nb # Let's create a short helper function to plot 3D NIfTI images def plot_slice(fname): # Load the image img = nb.load(fname) data = img.get_data() # Cut in the middle of the brain cut = int(data.shape[-1]/2) + 10 # Plot the data imshow(np.rot90(data[..., cut]), cmap="gray") gca().set_axis_off() """ Explanation: Workflows Although it would be possible to write analysis scripts using just Nipype Interfaces, and this may provide some advantages over directly making command-line calls, the main benefits of Nipype will come by creating workflows. A workflow controls the setup and the execution of individual interfaces. Let's assume you want to run multiple interfaces in a specific order, where some have to wait for others to finish while others can be executed in parallel. The nice thing about a nipype workflow is, that the workflow will take care of input and output of each interface and arrange the execution of each interface in the most efficient way. A workflow therefore consists of multiple Nodes, each representing a specific Interface and directed connection between those nodes. Those connections specify which output of which node should be used as an input for another node. To better understand why this is so great, let's look at an example. Preparation Before we can start, let's first load some helper functions: End of explanation """ %%bash ANAT_NAME=sub-02_ses-test_T1w ANAT=/data/ds000114/sub-02/ses-test/anat/${ANAT_NAME} bet ${ANAT} /output/${ANAT_NAME}_brain -m -f 0.3 fslmaths ${ANAT} -s 2 /output/${ANAT_NAME}_smooth fslmaths /output/${ANAT_NAME}_smooth -mas /output/${ANAT_NAME}_brain_mask /output/${ANAT_NAME}_smooth_mask """ Explanation: Example 1 - Command-line execution Let's take a look at a small preprocessing analysis where we would like to perform the following steps of processing: - Skullstrip an image to obtain a mask - Smooth the original image - Mask the smoothed image This could all very well be done with the following shell script: End of explanation """ f = plt.figure(figsize=(12, 4)) for i, img in enumerate(["T1w", "T1w_smooth", "T1w_brain_mask", "T1w_smooth_mask"]): f.add_subplot(1, 4, i + 1) if i == 0: plot_slice("/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_%s.nii.gz" % img) else: plot_slice("/output/sub-02_ses-test_%s.nii.gz" % img) plt.title(img) """ Explanation: This is simple and straightforward. We can see that this does exactly what we wanted by plotting the four steps of processing. End of explanation """ from nipype.interfaces import fsl # Skullstrip process skullstrip = fsl.BET( in_file="/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz", out_file="/output/sub-02_T1w_brain.nii.gz", mask=True) skullstrip.run() # Smoothing process smooth = fsl.IsotropicSmooth( in_file="/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz", out_file="/output/sub-02_T1w_smooth.nii.gz", fwhm=4) smooth.run() # Masking process mask = fsl.ApplyMask( in_file="/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz", out_file="/output/sub-02_T1w_smooth_mask.nii.gz", mask_file="/output/sub-02_T1w_brain_mask.nii.gz") mask.run() f = plt.figure(figsize=(12, 4)) for i, img in enumerate(["T1w", "T1w_smooth", "T1w_brain_mask", "T1w_smooth_mask"]): f.add_subplot(1, 4, i + 1) if i == 0: plot_slice("/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_%s.nii.gz" % img) else: plot_slice("/output/sub-02_%s.nii.gz" % img) plt.title(img) """ Explanation: Example 2 - Interface execution Now let's see what this would look like if we used Nipype, but only the Interfaces functionality. It's simple enough to write a basic procedural script, this time in Python, to do the same thing as above: End of explanation """ from nipype.interfaces import fsl # Skullstrip process skullstrip = fsl.BET( in_file="/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz", mask=True) bet_result = skullstrip.run() # skullstrip object # Smooth process smooth = fsl.IsotropicSmooth( in_file="/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz", fwhm=4) smooth_result = smooth.run() # smooth object # Mask process mask = fsl.ApplyMask(in_file=smooth_result.outputs.out_file, mask_file=bet_result.outputs.mask_file) mask_result = mask.run() f = plt.figure(figsize=(12, 4)) for i, img in enumerate([skullstrip.inputs.in_file, smooth_result.outputs.out_file, bet_result.outputs.mask_file, mask_result.outputs.out_file]): f.add_subplot(1, 4, i + 1) plot_slice(img) plt.title(img.split('/')[-1].split('.')[0].split('test_')[-1]) """ Explanation: This is more verbose, although it does have its advantages. There's the automated input validation we saw previously, some of the options are named more meaningfully, and you don't need to remember, for example, that fslmaths' smoothing kernel is set in sigma instead of FWHM -- Nipype does that conversion behind the scenes. Can't we optimize that a bit? As we can see above, the inputs for the mask routine in_file and mask_file are actually the output of skullstrip and smooth. We therefore somehow want to connect them. This can be accomplisehd by saving the executed routines under a given object and than using the output of those objects as input for other routines. End of explanation """ # Import Node and Workflow object and FSL interface from nipype import Node, Workflow from nipype.interfaces import fsl # For reasons that will later become clear, it's important to # pass filenames to Nodes as absolute paths from os.path import abspath in_file = abspath("/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz") # Skullstrip process skullstrip = Node(fsl.BET(in_file=in_file, mask=True), name="skullstrip") # Smooth process smooth = Node(fsl.IsotropicSmooth(in_file=in_file, fwhm=4), name="smooth") # Mask process mask = Node(fsl.ApplyMask(), name="mask") """ Explanation: Here we didn't need to name the intermediate files; Nipype did that behind the scenes, and then we passed the result object (which knows those names) onto the next step in the processing stream. This is somewhat more concise than the example above, but it's still a procedural script. And the dependency relationship between the stages of processing is not particularly obvious. To address these issues, and to provide solutions to problems we might not know we have yet, Nipype offers Workflows. Example 3 - Workflow execution What we've implicitly done above is to encode our processing stream as a directed acyclic graphs: each stage of processing is a node in this graph, and some nodes are unidirectionally dependent on others. In this case there is one input file and several output files, but there are no cycles -- there's a clear line of directionality to the processing. What the Node and Workflow classes do is make these relationships more explicit. The basic architecture is that the Node provides a light wrapper around an Interface. It exposes the inputs and outputs of the Interface as its own, but it adds some additional functionality that allows you to connect Nodes into a Workflow. Let's rewrite the above script with these tools: End of explanation """ # Initiation of a workflow wf = Workflow(name="smoothflow", base_dir="/output/working_dir") """ Explanation: This looks mostly similar to what we did above, but we've left out the two crucial inputs to the ApplyMask step. We'll set those up by defining a Workflow object and then making connections among the Nodes. End of explanation """ # First the "simple", but more restricted method wf.connect(skullstrip, "mask_file", mask, "mask_file") # Now the more complicated method wf.connect([(smooth, mask, [("out_file", "in_file")])]) """ Explanation: The Workflow object has a method called connect that is going to do most of the work here. This routine also checks if inputs and outputs are actually provided by the nodes that are being connected. There are two different ways to call connect: connect(source, "source_output", dest, "dest_input") connect([(source, dest, [("source_output1", "dest_input1"), ("source_output2", "dest_input2") ]) ]) With the first approach you can establish one connection at a time. With the second you can establish multiple connects between two nodes at once. In either case, you're providing it with four pieces of information to define the connection: The source node object The name of the output field from the source node The destination node object The name of the input field from the destination node We'll illustrate each method in the following cell: End of explanation """ wf.write_graph("workflow_graph.dot") from IPython.display import Image Image(filename="/output/working_dir/smoothflow/workflow_graph.dot.png") """ Explanation: Now the workflow is complete! Above, we mentioned that the workflow can be thought of as a directed acyclic graph. In fact, that's literally how it's represented behind the scenes, and we can use that to explore the workflow visually: End of explanation """ wf.write_graph(graph2use='flat') from IPython.display import Image Image(filename="/output/working_dir/smoothflow/graph_detailed.dot.png") """ Explanation: This representation makes the dependency structure of the workflow obvious. (By the way, the names of the nodes in this graph are the names we gave our Node objects above, so pick something meaningful for those!) Certain graph types also allow you to further inspect the individual connections between the nodes. For example: End of explanation """ # Specify the base directory for the working directory wf.base_dir = "/output/working_dir" # Execute the workflow wf.run() """ Explanation: Here you see very clearly, that the output mask_file of the skullstrip node is used as the input mask_file of the mask node. For more information on graph visualization, see the Graph Visualization section. But let's come back to our example. At this point, all we've done is define the workflow. We haven't executed any code yet. Much like Interface objects, the Workflow object has a run method that we can call so that it executes. Let's do that and then examine the results. End of explanation """ f = plt.figure(figsize=(12, 4)) for i, img in enumerate(["/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz", "/output/working_dir/smoothflow/smooth/sub-02_ses-test_T1w_smooth.nii.gz", "/output/working_dir/smoothflow/skullstrip/sub-02_ses-test_T1w_brain_mask.nii.gz", "/output/working_dir/smoothflow/mask/sub-02_ses-test_T1w_smooth_masked.nii.gz"]): f.add_subplot(1, 4, i + 1) plot_slice(img) """ Explanation: The specification of base_dir is very important (and is why we needed to use absolute paths above), because otherwise all the outputs would be saved somewhere in the temporary files. Unlike interfaces, which by default spit out results to the local directry, the Workflow engine executes things off in its own directory hierarchy. Let's take a look at the resulting images to convince ourselves we've done the same thing as before: End of explanation """ !tree /output/working_dir/smoothflow/ -I '*js|*json|*html|*pklz|_report' """ Explanation: Perfet! Let's also have a closer look at the working directory: End of explanation """ from nipype.workflows.fmri.fsl import create_susan_smooth """ Explanation: As you can see, the name of the working directory is the name we gave the workflow base_dir. And the name of the folder within is the name of the workflow object smoothflow. Each node of the workflow has its' own subfolder in the smoothflow folder. And each of those subfolders contains the output of the node as well as some additional files. A workflow inside a workflow When you start writing full-fledged analysis workflows, things can get quite complicated. Some aspects of neuroimaging analysis can be thought of as a coherent step at a level more abstract than the execution of a single command line binary. For instance, in the standard FEAT script in FSL, several calls are made in the process of using susan to perform nonlinear smoothing on an image. In Nipype, you can write nested workflows, where a sub-workflow can take the place of a Node in a given script. Let's use the prepackaged susan workflow that ships with Nipype to replace our Gaussian filtering node and demonstrate how this works. End of explanation """ susan = create_susan_smooth(separate_masks=False) """ Explanation: Calling this function will return a pre-written Workflow object: End of explanation """ susan.write_graph("susan_workflow.dot") from IPython.display import Image Image(filename="susan_workflow.dot.png") """ Explanation: Let's display the graph to see what happens here. End of explanation """ print("Inputs:\n", susan.inputs.inputnode) print("Outputs:\n", susan.outputs.outputnode) """ Explanation: We see that the workflow has an inputnode and an outputnode. While not strictly necessary, this is standard practice for workflows (especially those that are intended to be used as nested workflows in the context of a longer analysis graph) and makes it more clear how to connect inputs and outputs from this workflow. Let's take a look at what those inputs and outputs are. Like Nodes, Workflows have inputs and outputs attributes that take a second sub-attribute corresponding to the specific node we want to make connections to. End of explanation """ susan.inputs """ Explanation: Note that inputnode and outputnode are just conventions, and the Workflow object exposes connections to all of its component nodes: End of explanation """ from nipype import Function extract_func = lambda list_out: list_out[0] list_extract = Node(Function(input_names=["list_out"], output_names=["out_file"], function=extract_func), name="list_extract") """ Explanation: Let's see how we would write a new workflow that uses this nested smoothing step. The susan workflow actually expects to receive and output a list of files (it's intended to be executed on each of several runs of fMRI data). We'll cover exactly how that works in later tutorials, but for the moment we need to add an additional Function node to deal with the fact that susan is outputting a list. We can use a simple lambda function to do this: End of explanation """ # Initiate workflow with name and base directory wf2 = Workflow(name="susanflow", base_dir="/output/working_dir") # Create new skullstrip and mask nodes skullstrip2 = Node(fsl.BET(in_file=in_file, mask=True), name="skullstrip") mask2 = Node(fsl.ApplyMask(), name="mask") # Connect the nodes to each other and to the susan workflow wf2.connect([(skullstrip2, mask2, [("mask_file", "mask_file")]), (skullstrip2, susan, [("mask_file", "inputnode.mask_file")]), (susan, list_extract, [("outputnode.smoothed_files", "list_out")]), (list_extract, mask2, [("out_file", "in_file")]) ]) # Specify the remaining input variables for the susan workflow susan.inputs.inputnode.in_files = abspath( "/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz") susan.inputs.inputnode.fwhm = 4 """ Explanation: Now let's create a new workflow susanflow that contains the susan workflow as a sub-node. To be sure, let's also recreate the skullstrip and the mask node from the examples above. End of explanation """ wf2.write_graph(dotfilename='/output/working_dir/full_susanflow.dot', graph2use='colored') from IPython.display import Image Image(filename="/output/working_dir/full_susanflow.dot.png") """ Explanation: First, let's see what this new processing graph looks like. End of explanation """ wf2.write_graph(dotfilename='/output/working_dir/full_susanflow_toplevel.dot', graph2use='orig') from IPython.display import Image Image(filename="/output/working_dir/full_susanflow_toplevel.dot.png") """ Explanation: We can see how there is a nested smoothing workflow (blue) in the place of our previous smooth node. This provides a very detailed view, but what if you just wanted to give a higher-level summary of the processing steps? After all, that is the purpose of encapsulating smaller streams in a nested workflow. That, fortunately, is an option when writing out the graph: End of explanation """ wf2.run() """ Explanation: That's much more managable. Now let's execute the workflow End of explanation """ f = plt.figure(figsize=(12, 4)) for i, e in enumerate([["/data/ds000114/sub-02/ses-test/anat/sub-02_ses-test_T1w.nii.gz", 'input'], ["/output/working_dir//susanflow/mask/sub-02_ses-test_T1w_smooth_masked.nii.gz", 'output']]): f.add_subplot(1, 2, i + 1) plot_slice(e[0]) plt.title(e[1]) """ Explanation: As a final step, let's look at the input and the output. It's exactly what we wanted. End of explanation """ %time wf2.run() """ Explanation: So, why are workflows so great? So far, we've seen that you can build up rather complex analysis workflows. But at the moment, it's not been made clear why this is worth the extra trouble from writing a simple procedural script. To demonstrate the first added benefit of the Nipype, let's just rerun the susanflow workflow from above and measure the execution times. End of explanation """ wf.inputs.smooth.fwhm = 1 wf.run() """ Explanation: That happened quickly! Workflows (actually this is handled by the Node code) are smart, and know if their inputs have changed from the last time they are run. If they have not, they don't recompute; they just turn around and pass out the resulting files from the previous run. This is done on a node-by-node basis, also. Let's go back to the first workflow example. What happened if we just tweak one thing: End of explanation """
cwhite1026/Py2PAC
examples/Creating_AngularCatalogs_and_ImageMasks.ipynb
bsd-3-clause
import AngularCatalog_class as ac import ImageMask_class as imclass from astropy.io import fits from astropy.io import ascii import numpy as np import numpy.random as rand import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10, 6) """ Explanation: Creating AngularCatalogs and ImageMasks Py2PAC has several ways to create AngularCatalogs and ImageMasks. We'll start with ImageMasks since we need them in order to do anything meaningful with an AngularCatalog. First, import the things that we'll need. End of explanation """ mask_from_ranges = imclass.ImageMask.from_ranges([0, 1], [0, 0.5]) """ Explanation: Ways to create an ImageMask There are three main ways to create an ImageMask in Py2PAC, all classmethods of ImageMask: from_ranges: Creates a rectangular image mask over a range in RA and Dec with equal completeness in all parts of the image. Bug to be fixed: doesn't allow for negative RAs from_array: This doesn't work the way it should at the moment because WCS is wonky. This creates a rectangular image mask with the completeness in each cell defined by the value of an input array. I show here how it currently malfunctions. Eventually, this should be fixed. from_FITS_weight_file: Reads in a weight map in FITS format and converts it to completeness=1 at points with weight above the 5th percentile and completeness=0 below. From ranges: single completeness over a rectangular area We'll make the simplest mask first. The arguments to from_ranges are two arrays, the RA range first, then the Dec range, both in degrees. End of explanation """ #Generate the randoms ra, dec, completeness = mask_from_ranges.generate_random_sample(1e4) #Plot fig=plt.figure() ax=fig.add_subplot(111) ax.set_xlabel("RA (deg)") ax.set_ylabel("Dec (deg)") ax.scatter(ra, dec) """ Explanation: To see what the mask looks like, we generate some random points and plot them. End of explanation """ #Make the mask array mask_array = np.identity(4) print mask_array #Make the ImageMask mask_from_array = imclass.ImageMask.from_array(mask_array, [0,1], [0,1]) %%capture ## ^ Use to suppress lengthy output #Generate randoms ra, dec, completeness = mask_from_array.generate_random_sample(1e4) #Plot the randoms fig=plt.figure() ax=fig.add_subplot(111) ax.set_xlabel("RA (deg)") ax.set_ylabel("Dec (deg)") ax.scatter(ra, dec) """ Explanation: Simple enough. Note that if you manually change the completenesses in the ImageMask._mask, it will behave like from_array, which is to say "not the way you expect" (this is on the list of things to be fixed). See the next section. From array: Make a mask from a pre-existing array WARNING: This method does not work the way it should. I have included it solely to show how the function is broken. The concept for this method is to make it so that an arbitrary array with elements that range from 0 to 1 can be used as an image mask. However, at the present time, dividing the area into even bins doesn't work for reasons unbeknownst to me. We'll make a mask from the identity matrix to illustrate the strangeness, but then show how uneven completeness works. End of explanation """ #Make the new array mask mask_array2 = np.identity(4) mask_array2[0,0] = 0.2 mask_array2[0, 3] = 0.2 print mask_array2 #Make the new mask mask_from_array2 = imclass.ImageMask.from_array(mask_array2, [0,1], [0,1]) %%capture ## ^ Use to suppress lengthy output #Generate randoms ra2, dec2, completeness = mask_from_array2.generate_random_sample(1e4) #Plot the randoms fig=plt.figure() ax=fig.add_subplot(111) ax.set_xlabel("RA (deg)") ax.set_ylabel("Dec (deg)") ax.scatter(ra2, dec2) """ Explanation: The main thing to note here is that the binning isn't even. The mask also has a different orientation from the orientation of the array. The origin is in the lower left, at the minimum RA and Dec. To see this, we'll use a slightly different array to mask. End of explanation """ #Make the mask weight_file = 'hlsp_candels_hst_wfc3_gs-tot-sect33_f160w_v1.0_wht.fits' mask_from_fits = imclass.ImageMask.from_FITS_weight_file(weight_file) %%capture ## ^ Use to suppress lengthy output #Generate randoms ra, dec, completeness = mask_from_fits.generate_random_sample(1e5) #Plot the randoms fig=plt.figure() fig.set_size_inches(7,7) ax=fig.add_subplot(111) ax.set_xlabel("RA (deg)") ax.set_ylabel("Dec (deg)") ax.scatter(ra, dec) """ Explanation: This clearly shows that the origin is in the lower left and also illustrates how variable completeness would be implemented in this version of Py2PAC. Again, this should be fixed so the bins are square (or at least rectangular) in future versions. From FITS: Make a mask from a FITS file This function was written with the weight files from the CANDELS mosaics in mind. In principle, it should work with any FITS image with lower values denoting lower exposure times. The routine reads in the FITS file and finds the 5th percentile of the nonzero weight values from a random sample of 1e6 values on the image (to make computation time manageable). Then, a mask is created that has completeness 1 above the 5th percentile and 0 below. This example uses a CANDELS tile weight file. The file is too large to be included in the repository, so the file "hlsp_candels_hst_wfc3_gs-tot-sect33_f160w_v1.0_wht.fits" (found here) must be downloaded and placed in the examples folder. End of explanation """ #Make the RAs and Decs ras = rand.normal(loc=0.5, scale=0.2, size=int(1e3)) decs = rand.normal(loc=0, scale=0.2, size=int(1e3)) plt.scatter(ras, decs) """ Explanation: Ways to create an AngularCatalog An AngularCatalog can be created either with externally generated RAs and Decs or with randomly generated RAs and Decs. They can have an ImageMask of any kind. We'll start with pre-existing RAs and Decs (we'll make some up) and then move on to the random_catalog class method. AngularCatalogs from existing coordinates For the purposes of this exercise, we'll just create a random sample of "galaxies." For interest, we'll distribute them as a 2D Gaussian. End of explanation """ #Make the mask that we'll be using immask = imclass.ImageMask.from_ranges([0.1, .9], [-0.4, 0.4]) #Make the catalog cat = ac.AngularCatalog(ras, decs, image_mask=immask) #Generate some randoms to showthe mask area cat.generate_random_sample(number_to_make=2e4) #Plot both the randoms and all the data (not just what's within the mask) cat.scatterplot_points(sample="both", masked_data=False) cat.scatterplot_points(sample="both", masked_data=True) """ Explanation: Now we need to make this into an AngularCatalog with some image mask. The options are to pass an already existing ImageMask instance or to give the constructor the location of a weight file from which to construct the mask. Pre-existing ImageMask For this demonstration, we'll make a rectangular mask and pass it explicitly. End of explanation """ #Create an AngularCatalog with an ImageMask from a weight file weight_file = 'hlsp_candels_hst_wfc3_gs-tot-sect33_f160w_v1.0_wht.fits' data_file = "example_data.dat" data = ascii.read(data_file) #Only use the first 1000 points (it's random points, so it doesn't matter which 1000) to make #an AngularCatalog (so we can see the randoms too on the plot) cat_wt = ac.AngularCatalog(data['ra'][0:1000], data['dec'][0:1000], weight_file = weight_file) cat_wt.generate_random_sample(number_to_make=1e4) cat_wt.scatterplot_points(sample="both", masked_data=True) """ Explanation: The first plot shows all the data and the second shows just the data within the mask area (just to confirm that the mask is working). Creating an ImageMask from FITS at the same time you create the AngularCatalog You can also generate AngularCatalogs with ImageMask from FITS files with just the constructor. For this, we need coordinates that are in the right place, so we'll just use the CANDELS galaxies. End of explanation """ #Make the AngularCatalog with an existing image mask immask = imclass.ImageMask.from_ranges([0.1, .9], [-0.4, 0.4]) rand_cat_1 = ac.AngularCatalog.random_catalog(1e3, image_mask = immask) rand_cat_1.scatterplot_points(sample="data") #Make the AngularCatalog over a rectangular area rand_cat_1 = ac.AngularCatalog.random_catalog(1e3, ra_range=[0, 0.5], dec_range=[0, 0.5]) rand_cat_1.scatterplot_points(sample="data") """ Explanation: AngularCatalogs with randomly generated points For testing purposes, AngularCatalog has a class method called random_catalog. This method can be called with either ranges in RA and Dec or with an existing ImageMask. The code below shows an AngularCatalog made both ways. End of explanation """
georgetown-analytics/yelp-classification
data_munging/.ipynb_checkpoints/filter_user_reviews-checkpoint.ipynb
mit
biguser = [] for obj in users.find({'review_count':{'$gt':500}}): biguser.append(obj['user_id']) """ Explanation: The business ID field has already been filtered for only restaurants We want to filter the users collection for the following: 1. User must have at least 20 reviews 2. For users with 20 reviews, identify the reviews which are for businesses 3. For each user, keep only those reviews which are related to a business in the list of restaurant business IDs 4. Keep only users who have at least 500 reviews after finishing step 3 End of explanation """ userreview = {} for i in tqdm.tqdm(range(0,len(biguser[0:20]))): ulist = [] for obj in reviews.find({'user_id':biguser[i]}): del obj['_id'] ulist.append(obj) userreview[str(biguser[i])] = ulist with open('user_review_dictionary.json', 'w') as outfile: json.dump(userreview, outfile) """ Explanation: Create a new dictionary with the following structure and then export as a json object: {user id: [review, review, review], ..., user id: [review, review, review]} End of explanation """ biznames =[] for key in userreview.keys(): for review in userreview[key]: biznames.append(review['business_id']) """ Explanation: Get all the restaurant IDs within our user reviews End of explanation """ restreview = {} for i in tqdm.tqdm(range(0, len(biznames))): rlist = [] for obj in reviews.find({'business_id':biznames[i]}): rlist.append(obj) restreview[biznames[i]] = rlist for key in restreview.keys(): for review in restreview[key]: if '_id' in review: del review['_id'] with open('rest_review_dictionary.json', 'w') as outfile: json.dump(restreview, outfile) """ Explanation: For each of the businesses, find all of the reviews for that restaurant End of explanation """
ShubhamDebnath/Coursera-Machine-Learning
Course 5/Emojify v2.ipynb
mit
import numpy as np from emo_utils import * import emoji import matplotlib.pyplot as plt %matplotlib inline """ Explanation: Emojify! Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier. Have you ever wanted to make your text messages more expressive? Your emojifier app will help you do that. So rather than writing "Congratulations on the promotion! Lets get coffee and talk. Love you!" the emojifier can automatically turn this into "Congratulations on the promotion! 👍 Lets get coffee and talk. ☕️ Love you! ❤️" You will implement a model which inputs a sentence (such as "Let's go see the baseball game tonight!") and finds the most appropriate emoji to be used with this sentence (⚾️). In many emoji interfaces, you need to remember that ❤️ is the "heart" symbol rather than the "love" symbol. But using word vectors, you'll see that even if your training set explicitly relates only a few words to a particular emoji, your algorithm will be able to generalize and associate words in the test set to the same emoji even if those words don't even appear in the training set. This allows you to build an accurate classifier mapping from sentences to emojis, even using a small training set. In this exercise, you'll start with a baseline model (Emojifier-V1) using word embeddings, then build a more sophisticated model (Emojifier-V2) that further incorporates an LSTM. Lets get started! Run the following cell to load the package you are going to use. End of explanation """ X_train, Y_train = read_csv('data/train_emoji.csv') X_test, Y_test = read_csv('data/tesss.csv') maxLen = len(max(X_train, key=len).split()) """ Explanation: 1 - Baseline model: Emojifier-V1 1.1 - Dataset EMOJISET Let's start by building a simple baseline classifier. You have a tiny dataset (X, Y) where: - X contains 127 sentences (strings) - Y contains a integer label between 0 and 4 corresponding to an emoji for each sentence <img src="images/data_set.png" style="width:700px;height:300px;"> <caption><center> Figure 1: EMOJISET - a classification problem with 5 classes. A few examples of sentences are given here. </center></caption> Let's load the dataset using the code below. We split the dataset between training (127 examples) and testing (56 examples). End of explanation """ index = 1 print(X_train[index], label_to_emoji(Y_train[index])) """ Explanation: Run the following cell to print sentences from X_train and corresponding labels from Y_train. Change index to see different examples. Because of the font the iPython notebook uses, the heart emoji may be colored black rather than red. End of explanation """ Y_oh_train = convert_to_one_hot(Y_train, C = 5) Y_oh_test = convert_to_one_hot(Y_test, C = 5) """ Explanation: 1.2 - Overview of the Emojifier-V1 In this part, you are going to implement a baseline model called "Emojifier-v1". <center> <img src="images/image_1.png" style="width:900px;height:300px;"> <caption><center> Figure 2: Baseline model (Emojifier-V1).</center></caption> </center> The input of the model is a string corresponding to a sentence (e.g. "I love you). In the code, the output will be a probability vector of shape (1,5), that you then pass in an argmax layer to extract the index of the most likely emoji output. To get our labels into a format suitable for training a softmax classifier, lets convert $Y$ from its current shape current shape $(m, 1)$ into a "one-hot representation" $(m, 5)$, where each row is a one-hot vector giving the label of one example, You can do so using this next code snipper. Here, Y_oh stands for "Y-one-hot" in the variable names Y_oh_train and Y_oh_test: End of explanation """ index = 50 print(Y_train[index], "is converted into one hot", Y_oh_train[index]) """ Explanation: Let's see what convert_to_one_hot() did. Feel free to change index to print out different values. End of explanation """ word_to_index, index_to_word, word_to_vec_map = read_glove_vecs('data/glove.6B.50d.txt') """ Explanation: All the data is now ready to be fed into the Emojify-V1 model. Let's implement the model! 1.3 - Implementing Emojifier-V1 As shown in Figure (2), the first step is to convert an input sentence into the word vector representation, which then get averaged together. Similar to the previous exercise, we will use pretrained 50-dimensional GloVe embeddings. Run the following cell to load the word_to_vec_map, which contains all the vector representations. End of explanation """ word = "cucumber" index = 289846 print("the index of", word, "in the vocabulary is", word_to_index[word]) print("the", str(index) + "th word in the vocabulary is", index_to_word[index]) """ Explanation: You've loaded: - word_to_index: dictionary mapping from words to their indices in the vocabulary (400,001 words, with the valid indices ranging from 0 to 400,000) - index_to_word: dictionary mapping from indices to their corresponding words in the vocabulary - word_to_vec_map: dictionary mapping words to their GloVe vector representation. Run the following cell to check if it works. End of explanation """ # GRADED FUNCTION: sentence_to_avg def sentence_to_avg(sentence, word_to_vec_map): """ Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word and averages its value into a single vector encoding the meaning of the sentence. Arguments: sentence -- string, one training example from X word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation Returns: avg -- average vector encoding information about the sentence, numpy-array of shape (50,) """ ### START CODE HERE ### # Step 1: Split sentence into list of lower case words (≈ 1 line) words = sentence.lower().split() print(words) # Initialize the average word vector, should have the same shape as your word vectors. avg = np.zeros((50,)) # Step 2: average the word vectors. You can loop over the words in the list "words". for w in words: avg += word_to_vec_map[w] avg = avg / len(words) ### END CODE HERE ### return avg avg = sentence_to_avg("Morrocan couscous is my favorite dish", word_to_vec_map) print("avg = ", avg) """ Explanation: Exercise: Implement sentence_to_avg(). You will need to carry out two steps: 1. Convert every sentence to lower-case, then split the sentence into a list of words. X.lower() and X.split() might be useful. 2. For each word in the sentence, access its GloVe representation. Then, average all these values. End of explanation """ # GRADED FUNCTION: model def model(X, Y, word_to_vec_map, learning_rate = 0.01, num_iterations = 400): """ Model to train word vector representations in numpy. Arguments: X -- input data, numpy array of sentences as strings, of shape (m, 1) Y -- labels, numpy array of integers between 0 and 7, numpy-array of shape (m, 1) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation learning_rate -- learning_rate for the stochastic gradient descent algorithm num_iterations -- number of iterations Returns: pred -- vector of predictions, numpy-array of shape (m, 1) W -- weight matrix of the softmax layer, of shape (n_y, n_h) b -- bias of the softmax layer, of shape (n_y,) """ np.random.seed(1) # Define number of training examples m = Y.shape[0] # number of training examples n_y = 5 # number of classes n_h = 50 # dimensions of the GloVe vectors # Initialize parameters using Xavier initialization W = np.random.randn(n_y, n_h) / np.sqrt(n_h) b = np.zeros((n_y,)) # Convert Y to Y_onehot with n_y classes Y_oh = convert_to_one_hot(Y, C = n_y) # Optimization loop for t in range(num_iterations): # Loop over the number of iterations for i in range(m): # Loop over the training examples ### START CODE HERE ### (≈ 4 lines of code) # Average the word vectors of the words from the i'th training example avg = sentence_to_avg(X[i], word_to_vec_map) # Forward propagate the avg through the softmax layer z = np.dot(W, avg) + b a = softmax(z) # Compute cost using the i'th training label's one hot representation and "A" (the output of the softmax) cost = -np.sum(Y_oh[i] * np.log(a)) ### END CODE HERE ### # Compute gradients dz = a - Y_oh[i] dW = np.dot(dz.reshape(n_y,1), avg.reshape(1, n_h)) db = dz # Update parameters with Stochastic Gradient Descent W = W - learning_rate * dW b = b - learning_rate * db if t % 100 == 0: print("Epoch: " + str(t) + " --- cost = " + str(cost)) pred = predict(X, Y, W, b, word_to_vec_map) return pred, W, b print(X_train.shape) print(Y_train.shape) print(np.eye(5)[Y_train.reshape(-1)].shape) print(X_train[0]) print(type(X_train)) Y = np.asarray([5,0,0,5, 4, 4, 4, 6, 6, 4, 1, 1, 5, 6, 6, 3, 6, 3, 4, 4]) print(Y.shape) X = np.asarray(['I am going to the bar tonight', 'I love you', 'miss you my dear', 'Lets go party and drinks','Congrats on the new job','Congratulations', 'I am so happy for you', 'Why are you feeling bad', 'What is wrong with you', 'You totally deserve this prize', 'Let us go play football', 'Are you down for football this afternoon', 'Work hard play harder', 'It is suprising how people can be dumb sometimes', 'I am very disappointed','It is the best day in my life', 'I think I will end up alone','My life is so boring','Good job', 'Great so awesome']) print(X.shape) print(np.eye(5)[Y_train.reshape(-1)].shape) print(type(X_train)) """ Explanation: Expected Output: <table> <tr> <td> **avg= ** </td> <td> [-0.008005 0.56370833 -0.50427333 0.258865 0.55131103 0.03104983 -0.21013718 0.16893933 -0.09590267 0.141784 -0.15708967 0.18525867 0.6495785 0.38371117 0.21102167 0.11301667 0.02613967 0.26037767 0.05820667 -0.01578167 -0.12078833 -0.02471267 0.4128455 0.5152061 0.38756167 -0.898661 -0.535145 0.33501167 0.68806933 -0.2156265 1.797155 0.10476933 -0.36775333 0.750785 0.10282583 0.348925 -0.27262833 0.66768 -0.10706167 -0.283635 0.59580117 0.28747333 -0.3366635 0.23393817 0.34349183 0.178405 0.1166155 -0.076433 0.1445417 0.09808667] </td> </tr> </table> Model You now have all the pieces to finish implementing the model() function. After using sentence_to_avg() you need to pass the average through forward propagation, compute the cost, and then backpropagate to update the softmax's parameters. Exercise: Implement the model() function described in Figure (2). Assuming here that $Yoh$ ("Y one hot") is the one-hot encoding of the output labels, the equations you need to implement in the forward pass and to compute the cross-entropy cost are: $$ z^{(i)} = W . avg^{(i)} + b$$ $$ a^{(i)} = softmax(z^{(i)})$$ $$ \mathcal{L}^{(i)} = - \sum_{k = 0}^{n_y - 1} Yoh^{(i)}_k * log(a^{(i)}_k)$$ It is possible to come up with a more efficient vectorized implementation. But since we are using a for-loop to convert the sentences one at a time into the avg^{(i)} representation anyway, let's not bother this time. We provided you a function softmax(). End of explanation """ pred, W, b = model(X_train, Y_train, word_to_vec_map) print(pred) """ Explanation: Run the next cell to train your model and learn the softmax parameters (W,b). End of explanation """ print("Training set:") pred_train = predict(X_train, Y_train, W, b, word_to_vec_map) print('Test set:') pred_test = predict(X_test, Y_test, W, b, word_to_vec_map) """ Explanation: Expected Output (on a subset of iterations): <table> <tr> <td> **Epoch: 0** </td> <td> cost = 1.95204988128 </td> <td> Accuracy: 0.348484848485 </td> </tr> <tr> <td> **Epoch: 100** </td> <td> cost = 0.0797181872601 </td> <td> Accuracy: 0.931818181818 </td> </tr> <tr> <td> **Epoch: 200** </td> <td> cost = 0.0445636924368 </td> <td> Accuracy: 0.954545454545 </td> </tr> <tr> <td> **Epoch: 300** </td> <td> cost = 0.0343226737879 </td> <td> Accuracy: 0.969696969697 </td> </tr> </table> Great! Your model has pretty high accuracy on the training set. Lets now see how it does on the test set. 1.4 - Examining test set performance End of explanation """ X_my_sentences = np.array(["i adore you", "i love you", "funny lol", "lets play with a ball", "food is ready", "not feeling happy"]) Y_my_labels = np.array([[0], [0], [2], [1], [4],[3]]) pred = predict(X_my_sentences, Y_my_labels , W, b, word_to_vec_map) print_predictions(X_my_sentences, pred) """ Explanation: Expected Output: <table> <tr> <td> **Train set accuracy** </td> <td> 97.7 </td> </tr> <tr> <td> **Test set accuracy** </td> <td> 85.7 </td> </tr> </table> Random guessing would have had 20% accuracy given that there are 5 classes. This is pretty good performance after training on only 127 examples. In the training set, the algorithm saw the sentence "I love you" with the label ❤️. You can check however that the word "adore" does not appear in the training set. Nonetheless, lets see what happens if you write "I adore you." End of explanation """ print(Y_test.shape) print(' '+ label_to_emoji(0)+ ' ' + label_to_emoji(1) + ' ' + label_to_emoji(2)+ ' ' + label_to_emoji(3)+' ' + label_to_emoji(4)) print(pd.crosstab(Y_test, pred_test.reshape(56,), rownames=['Actual'], colnames=['Predicted'], margins=True)) plot_confusion_matrix(Y_test, pred_test) """ Explanation: Amazing! Because adore has a similar embedding as love, the algorithm has generalized correctly even to a word it has never seen before. Words such as heart, dear, beloved or adore have embedding vectors similar to love, and so might work too---feel free to modify the inputs above and try out a variety of input sentences. How well does it work? Note though that it doesn't get "not feeling happy" correct. This algorithm ignores word ordering, so is not good at understanding phrases like "not happy." Printing the confusion matrix can also help understand which classes are more difficult for your model. A confusion matrix shows how often an example whose label is one class ("actual" class) is mislabeled by the algorithm with a different class ("predicted" class). End of explanation """ import numpy as np np.random.seed(0) from keras.models import Model from keras.layers import Dense, Input, Dropout, LSTM, Activation from keras.layers.embeddings import Embedding from keras.preprocessing import sequence from keras.initializers import glorot_uniform np.random.seed(1) """ Explanation: <font color='blue'> What you should remember from this part: - Even with a 127 training examples, you can get a reasonably good model for Emojifying. This is due to the generalization power word vectors gives you. - Emojify-V1 will perform poorly on sentences such as "This movie is not good and not enjoyable" because it doesn't understand combinations of words--it just averages all the words' embedding vectors together, without paying attention to the ordering of words. You will build a better algorithm in the next part. 2 - Emojifier-V2: Using LSTMs in Keras: Let's build an LSTM model that takes as input word sequences. This model will be able to take word ordering into account. Emojifier-V2 will continue to use pre-trained word embeddings to represent words, but will feed them into an LSTM, whose job it is to predict the most appropriate emoji. Run the following cell to load the Keras packages. End of explanation """ # GRADED FUNCTION: sentences_to_indices def sentences_to_indices(X, word_to_index, max_len): """ Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to `Embedding()` (described in Figure 4). Arguments: X -- array of sentences (strings), of shape (m, 1) word_to_index -- a dictionary containing the each word mapped to its index max_len -- maximum number of words in a sentence. You can assume every sentence in X is no longer than this. Returns: X_indices -- array of indices corresponding to words in the sentences from X, of shape (m, max_len) """ m = X.shape[0] # number of training examples ### START CODE HERE ### # Initialize X_indices as a numpy matrix of zeros and the correct shape (≈ 1 line) X_indices = np.zeros((m, max_len)) for i in range(m): # loop over training examples # Convert the ith training sentence in lower case and split is into words. You should get a list of words. sentence_words = X[i].lower().split() # Initialize j to 0 j = 0 # Loop over the words of sentence_words for w in sentence_words: # Set the (i,j)th entry of X_indices to the index of the correct word. X_indices[i, j] = word_to_index[w] # Increment j to j + 1 j = j+1 ### END CODE HERE ### return X_indices """ Explanation: 2.1 - Overview of the model Here is the Emojifier-v2 you will implement: <img src="images/emojifier-v2.png" style="width:700px;height:400px;"> <br> <caption><center> Figure 3: Emojifier-V2. A 2-layer LSTM sequence classifier. </center></caption> 2.2 Keras and mini-batching In this exercise, we want to train Keras using mini-batches. However, most deep learning frameworks require that all sequences in the same mini-batch have the same length. This is what allows vectorization to work: If you had a 3-word sentence and a 4-word sentence, then the computations needed for them are different (one takes 3 steps of an LSTM, one takes 4 steps) so it's just not possible to do them both at the same time. The common solution to this is to use padding. Specifically, set a maximum sequence length, and pad all sequences to the same length. For example, of the maximum sequence length is 20, we could pad every sentence with "0"s so that each input sentence is of length 20. Thus, a sentence "i love you" would be represented as $(e_{i}, e_{love}, e_{you}, \vec{0}, \vec{0}, \ldots, \vec{0})$. In this example, any sentences longer than 20 words would have to be truncated. One simple way to choose the maximum sequence length is to just pick the length of the longest sentence in the training set. 2.3 - The Embedding layer In Keras, the embedding matrix is represented as a "layer", and maps positive integers (indices corresponding to words) into dense vectors of fixed size (the embedding vectors). It can be trained or initialized with a pretrained embedding. In this part, you will learn how to create an Embedding() layer in Keras, initialize it with the GloVe 50-dimensional vectors loaded earlier in the notebook. Because our training set is quite small, we will not update the word embeddings but will instead leave their values fixed. But in the code below, we'll show you how Keras allows you to either train or leave fixed this layer. The Embedding() layer takes an integer matrix of size (batch size, max input length) as input. This corresponds to sentences converted into lists of indices (integers), as shown in the figure below. <img src="images/embedding1.png" style="width:700px;height:250px;"> <caption><center> Figure 4: Embedding layer. This example shows the propagation of two examples through the embedding layer. Both have been zero-padded to a length of max_len=5. The final dimension of the representation is (2,max_len,50) because the word embeddings we are using are 50 dimensional. </center></caption> The largest integer (i.e. word index) in the input should be no larger than the vocabulary size. The layer outputs an array of shape (batch size, max input length, dimension of word vectors). The first step is to convert all your training sentences into lists of indices, and then zero-pad all these lists so that their length is the length of the longest sentence. Exercise: Implement the function below to convert X (array of sentences as strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to Embedding() (described in Figure 4). End of explanation """ X1 = np.array(["funny lol", "lets play baseball", "food is ready for you"]) X1_indices = sentences_to_indices(X1,word_to_index, max_len = 5) print("X1 =", X1) print("X1_indices =", X1_indices) """ Explanation: Run the following cell to check what sentences_to_indices() does, and check your results. End of explanation """ # GRADED FUNCTION: pretrained_embedding_layer def pretrained_embedding_layer(word_to_vec_map, word_to_index): """ Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words) Returns: embedding_layer -- pretrained layer Keras instance """ vocab_len = len(word_to_index) + 1 # adding 1 to fit Keras embedding (requirement) emb_dim = word_to_vec_map["cucumber"].shape[0] # define dimensionality of your GloVe word vectors (= 50) ### START CODE HERE ### # Initialize the embedding matrix as a numpy array of zeros of shape (vocab_len, dimensions of word vectors = emb_dim) emb_matrix = np.zeros((vocab_len, emb_dim)) # Set each row "index" of the embedding matrix to be the word vector representation of the "index"th word of the vocabulary for word, index in word_to_index.items(): emb_matrix[index, :] = word_to_vec_map[word] # Define Keras embedding layer with the correct output/input sizes, make it trainable. Use Embedding(...). Make sure to set trainable=False. embedding_layer = Embedding(vocab_len, emb_dim, trainable = False) ### END CODE HERE ### # Build the embedding layer, it is required before setting the weights of the embedding layer. Do not modify the "None". embedding_layer.build((None,)) # Set the weights of the embedding layer to the embedding matrix. Your layer is now pretrained. embedding_layer.set_weights([emb_matrix]) return embedding_layer embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index) print("weights[0][1][3] =", embedding_layer.get_weights()[0][1][3]) """ Explanation: Expected Output: <table> <tr> <td> **X1 =** </td> <td> ['funny lol' 'lets play football' 'food is ready for you'] </td> </tr> <tr> <td> **X1_indices =** </td> <td> [[ 155345. 225122. 0. 0. 0.] <br> [ 220930. 286375. 151266. 0. 0.] <br> [ 151204. 192973. 302254. 151349. 394475.]] </td> </tr> </table> Let's build the Embedding() layer in Keras, using pre-trained word vectors. After this layer is built, you will pass the output of sentences_to_indices() to it as an input, and the Embedding() layer will return the word embeddings for a sentence. Exercise: Implement pretrained_embedding_layer(). You will need to carry out the following steps: 1. Initialize the embedding matrix as a numpy array of zeroes with the correct shape. 2. Fill in the embedding matrix with all the word embeddings extracted from word_to_vec_map. 3. Define Keras embedding layer. Use Embedding(). Be sure to make this layer non-trainable, by setting trainable = False when calling Embedding(). If you were to set trainable = True, then it will allow the optimization algorithm to modify the values of the word embeddings. 4. Set the embedding weights to be equal to the embedding matrix End of explanation """ # GRADED FUNCTION: Emojify_V2 def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words) Returns: model -- a model instance in Keras """ ### START CODE HERE ### # Define sentence_indices as the input of the graph, it should be of shape input_shape and dtype 'int32' (as it contains indices). sentence_indices = Input(shape = input_shape, dtype = 'int32') # Create the embedding layer pretrained with GloVe Vectors (≈1 line) embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index) # Propagate sentence_indices through your embedding layer, you get back the embeddings embeddings = embedding_layer(sentence_indices) # Propagate the embeddings through an LSTM layer with 128-dimensional hidden state # Be careful, the returned output should be a batch of sequences. X = LSTM(128, return_sequences = True)(embeddings) # Add dropout with a probability of 0.5 X = Dropout(0.5)(X) # Propagate X trough another LSTM layer with 128-dimensional hidden state # Be careful, the returned output should be a single hidden state, not a batch of sequences. X = LSTM(128, return_sequences = False)(X) # Add dropout with a probability of 0.5 X = Dropout(0.5)(X) # Propagate X through a Dense layer with softmax activation to get back a batch of 5-dimensional vectors. X = Dense(5)(X) # Add a softmax activation X = Activation('softmax')(X) # Create Model instance which converts sentence_indices into X. model = Model(inputs = sentence_indices, outputs = X) ### END CODE HERE ### return model """ Explanation: Expected Output: <table> <tr> <td> **weights[0][1][3] =** </td> <td> -0.3403 </td> </tr> </table> 2.3 Building the Emojifier-V2 Lets now build the Emojifier-V2 model. You will do so using the embedding layer you have built, and feed its output to an LSTM network. <img src="images/emojifier-v2.png" style="width:700px;height:400px;"> <br> <caption><center> Figure 3: Emojifier-v2. A 2-layer LSTM sequence classifier. </center></caption> Exercise: Implement Emojify_V2(), which builds a Keras graph of the architecture shown in Figure 3. The model takes as input an array of sentences of shape (m, max_len, ) defined by input_shape. It should output a softmax probability vector of shape (m, C = 5). You may need Input(shape = ..., dtype = '...'), LSTM(), Dropout(), Dense(), and Activation(). End of explanation """ model = Emojify_V2((maxLen,), word_to_vec_map, word_to_index) model.summary() """ Explanation: Run the following cell to create your model and check its summary. Because all sentences in the dataset are less than 10 words, we chose max_len = 10. You should see your architecture, it uses "20,223,927" parameters, of which 20,000,050 (the word embeddings) are non-trainable, and the remaining 223,877 are. Because our vocabulary size has 400,001 words (with valid indices from 0 to 400,000) there are 400,001*50 = 20,000,050 non-trainable parameters. End of explanation """ model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) """ Explanation: As usual, after creating your model in Keras, you need to compile it and define what loss, optimizer and metrics your are want to use. Compile your model using categorical_crossentropy loss, adam optimizer and ['accuracy'] metrics: End of explanation """ X_train_indices = sentences_to_indices(X_train, word_to_index, maxLen) Y_train_oh = convert_to_one_hot(Y_train, C = 5) """ Explanation: It's time to train your model. Your Emojifier-V2 model takes as input an array of shape (m, max_len) and outputs probability vectors of shape (m, number of classes). We thus have to convert X_train (array of sentences as strings) to X_train_indices (array of sentences as list of word indices), and Y_train (labels as indices) to Y_train_oh (labels as one-hot vectors). End of explanation """ model.fit(X_train_indices, Y_train_oh, epochs = 50, batch_size = 32, shuffle=True) """ Explanation: Fit the Keras model on X_train_indices and Y_train_oh. We will use epochs = 50 and batch_size = 32. End of explanation """ X_test_indices = sentences_to_indices(X_test, word_to_index, max_len = maxLen) Y_test_oh = convert_to_one_hot(Y_test, C = 5) loss, acc = model.evaluate(X_test_indices, Y_test_oh) print() print("Test accuracy = ", acc) """ Explanation: Your model should perform close to 100% accuracy on the training set. The exact accuracy you get may be a little different. Run the following cell to evaluate your model on the test set. End of explanation """ # This code allows you to see the mislabelled examples C = 5 y_test_oh = np.eye(C)[Y_test.reshape(-1)] X_test_indices = sentences_to_indices(X_test, word_to_index, maxLen) pred = model.predict(X_test_indices) for i in range(len(X_test)): x = X_test_indices num = np.argmax(pred[i]) if(num != Y_test[i]): print('Expected emoji:'+ label_to_emoji(Y_test[i]) + ' prediction: '+ X_test[i] + label_to_emoji(num).strip()) """ Explanation: You should get a test accuracy between 80% and 95%. Run the cell below to see the mislabelled examples. End of explanation """ # Change the sentence below to see your prediction. Make sure all the words are in the Glove embeddings. x_test = np.array(['not feeling happy']) X_test_indices = sentences_to_indices(x_test, word_to_index, maxLen) print(x_test[0] +' '+ label_to_emoji(np.argmax(model.predict(X_test_indices)))) """ Explanation: Now you can try it on your own example. Write your own sentence below. End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/ncc/cmip6/models/noresm2-lmec/landice.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-lmec', 'landice') """ Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NCC Source ID: NORESM2-LMEC Topic: Landice Sub-Topics: Glaciers, Ice. Properties: 30 (21 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:24 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Software Properties 3. Grid 4. Glaciers 5. Ice 6. Ice --&gt; Mass Balance 7. Ice --&gt; Mass Balance --&gt; Basal 8. Ice --&gt; Mass Balance --&gt; Frontal 9. Ice --&gt; Dynamics 1. Key Properties Land ice key properties 1.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of land surface model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of land surface model code End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.ice_albedo') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "prescribed" # "function of ice age" # "function of ice density" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Ice Albedo Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Specify how ice albedo is modelled End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.atmospheric_coupling_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.4. Atmospheric Coupling Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Which variables are passed between the atmosphere and ice (e.g. orography, ice mass) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.oceanic_coupling_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.5. Oceanic Coupling Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Which variables are passed between the ocean and ice End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "ice velocity" # "ice thickness" # "ice temperature" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.6. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Which variables are prognostically calculated in the ice model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Software Properties Software properties of land ice code 2.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3. Grid Land ice grid 3.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of the grid in the land ice scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 3.2. Adaptive Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is an adative grid being used? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.base_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.3. Base Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The base resolution (in metres), before any adaption End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.resolution_limit') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.4. Resolution Limit Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If an adaptive grid is being used, what is the limit of the resolution (in metres) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.projection') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.5. Projection Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The projection of the land ice grid (e.g. albers_equal_area) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4. Glaciers Land ice glaciers 4.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of glaciers in the land ice scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.2. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of glaciers, if any End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.dynamic_areal_extent') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 4.3. Dynamic Areal Extent Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Does the model include a dynamic glacial extent? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Ice Ice sheet and ice shelf 5.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of the ice sheet and ice shelf in the land ice scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.grounding_line_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "grounding line prescribed" # "flux prescribed (Schoof)" # "fixed grid size" # "moving grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 5.2. Grounding Line Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify the technique used for modelling the grounding line in the ice sheet-ice shelf coupling End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.ice_sheet') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 5.3. Ice Sheet Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Are ice sheets simulated? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.ice_shelf') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 5.4. Ice Shelf Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Are ice shelves simulated? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.surface_mass_balance') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Ice --&gt; Mass Balance Description of the surface mass balance treatment 6.1. Surface Mass Balance Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how and where the surface mass balance (SMB) is calulated. Include the temporal coupling frequeny from the atmosphere, whether or not a seperate SMB model is used, and if so details of this model, such as its resolution End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.basal.bedrock') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Ice --&gt; Mass Balance --&gt; Basal Description of basal melting 7.1. Bedrock Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the implementation of basal melting over bedrock End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.basal.ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.2. Ocean Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the implementation of basal melting over the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.frontal.calving') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Ice --&gt; Mass Balance --&gt; Frontal Description of claving/melting from the ice shelf front 8.1. Calving Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the implementation of calving from the front of the ice shelf End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.frontal.melting') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.2. Melting Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the implementation of melting from the front of the ice shelf End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Ice --&gt; Dynamics ** 9.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description if ice sheet and ice shelf dynamics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.approximation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "SIA" # "SAA" # "full stokes" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 9.2. Approximation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Approximation type used in modelling ice dynamics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.adaptive_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 9.3. Adaptive Timestep Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there an adaptive time scheme for the ice scheme? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 9.4. Timestep Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep (in seconds) of the ice scheme. If the timestep is adaptive, then state a representative timestep. End of explanation """
aburrell/davitpy
docs/notebook/maps.ipynb
gpl-3.0
%pylab inline from davitpy.pydarn.radar import * from davitpy.pydarn.plotting import * from davitpy.utils import * import datetime as dt """ Explanation: Mapping utilities and options This notebook illustrate how to map SuperDARN radars and FoVs End of explanation """ figure(figsize=(15,10)) # Plot map subplot(121) m1 = plotUtils.mapObj(boundinglat=30., gridLabels=True, coords='mag') overlayRadar(m1, fontSize=8, plot_all=True, markerSize=5) subplot(122) m2 = plotUtils.mapObj(boundinglat=-30., gridLabels=True, coords='mag') overlayRadar(m2, fontSize=8, plot_all=True, markerSize=5) """ Explanation: Plot all radars in AACGM coordinates Be patient, this takes a few seconds (so many radars, not to mention the coordinate calculatsions) End of explanation """ figure(figsize=(15,10)) # Plot map subplot(121) m1 = plotUtils.mapObj(boundinglat=30., gridLabels=False) overlayRadar(m1, fontSize=8, plot_all=True, markerSize=5) subplot(122) m2 = plotUtils.mapObj(boundinglat=-30., gridLabels=False) overlayRadar(m2, fontSize=8, plot_all=True, markerSize=5) """ Explanation: Plot all radars in geographic coordinates This is a bit faster (but there are still lots of radars) End of explanation """ # Set map figure(figsize=(10,10)) width = 111e3*40 m = plotUtils.mapObj(width=width, height=width, lat_0=60., lon_0=-30, coords='mag') code = 'bks' # Plotting some radars overlayRadar(m, fontSize=12, codes=code) # Plot radar fov overlayFov(m, codes=code, maxGate=75, beams=[0,4,7,8,23]) """ Explanation: Plot a single radar, highlight beams Still a bit slow due to aacgm coordinates End of explanation """ # Set map fig = figure(figsize=(10,10)) m = plotUtils.mapObj(lat_0=70., lon_0=-60, width=111e3*120, height=111e3*55, coords='mag') codes = ['wal','fhe','fhw','cve','cvw','hok','ade','adw','bks'] # Plotting some radars overlayRadar(m, fontSize=12, codes=codes) # Plot radar fov overlayFov(m, codes=codes[:-1], maxGate=70)#, fovColor=(.8,.9,.9)) overlayFov(m, codes=codes[-1], maxGate=70, fovColor=(.8,.7,.8), fovAlpha=.5) fig.tight_layout(pad=2) rcParams.update({'font.size': 12}) """ Explanation: Plot a nice view of the mid-latitude radars End of explanation """ # Set map figure(figsize=(8,8)) lon_0 = -70. m = plotUtils.mapObj(boundinglat=35., lon_0=lon_0) # Go through each radar codes = ['gbr','kap','sas','pgr', \ 'kod','sto','pyk','han', \ 'ksr','cve','cvw','wal', \ 'bks','hok','fhw','fhe', \ 'inv','rkn'] beams = [[3,4,6],[10,11,13],[2,3,5],[12,13,15], \ [2,3,5],[12,13,15],[0,1,3],[5,6,8], \ [12,13,15],[0,1,3],[19,20,22],[0,1,3], \ [12,13,15],[0,1,3],[18,19,21],[0,1,3],\ [6,7,9],[6,7,9]] for i,rad in enumerate(codes): # Plot radar overlayRadar(m, fontSize=12, codes=rad) # Plot radar fov overlayFov(m, codes=rad, maxGate=75, beams=beams[i]) #savefig('rbsp_beams.pdf') """ Explanation: Plot the RBSP mode This is sloooooooow... End of explanation """
morganics/bayesianpy
examples/notebook/iris_anomaly_detection.ipynb
apache-2.0
%matplotlib notebook import pandas as pd import sys sys.path.append("../../../bayesianpy") import bayesianpy from bayesianpy.network import Builder as builder import logging import os import matplotlib.pyplot as plt from IPython.display import display logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) bayesianpy.jni.attach(logger) db_folder = bayesianpy.utils.get_path_to_parent_dir("") iris = pd.read_csv(os.path.join(db_folder, "data/iris.csv"), index_col=False) """ Explanation: Anomaly detection using the Iris dataset The Iris dataset is not perhaps the most natural dataset for anomaly detection, so I will get round to writing one with a slightly more appropriate dataset at some point. Regardless, the principles are the same; unsupervised learning of a 'normal' model, e.g. generating a model of normality and using that to identify anomalous data points. It's then possible to use the Log Likelihood score to identify points that aren't 'normal'. In practical terms there are some hurdles, in that ideally the model of normality should be (in general) normal, and abnormal points in the system that you're monitoring should be removed (it really is quite sensitive to training data); whether manually or automatically. If performing automatic removal you can use a more constrained model rather than using exactly the same structure. On the other hand, there are a host of benefits; it's possible to identify the likely variables that caused the abnormality, and it's also possible to identify what the model is expecting it to be. In that regard (unlike many other approaches), the model can essenentially be debugged by identifying which variables are not performing in the way that would be expected. This article won't cover those two additional points, but I will return to it at a later date. First off, define all the imports. End of explanation """ network = bayesianpy.network.create_network() cluster = builder.create_cluster_variable(network, 4) petal_length = builder.create_continuous_variable(network, "petal_length") petal_width = builder.create_continuous_variable(network, "petal_width") sepal_length = builder.create_continuous_variable(network, "sepal_length") sepal_width = builder.create_continuous_variable(network, "sepal_width") nodes = [petal_length, petal_width, sepal_length, sepal_width] for i, node in enumerate(nodes): builder.create_link(network, cluster, node) for j in range(i+1, len(nodes)): builder.create_link(network, node, nodes[j]) layout = bayesianpy.visual.NetworkLayout(network) graph = layout.build_graph() pos = layout.fruchterman_reingold_layout(graph) layout.visualise(graph, pos) """ Explanation: Rather than using a template to build the network, it's fairly easy to define it by hand. The network looks something like the following: End of explanation """ # build the 'normal' model on two of the classes model = bayesianpy.model.NetworkModel(network, logger) with bayesianpy.data.DataSet(iris.drop('iris_class', axis=1), db_folder, logger) as dataset: subset = dataset.subset( iris[(iris.iris_class == "Iris-versicolor") | (iris.iris_class == "Iris-virginica")].index.tolist()) model.train(subset) """ Explanation: Using the above network, train the model on only two of the classes (for clarity, I chose the two that are least separated, versicolor and virginica) End of explanation """ with bayesianpy.data.DataSet(iris.drop('iris_class', axis=1), db_folder, logger) as dataset: # get the loglikelihood value for the whole model on each individual sample, # the lower the loglikelihood value the less likely the data point has been # generated by the model. results = model.batch_query(dataset, [bayesianpy.model.QueryModelStatistics()]) display(results) cmap = plt.cm.get_cmap('Blues_r') fig = plt.figure(figsize=(10, 10)) k = 1 for i, v in enumerate(nodes): for j in range(i+1, len(nodes)): v_name = v.getName() v1_name = nodes[j].getName() ax = fig.add_subplot(3,2,k) ax.set_title("{} vs {}".format(v_name, v1_name)) h = ax.scatter(x=iris[v_name].tolist(), y=iris[v1_name].tolist(), c=results['loglikelihood'].tolist(), vmin=results.loglikelihood.min(), vmax=results.loglikelihood.max(), cmap=cmap ) k+=1 fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(h, cax=cbar_ax) plt.show() """ Explanation: The network is then ready for anomaly detection; this entails applying the entire dataset to the trained model, and plotting the results. The Log Likelihood will always give a negative value, the closer to 0, the more normal the applied data sample is. End of explanation """
mangecoeur/pineapple
data/examples/python3.5/Execution.ipynb
gpl-3.0
def f(x): return 1.0 / x def g(x): return x - 1.0 f(g(1.0)) """ Explanation: Executing Code In this notebook we'll look at some of the issues surrounding executing code in the notebook. Backtraces When you interrupt a computation, or if an exception is raised but not caught, you will see a backtrace of what was happening when the program halted. The backtrace is color highlighted to help you find the information you need to debug the problem. End of explanation """ %pdb on f(g(1.0)) """ Explanation: Python Debugging You can also turn on the Python debugger inside a notebook using the magic invocation %pdb on. When an exception occurs, the debugger will activate inside the output cell. You can then type commands and see responses from the stopped state of the program. Some commands: - h help - w print stack trace - p expr print expressions - q quit - r restart Full documentation on the debugger can be found at Python debugger pdb. End of explanation """ import sys print('Hello, world!') sys.stdout.write('We meet again, stdout.') sys.stderr.write('Error, you appear to have created a black hole.') """ Explanation: Output Normal output is shown after the In[] area. Output written to stdout is shown in one color, while output written to stderr is shown with a red background. End of explanation """ import time for i in range(10): print(i) time.sleep(0.5) """ Explanation: Asynchronous Output Output written to stdout and stderr shows up immediately in the notebook, you don't have to wait for the evaluation to finish before you see anything. Here is demo. End of explanation """ import threading class SummingThread(threading.Thread): def __init__(self, low, high): super(SummingThread, self).__init__() self.low = low self.high = high self.total = 0 def run(self): for i in range(self.low, self.high): self.total += i def sequential_sum(n): total = 0 for i in range(0, n): total += i return total def parallel_sum(n): thread1 = SummingThread(0, n//2) thread2 = SummingThread(n//2, n) thread1.start() thread2.start() thread1.join() thread2.join() return thread1.total + thread2.total %timeit sequential_sum(100000) %timeit parallel_sum(1000000) """ Explanation: Threads You can start multiple threads and use the standard Python threading libraries such as threads and threading to coordinate between them. Note that because of the global interpreter lock in CPython two threads with work to do will never run at the same time. End of explanation """ from time import sleep from multiprocessing import Pool def f(p): low, high = p total = 0 for i in range(low, high): total += i return total def sequential_sum(n): total = 0 for i in range(0, n): total += i return total def parallel_sum(n): p = Pool(2) results = p.map(f, [[0, n//2], [n//2, n]]) return results[0] + results[1] if __name__ == "__main__": %timeit sequential_sum(10000) %timeit parallel_sum(100000) """ Explanation: Multiprocessing It is possible to use the multiprocessing library inside Pineapple notebooks. The multiprocessing library spawns multiple interpreters which can actually run in parallel. Of course this is still no guarantee of higher performance. End of explanation """
GoogleCloudPlatform/mlops-on-gcp
immersion/kubeflow_pipelines/walkthrough/labs/lab-01_vertex.ipynb
apache-2.0
!pip freeze | grep google-cloud-aiplatform || pip install google-cloud-aiplatform import os import time from google.cloud import aiplatform from google.cloud import bigquery import pandas as pd from sklearn.compose import ColumnTransformer from sklearn.linear_model import SGDClassifier from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, OneHotEncoder """ Explanation: Using custom containers with Vertex AI Training Learning Objectives: 1. Learn how to create a train and a validation split with BigQuery 1. Learn how to wrap a machine learning model into a Docker container and train in on Vertex AI 1. Learn how to use the hyperparameter tuning engine on Vertex AI to find the best hyperparameters 1. Learn how to deploy a trained machine learning model on Vertex AI as a REST API and query it In this lab, you develop, package as a docker image, and run on Vertex AI Training a training application that trains a multi-class classification model that predicts the type of forest cover from cartographic data. The dataset used in the lab is based on Covertype Data Set from UCI Machine Learning Repository. The training code uses scikit-learn for data pre-processing and modeling. The code has been instrumented using the hypertune package so it can be used with Vertex AI hyperparameter tuning. End of explanation """ REGION = 'us-central1' PROJECT_ID = !(gcloud config get-value core/project) PROJECT_ID = PROJECT_ID[0] ARTIFACT_STORE = f'gs://{PROJECT_ID}-vertex' DATA_ROOT = f'{ARTIFACT_STORE}/data' JOB_DIR_ROOT = f'{ARTIFACT_STORE}/jobs' TRAINING_FILE_PATH = f'{DATA_ROOT}/training/dataset.csv' VALIDATION_FILE_PATH = f'{DATA_ROOT}/validation/dataset.csv' API_ENDPOINT = f'{REGION}-aiplatform.googleapis.com' os.environ['JOB_DIR_ROOT'] = JOB_DIR_ROOT os.environ['TRAINING_FILE_PATH'] = TRAINING_FILE_PATH os.environ['VALIDATION_FILE_PATH'] = VALIDATION_FILE_PATH os.environ['PROJECT_ID'] = PROJECT_ID os.environ['REGION'] = REGION """ Explanation: Configure environment settings Set location paths, connections strings, and other environment settings. Make sure to update REGION, and ARTIFACT_STORE with the settings reflecting your lab environment. REGION - the compute region for Vertex AI Training and Prediction ARTIFACT_STORE - A GCS bucket in the created in the same region. End of explanation """ !gsutil ls | grep ^{ARTIFACT_STORE}/$ || gsutil mb -l {REGION} {ARTIFACT_STORE} """ Explanation: We now create the ARTIFACT_STORE bucket if it's not there. Note that this bucket should be created in the region specified in the variable REGION (if you have already a bucket with this name in a different region than REGION, you may want to change the ARTIFACT_STORE name so that you can recreate a bucket in REGION with the command in the cell below). End of explanation """ %%bash DATASET_LOCATION=US DATASET_ID=covertype_dataset TABLE_ID=covertype DATA_SOURCE=gs://workshop-datasets/covertype/small/dataset.csv SCHEMA=Elevation:INTEGER,\ Aspect:INTEGER,\ Slope:INTEGER,\ Horizontal_Distance_To_Hydrology:INTEGER,\ Vertical_Distance_To_Hydrology:INTEGER,\ Horizontal_Distance_To_Roadways:INTEGER,\ Hillshade_9am:INTEGER,\ Hillshade_Noon:INTEGER,\ Hillshade_3pm:INTEGER,\ Horizontal_Distance_To_Fire_Points:INTEGER,\ Wilderness_Area:STRING,\ Soil_Type:STRING,\ Cover_Type:INTEGER bq --location=$DATASET_LOCATION --project_id=$PROJECT_ID mk --dataset $DATASET_ID bq --project_id=$PROJECT_ID --dataset_id=$DATASET_ID load \ --source_format=CSV \ --skip_leading_rows=1 \ --replace \ $TABLE_ID \ $DATA_SOURCE \ $SCHEMA """ Explanation: Importing the dataset into BigQuery End of explanation """ %%bigquery SELECT * FROM `covertype_dataset.covertype` """ Explanation: Explore the Covertype dataset End of explanation """ !bq query \ -n 0 \ --destination_table covertype_dataset.training \ --replace \ --use_legacy_sql=false \ 'SELECT * \ FROM `covertype_dataset.covertype` AS cover \ WHERE \ MOD(ABS(FARM_FINGERPRINT(TO_JSON_STRING(cover))), 10) IN (1, 2, 3, 4)' !bq extract \ --destination_format CSV \ covertype_dataset.training \ $TRAINING_FILE_PATH """ Explanation: Create training and validation splits Use BigQuery to sample training and validation splits and save them to GCS storage Create a training split End of explanation """ # TODO: You code to create the BQ table validation split # TODO: Your code to export the validation table to GCS df_train = pd.read_csv(TRAINING_FILE_PATH) df_validation = pd.read_csv(VALIDATION_FILE_PATH) print(df_train.shape) print(df_validation.shape) """ Explanation: Create a validation split Exercise End of explanation """ numeric_feature_indexes = slice(0, 10) categorical_feature_indexes = slice(10, 12) preprocessor = ColumnTransformer( transformers=[ ('num', StandardScaler(), numeric_feature_indexes), ('cat', OneHotEncoder(), categorical_feature_indexes) ]) pipeline = Pipeline([ ('preprocessor', preprocessor), ('classifier', SGDClassifier(loss='log', tol=1e-3)) ]) """ Explanation: Develop a training application Configure the sklearn training pipeline. The training pipeline preprocesses data by standardizing all numeric features using sklearn.preprocessing.StandardScaler and encoding all categorical features using sklearn.preprocessing.OneHotEncoder. It uses stochastic gradient descent linear classifier (SGDClassifier) for modeling. End of explanation """ num_features_type_map = {feature: 'float64' for feature in df_train.columns[numeric_feature_indexes]} df_train = df_train.astype(num_features_type_map) df_validation = df_validation.astype(num_features_type_map) """ Explanation: Convert all numeric features to float64 To avoid warning messages from StandardScaler all numeric features are converted to float64. End of explanation """ X_train = df_train.drop('Cover_Type', axis=1) y_train = df_train['Cover_Type'] X_validation = df_validation.drop('Cover_Type', axis=1) y_validation = df_validation['Cover_Type'] pipeline.set_params(classifier__alpha=0.001, classifier__max_iter=200) pipeline.fit(X_train, y_train) """ Explanation: Run the pipeline locally. End of explanation """ accuracy = pipeline.score(X_validation, y_validation) print(accuracy) """ Explanation: Calculate the trained model's accuracy. End of explanation """ TRAINING_APP_FOLDER = 'training_app' os.makedirs(TRAINING_APP_FOLDER, exist_ok=True) """ Explanation: Prepare the hyperparameter tuning application. Since the training run on this dataset is computationally expensive you can benefit from running a distributed hyperparameter tuning job on Vertex AI Training. End of explanation """ %%writefile {TRAINING_APP_FOLDER}/train.py import os import subprocess import sys import fire import hypertune import numpy as np import pandas as pd import pickle from sklearn.compose import ColumnTransformer from sklearn.linear_model import SGDClassifier from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, OneHotEncoder def train_evaluate(job_dir, training_dataset_path, validation_dataset_path, alpha, max_iter, hptune): df_train = pd.read_csv(training_dataset_path) df_validation = pd.read_csv(validation_dataset_path) if not hptune: df_train = pd.concat([df_train, df_validation]) numeric_feature_indexes = slice(0, 10) categorical_feature_indexes = slice(10, 12) preprocessor = ColumnTransformer( transformers=[ ('num', StandardScaler(), numeric_feature_indexes), ('cat', OneHotEncoder(), categorical_feature_indexes) ]) pipeline = Pipeline([ ('preprocessor', preprocessor), ('classifier', SGDClassifier(loss='log',tol=1e-3)) ]) num_features_type_map = {feature: 'float64' for feature in df_train.columns[numeric_feature_indexes]} df_train = df_train.astype(num_features_type_map) df_validation = df_validation.astype(num_features_type_map) print('Starting training: alpha={}, max_iter={}'.format(alpha, max_iter)) X_train = df_train.drop('Cover_Type', axis=1) y_train = df_train['Cover_Type'] pipeline.set_params(classifier__alpha=alpha, classifier__max_iter=max_iter) pipeline.fit(X_train, y_train) if hptune: X_validation = df_validation.drop('Cover_Type', axis=1) y_validation = df_validation['Cover_Type'] accuracy = pipeline.score(X_validation, y_validation) print('Model accuracy: {}'.format(accuracy)) # Log it with hypertune hpt = hypertune.HyperTune() hpt.report_hyperparameter_tuning_metric( hyperparameter_metric_tag='accuracy', metric_value=accuracy ) # Save the model if not hptune: model_filename = 'model.pkl' with open(model_filename, 'wb') as model_file: pickle.dump(pipeline, model_file) gcs_model_path = "{}/{}".format(job_dir, model_filename) subprocess.check_call(['gsutil', 'cp', model_filename, gcs_model_path], stderr=sys.stdout) print("Saved model in: {}".format(gcs_model_path)) if __name__ == "__main__": fire.Fire(train_evaluate) """ Explanation: Write the tuning script. Notice the use of the hypertune package to report the accuracy optimization metric to Vertex AI hyperparameter tuning service. End of explanation """ %%writefile {TRAINING_APP_FOLDER}/Dockerfile FROM gcr.io/deeplearning-platform-release/base-cpu RUN pip install -U fire cloudml-hypertune scikit-learn==0.20.4 pandas==0.24.2 # TODO """ Explanation: Package the script into a docker image. Notice that we are installing specific versions of scikit-learn and pandas in the training image. This is done to make sure that the training runtime in the training container is aligned with the serving runtime in the serving container. Make sure to update the URI for the base image so that it points to your project's Container Registry. Exercise Complete the Dockerfile below so that it copies the 'train.py' file into the container at /app and runs it when the container is started. End of explanation """ IMAGE_NAME='trainer_image' IMAGE_TAG='latest' IMAGE_URI='gcr.io/{}/{}:{}'.format(PROJECT_ID, IMAGE_NAME, IMAGE_TAG) os.environ['IMAGE_URI'] = IMAGE_URI !gcloud builds submit --tag $IMAGE_URI $TRAINING_APP_FOLDER """ Explanation: Build the docker image. You use Cloud Build to build the image and push it your project's Container Registry. As you use the remote cloud service to build the image, you don't need a local installation of Docker. End of explanation """ TIMESTAMP = time.strftime("%Y%m%d_%H%M%S") JOB_NAME = f"forestcover_tuning_{TIMESTAMP}" JOB_DIR = f"{JOB_DIR_ROOT}/{JOB_NAME}" os.environ['JOB_NAME'] = JOB_NAME os.environ['JOB_DIR'] = JOB_DIR """ Explanation: Submit an Vertex AI hyperparameter tuning job Create the hyperparameter configuration file. Recall that the training code uses SGDClassifier. The training application has been designed to accept two hyperparameters that control SGDClassifier: - Max iterations - Alpha The file below configures Vertex AI hypertuning to run up to 5 trials in parallel and to choose from two discrete values of max_iter and the linear range between 1.0e-4 and 1.0e-1 for alpha. End of explanation """ %%bash MACHINE_TYPE="n1-standard-4" REPLICA_COUNT=1 CONFIG_YAML=config.yaml cat <<EOF > $CONFIG_YAML studySpec: metrics: - metricId: accuracy goal: MAXIMIZE parameters: # TODO algorithm: ALGORITHM_UNSPECIFIED # results in Bayesian optimization trialJobSpec: workerPoolSpecs: - machineSpec: machineType: $MACHINE_TYPE replicaCount: $REPLICA_COUNT containerSpec: imageUri: $IMAGE_URI args: - --job_dir=$JOB_DIR - --training_dataset_path=$TRAINING_FILE_PATH - --validation_dataset_path=$VALIDATION_FILE_PATH - --hptune EOF gcloud ai hp-tuning-jobs create \ --region=# TODO \ --display-name=# TODO \ --config=# TODO \ --max-trial-count=# TODO \ --parallel-trial-count=# TODO echo "JOB_NAME: $JOB_NAME" """ Explanation: Exercise Complete the config.yaml file generated below so that the hyperparameter tunning engine try for parameter values * max_iter the two values 10 and 20 * alpha a linear range of values between 1.0e-4 and 1.0e-1 Also complete the gcloud command to start the hyperparameter tuning job with a max trial count and a max number of parallel trials both of 5 each. End of explanation """ def retrieve_best_trial_from_job_name(jobname): # TODO return best_trial """ Explanation: Go to the Vertex AI Training dashboard and view the progression of the HP tuning job under "Hyperparameter Tuning Jobs". Retrieve HP-tuning results. After the job completes you can review the results using GCP Console or programmatically using the following functions (note that this code supposes that the metrics that the hyperparameter tuning engine optimizes is maximized): Exercise Complete the body of the function below to retrieve the best trial from the JOBNAME: End of explanation """ best_trial = retrieve_best_trial_from_job_name(JOB_NAME) """ Explanation: You'll need to wait for the hyperparameter job to complete before being able to retrieve the best job by running the cell below. End of explanation """ alpha = best_trial.parameters[0].value max_iter = best_trial.parameters[1].value TIMESTAMP = time.strftime("%Y%m%d_%H%M%S") JOB_NAME = f"JOB_VERTEX_{TIMESTAMP}" JOB_DIR = f"{JOB_DIR_ROOT}/{JOB_NAME}" MACHINE_TYPE="n1-standard-4" REPLICA_COUNT=1 WORKER_POOL_SPEC = f"""\ machine-type={MACHINE_TYPE},\ replica-count={REPLICA_COUNT},\ container-image-uri={IMAGE_URI}\ """ ARGS = f"""\ --job_dir={JOB_DIR},\ --training_dataset_path={TRAINING_FILE_PATH},\ --validation_dataset_path={VALIDATION_FILE_PATH},\ --alpha={alpha},\ --max_iter={max_iter},\ --nohptune\ """ !gcloud ai custom-jobs create \ --region={REGION} \ --display-name={JOB_NAME} \ --worker-pool-spec={WORKER_POOL_SPEC} \ --args={ARGS} print("The model will be exported at:", JOB_DIR) """ Explanation: Retrain the model with the best hyperparameters You can now retrain the model using the best hyperparameters and using combined training and validation splits as a training dataset. Configure and run the training job End of explanation """ !gsutil ls $JOB_DIR """ Explanation: Examine the training output The training script saved the trained model as the 'model.pkl' in the JOB_DIR folder on GCS. Note: We need to wait for job triggered by the cell above to complete before running the cells below. End of explanation """ MODEL_NAME = 'forest_cover_classifier_2' SERVING_CONTAINER_IMAGE_URI = 'us-docker.pkg.dev/vertex-ai/prediction/sklearn-cpu.0-20:latest' SERVING_MACHINE_TYPE = "n1-standard-2" """ Explanation: Deploy the model to Vertex AI Prediction End of explanation """ uploaded_model = # TODO """ Explanation: Uploading the trained model Exercise Upload the trained model using aiplatform.Model.upload: End of explanation """ endpoint = # TODO """ Explanation: Deploying the uploaded model Exercise Deploy the model using uploaded_model: End of explanation """ instance = [2841.0, 45.0, 0.0, 644.0, 282.0, 1376.0, 218.0, 237.0, 156.0, 1003.0, "Commanche", "C4758"] # TODO """ Explanation: Serve predictions Prepare the input file with JSON formated instances. Exercise Query the deployed model using endpoint: End of explanation """
AEW2015/PYNQ_PR_Overlay
Pynq-Z1/notebooks/examples/usb_wifi.ipynb
bsd-3-clause
# Make sure the base overlay is loaded from pynq import Overlay from pynq.drivers import Usb_Wifi Overlay("base.bit").download() port = Usb_Wifi() """ Explanation: USB Wifi Example In this notebook, a wifi dongle has been plugged into the board. Specifically a RALink wifi dongle commonly used with Raspberry Pi kits is connected into the board. Using Linux calls and Python functions, we will determine the unique name of the dongle and then create a network entry for a known ssid/password pair. This demo was first done using an iPhone hotspot wireless connection. References <br> http://www.canakit.com/raspberry-pi-wifi.html <br> <img src="data/wifi.jpg"/> 1. Create usb wifi instance End of explanation """ port.connect('ssid', 'pwd') """ Explanation: 2. Connect to a wifi link End of explanation """ ! ping www.xilinx.com """ Explanation: 3. Test connection End of explanation """ port.reset() """ Explanation: 4. Reset connection End of explanation """
sdpython/teachpyx
_doc/notebooks/pandas/pandas_groupby.ipynb
mit
from jyquickhelper import add_notebook_menu add_notebook_menu() """ Explanation: Pandas et groupby Petit tour de passe passe autour d'un groupby et des valeurs manquantes qui ne sont plus prises en compte depuis les dernières versions. End of explanation """ import pandas data = [{"a":1, "b":2}, {"a":10, "b":20}, {"b":3}, {"b":4}] df = pandas.DataFrame(data) df df.groupby("a").sum() """ Explanation: groupby et valeur manquantes End of explanation """ from pandas_streaming.df import pandas_groupby_nan pandas_groupby_nan(df, "a").sum() """ Explanation: Les valeurs manquantes ont disparu et c'est le comportement attendu d'après groupby and missing values. Il est possible de ocrriger le tir avec la fonction implémenté dans ce module. End of explanation """
ZhangXinNan/tensorflow
tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb
apache-2.0
# to generate gifs !pip install imageio """ Explanation: Copyright 2018 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"). Convolutional VAE: An example with tf.keras and eager <table class="tfo-notebook-buttons" align="left"><td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td><td> <a target="_blank" href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a></td></table> This notebook demonstrates how to generate images of handwritten digits using tf.keras and eager execution by training a Variational Autoencoder. (VAE, [1], [2]). End of explanation """ from __future__ import absolute_import, division, print_function # Import TensorFlow >= 1.9 and enable eager execution import tensorflow as tf tfe = tf.contrib.eager tf.enable_eager_execution() import os import time import numpy as np import glob import matplotlib.pyplot as plt import PIL import imageio from IPython import display """ Explanation: Import TensorFlow and enable Eager execution End of explanation """ (train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data() train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32') test_images = test_images.reshape(test_images.shape[0], 28, 28, 1).astype('float32') # Normalizing the images to the range of [0., 1.] train_images /= 255. test_images /= 255. # Binarization train_images[train_images >= .5] = 1. train_images[train_images < .5] = 0. test_images[test_images >= .5] = 1. test_images[test_images < .5] = 0. TRAIN_BUF = 60000 BATCH_SIZE = 100 TEST_BUF = 10000 """ Explanation: Load the MNIST dataset Each MNIST image is originally a vector of 784 integers, each of which is between 0-255 and represents the intensity of a pixel. We model each pixel with a Bernoulli distribution in our model, and we statically binarize the dataset. End of explanation """ train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(TRAIN_BUF).batch(BATCH_SIZE) test_dataset = tf.data.Dataset.from_tensor_slices(test_images).shuffle(TEST_BUF).batch(BATCH_SIZE) """ Explanation: Use tf.data to create batches and shuffle the dataset End of explanation """ class CVAE(tf.keras.Model): def __init__(self, latent_dim): super(CVAE, self).__init__() self.latent_dim = latent_dim self.inference_net = tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(28, 28, 1)), tf.keras.layers.Conv2D( filters=32, kernel_size=3, strides=(2, 2), activation=tf.nn.relu), tf.keras.layers.Conv2D( filters=64, kernel_size=3, strides=(2, 2), activation=tf.nn.relu), tf.keras.layers.Flatten(), # No activation tf.keras.layers.Dense(latent_dim + latent_dim), ] ) self.generative_net = tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(latent_dim,)), tf.keras.layers.Dense(units=7*7*32, activation=tf.nn.relu), tf.keras.layers.Reshape(target_shape=(7, 7, 32)), tf.keras.layers.Conv2DTranspose( filters=64, kernel_size=3, strides=(2, 2), padding="SAME", activation=tf.nn.relu), tf.keras.layers.Conv2DTranspose( filters=32, kernel_size=3, strides=(2, 2), padding="SAME", activation=tf.nn.relu), # No activation tf.keras.layers.Conv2DTranspose( filters=1, kernel_size=3, strides=(1, 1), padding="SAME"), ] ) def sample(self, eps=None): if eps is None: eps = tf.random_normal(shape=(100, self.latent_dim)) return self.decode(eps, apply_sigmoid=True) def encode(self, x): mean, logvar = tf.split(self.inference_net(x), num_or_size_splits=2, axis=1) return mean, logvar def reparameterize(self, mean, logvar): eps = tf.random_normal(shape=mean.shape) return eps * tf.exp(logvar * .5) + mean def decode(self, z, apply_sigmoid=False): logits = self.generative_net(z) if apply_sigmoid: probs = tf.sigmoid(logits) return probs return logits """ Explanation: Wire up the generative and inference network with tf.keras.Sequential In our VAE example, we use two small ConvNets for the generative and inference network. Since these neural nets are small, we use tf.keras.Sequential to simplify our code. Let $x$ and $z$ denote the observation and latent variable respectively in the following descriptions. Generative Network This defines the generative model which takes a latent encoding as input, and outputs the parameters for a conditional distribution of the observation, i.e. $p(x|z)$. Additionally, we use a unit Gaussian prior $p(z)$ for the latent variable. Inference Network This defines an approximate posterior distribution $q(z|x)$, which takes as input an observation and outputs a set of parameters for the conditional distribution of the latent representation. In this example, we simply model this distribution as a diagonal Gaussian. In this case, the inference network outputs the mean and log-variance parameters of a factorized Gaussian (log-variance instead of the variance directly is for numerical stability). Reparameterization Trick During optimization, we can sample from $q(z|x)$ by first sampling from a unit Gaussian, and then multiplying by the standard deviation and adding the mean. This ensures the gradients could pass through the sample to the inference network parameters. Network architecture For the inference network, we use two convolutional layers followed by a fully-connected layer. In the generative network, we mirror this architecture by using a fully-connected layer followed by three convolution transpose layers (a.k.a. deconvolutional layers in some contexts). Note, it's common practice to avoid using batch normalization when training VAEs, since the additional stochasticity due to using mini-batches may aggravate instability on top of the stochasticity from sampling. End of explanation """ def log_normal_pdf(sample, mean, logvar, raxis=1): log2pi = tf.log(2. * np.pi) return tf.reduce_sum( -.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi), axis=raxis) def compute_loss(model, x): mean, logvar = model.encode(x) z = model.reparameterize(mean, logvar) x_logit = model.decode(z) cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_logit, labels=x) logpx_z = -tf.reduce_sum(cross_ent, axis=[1, 2, 3]) logpz = log_normal_pdf(z, 0., 0.) logqz_x = log_normal_pdf(z, mean, logvar) return -tf.reduce_mean(logpx_z + logpz - logqz_x) def compute_gradients(model, x): with tf.GradientTape() as tape: loss = compute_loss(model, x) return tape.gradient(loss, model.trainable_variables), loss optimizer = tf.train.AdamOptimizer(1e-4) def apply_gradients(optimizer, gradients, variables, global_step=None): optimizer.apply_gradients(zip(gradients, variables), global_step=global_step) """ Explanation: Define the loss function and the optimizer VAEs train by maximizing the evidence lower bound (ELBO) on the marginal log-likelihood: $$\log p(x) \ge \text{ELBO} = \mathbb{E}_{q(z|x)}\left[\log \frac{p(x, z)}{q(z|x)}\right].$$ In practice, we optimize the single sample Monte Carlo estimate of this expectation: $$\log p(x| z) + \log p(z) - \log q(z|x),$$ where $z$ is sampled from $q(z|x)$. Note: we could also analytically compute the KL term, but here we incorporate all three terms in the Monte Carlo estimator for simplicity. End of explanation """ epochs = 100 latent_dim = 50 num_examples_to_generate = 16 # keeping the random vector constant for generation (prediction) so # it will be easier to see the improvement. random_vector_for_generation = tf.random_normal( shape=[num_examples_to_generate, latent_dim]) model = CVAE(latent_dim) def generate_and_save_images(model, epoch, test_input): predictions = model.sample(test_input) fig = plt.figure(figsize=(4,4)) for i in range(predictions.shape[0]): plt.subplot(4, 4, i+1) plt.imshow(predictions[i, :, :, 0], cmap='gray') plt.axis('off') # tight_layout minimizes the overlap between 2 sub-plots plt.savefig('image_at_epoch_{:04d}.png'.format(epoch)) plt.show() generate_and_save_images(model, 0, random_vector_for_generation) for epoch in range(1, epochs + 1): start_time = time.time() for train_x in train_dataset: gradients, loss = compute_gradients(model, train_x) apply_gradients(optimizer, gradients, model.trainable_variables) end_time = time.time() if epoch % 1 == 0: loss = tfe.metrics.Mean() for test_x in test_dataset.make_one_shot_iterator(): loss(compute_loss(model, test_x)) elbo = -loss.result() display.clear_output(wait=False) print('Epoch: {}, Test set ELBO: {}, ' 'time elapse for current epoch {}'.format(epoch, elbo, end_time - start_time)) generate_and_save_images( model, epoch, random_vector_for_generation) """ Explanation: Training We start by iterating over the dataset During each iteration, we pass the image to the encoder to obtain a set of mean and log-variance parameters of the approximate posterior $q(z|x)$ We then apply the reparameterization trick to sample from $q(z|x)$ Finally, we pass the reparameterized samples to the decoder to obtain the logits of the generative distribution $p(x|z)$ Note: Since we use the dataset loaded by keras with 60k datapoints in the training set and 10k datapoints in the test set, our resulting ELBO on the test set is slightly higher than reported results in the literature which uses dynamic binarization of Larochelle's MNIST. Generate Images After training, it is time to generate some images We start by sampling a set of latent vectors from the unit Gaussian prior distribution $p(z)$ The generator will then convert the latent sample $z$ to logits of the observation, giving a distribution $p(x|z)$ Here we plot the probabilities of Bernoulli distributions End of explanation """ def display_image(epoch_no): return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no)) display_image(epochs) # Display images """ Explanation: Display an image using the epoch number End of explanation """ with imageio.get_writer('cvae.gif', mode='I') as writer: filenames = glob.glob('image*.png') filenames = sorted(filenames) last = -1 for i,filename in enumerate(filenames): frame = 2*(i**0.5) if round(frame) > round(last): last = frame else: continue image = imageio.imread(filename) writer.append_data(image) image = imageio.imread(filename) writer.append_data(image) # this is a hack to display the gif inside the notebook os.system('cp cvae.gif cvae.gif.png') display.Image(filename="cvae.gif.png") """ Explanation: Generate a GIF of all the saved images. End of explanation """ #from google.colab import files #files.download('cvae.gif') """ Explanation: To downlod the animation from Colab uncomment the code below: End of explanation """
lcharleux/numerical_analysis
doc/Optimisation/notebooks/Optimization_practical_work.ipynb
gpl-2.0
%load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt %matplotlib nbagg import sys, copy, os from scipy import optimize sys.path.append("truss-master") try: import truss print("Truss is correctly installed") except: print("Truss is NOT correctly installed !") """ Explanation: Practical work: optimizing a bridge structure Installation of the truss package For this session, you will need the Python package Truss that can be download here: https://github.com/lcharleux/truss/archive/master.zip Dowload it, extract the content of the archive and put it in your work directory. Once this is completed, execute the cell below to check the install is working. End of explanation """ E = 210.e9 # Young Modulus [Pa] rho = 7800. # Density [kg/m**3] A = 5.e-2 # Cross section [m**2] sigmay = 400.e6 # Yield Stress [Pa] # Model definition model = truss.core.Model() # Model definition # NODES nA = model.add_node((0.,0.), label = "A") nC = model.add_node((3.,0.), label = "C") nD = model.add_node((3.,3.), label = "D") nE = model.add_node((6.,0.), label = "E") nF = model.add_node((6.,3.), label = "F") nG = model.add_node((9.,0.), label = "G") nH = model.add_node((9.,3.), label = "H") # BOUNDARY CONDITIONS nA.block[1] = True nG.block[0] = True nH.block[0] = True # BARS AC = model.add_bar(nA, nC, modulus = E, density = rho, section = A, yield_stress = sigmay) CD = model.add_bar(nC, nD, modulus = E, density = rho, section = A, yield_stress = sigmay) AD = model.add_bar(nA, nD, modulus = E, density = rho, section = A, yield_stress = sigmay) CE = model.add_bar(nC, nE, modulus = E, density = rho, section = A, yield_stress = sigmay) DF = model.add_bar(nD, nF, modulus = E, density = rho, section = A, yield_stress = sigmay) DE = model.add_bar(nD, nE, modulus = E, density = rho, section = A, yield_stress = sigmay) EF = model.add_bar(nE, nF, modulus = E, density = rho, section = A, yield_stress = sigmay) EG = model.add_bar(nE, nG, modulus = E, density = rho, section = A, yield_stress = sigmay) FH = model.add_bar(nF, nH, modulus = E, density = rho, section = A, yield_stress = sigmay) FG = model.add_bar(nF, nG, modulus = E, density = rho, section = A, yield_stress = sigmay) GH = model.add_bar(nG, nH, modulus = E, density = rho, section = A, yield_stress = sigmay) # STRUCTURAL LOADING nG.force = np.array([0., -1.e6]) model.solve() xlim, ylim = model.bbox(deformed = False) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.set_aspect("equal") #ax.axis("off") model.draw(ax, deformed = False, field = "stress", label = True, force_scale = 1.e-6, forces = True) plt.xlim(xlim) plt.ylim(ylim) plt.grid() plt.xlabel("Axe $x$") plt.ylabel("Axe $y$") """ Explanation: A short truss tutorial is available here: http://truss.readthedocs.io/en/latest/tutorial.html Building the bridge structure In this session, we will modelled a bridge structure using truss and optimize it using various criteria. The basic structure is introduced below. It is made of steel bars and loaded with one vertical force on $G$. The bridge is symmetrical so only the left half is modelled. End of explanation """ model.data(at = "nodes") """ Explanation: Detailed results at the nodes End of explanation """ model.data(at = "bars") """ Explanation: Detailed results on the bars End of explanation """ m0 = model.mass() m0 * 1.e-3 # Mass in tons ! """ Explanation: Dead (or structural) mass End of explanation """ # Example: model.data(at = "bars").state.failure.values #... """ Explanation: Questions Question 1: Verify that the yield stress is not exceeded anywhere, do you think this structure has an optimimum weight ? You can use the state/failure data available on the whole model. End of explanation """
yjzhang/uncurl_python
notebooks/Tutorial.ipynb
mit
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import scipy.io import uncurl """ Explanation: Tutorial Let's work through an example of single-cell data analysis using Uncurl, using many of its features. For a much briefer example using the same dataset, see examples/zeisel_subset_example.py. End of explanation """ data = scipy.io.loadmat('data/GSE60361_dat.mat') """ Explanation: Loading data End of explanation """ X = data['Dat'] X.shape """ Explanation: This dataset is a subset of the data from Zeisel et al. 2015 (https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE60361), consisting of mouse brain cells. End of explanation """ genes = uncurl.max_variance_genes(X, nbins=5, frac=0.2) len(genes) """ Explanation: Here, X is a 2d numpy array containing read count data. It contains 753 cells and 19971 genes. Gene subset selection Before doing anything else, we usually select a subset of about 20% of the genes. This is done using the max_variance_genes function, which first bins the genes by their mean expression values, and for each bin, selects the highest variance genes. End of explanation """ data_subset = X[genes,:] data_subset.shape """ Explanation: Here, we divide the genes into five bins by their mean expression value, and in each bin, we select the top 20% of genes by variance. This gives us 3990 genes. End of explanation """ from uncurl import fit_dist_data fit_errors = fit_dist_data.DistFitDataset(data_subset) poiss_errors = fit_errors['poiss'] lognorm_errors = fit_errors['lognorm'] norm_errors = fit_errors['norm'] errors = np.vstack((poiss_errors, lognorm_errors, norm_errors)) print(sum(errors.argmax(0)==0)) print(sum(errors.argmax(0)==1)) print(sum(errors.argmax(0)==2)) """ Explanation: Distribution selection Now, we can try determining which distribution fits the data best using the DistFitDataset function. This is a heuristic method that returns the fit errors for the Gaussian, Poisson, and Log-Normal distributions for each gene. Based on our results, the Poisson distribution will be best for count (UMI) data, while the Log-Normal distribution will be a better fit for transformed (TPM, etc.) data. So it's okay to skip this step if you have a good sense of the data you're working with. End of explanation """ M1, W1, ll = uncurl.run_state_estimation(data_subset, 7, dist='Poiss', disp=False) M2, W2, cost = uncurl.run_state_estimation(data_subset, 7, dist='LogNorm') """ Explanation: This would indicate that the best fit distribution is the Log-Normal distribution, despite the data being UMI counts. State estimation State estimation is the heart of UNCURL. This involves probabilistic matrix factorization and returns two matrices: M, a genes by clusters matrix indicating the "archetypal" cell for each cluster, and W, a clusters by cells matrix indicating the cluster assignments of each cell. State estimation requires the number of clusters to be provided beforehand. In this case, we know that there are 7 cell types. The run_state_estimation is an interface to different state estimation methods for different distributions. This step should finish in less than a couple of minutes. End of explanation """ labels = W1.argmax(0) """ Explanation: Clustering The simplest way to do clustering is simply to take W.argmax(0). This returns the most likely assigned cluster for each cell. End of explanation """ from sklearn.manifold import TSNE from uncurl.sparse_utils import symmetric_kld tsne = TSNE(2, metric=symmetric_kld) tsne_w = tsne.fit_transform(W1.T) fig = visualize_dim_red(tsne_w.T, labels, title='TSNE(W) assigned labels', figsize=(10,6)) """ Explanation: Visualization It is recommended to run t-SNE on W, or M*W. The Euclidean distance isn't really the best distance metric for W; usually cosine distance, L1 distance, or symmetric KL divergence work better, with KL divergence usually the best. However, as a custom distance metric it tends to be rather slow. M*W can be treated basically the same as the original data, and whatever visualization methods for the original data can also be used on it. However, given that M*W is low-rank, taking the log might be necessary. End of explanation """ fig = visualize_dim_red(tsne_w.T, data['ActLabs'].flatten(), title='TSNE(W) actual labels', figsize=(10,6)) """ Explanation: Since we know the actual labels for the cell types, we can plot them here too: End of explanation """ from sklearn.decomposition import TruncatedSVD tsvd = TruncatedSVD(50) tsne = TSNE(2) mw = M1.dot(W1) mw_log = np.log1p(mw) mw_tsvd = tsvd.fit_transform(mw_log.T) mw_tsne = tsne.fit_transform(mw_tsvd) fig = visualize_dim_red(mw_tsne.T, labels, title='TSNE(MW) assigned labels', figsize=(10,6)) fig = visualize_dim_red(mw_tsne.T, data['ActLabs'].flatten(), title='TSNE(MW) actual labels', figsize=(10,6)) """ Explanation: To use M*W for visualization, we usually do some additional processing on it (as with t-SNE on the original dataset): End of explanation """ from uncurl.vis import visualize_dim_red vis_mds = uncurl.mds(M1, W1, 2) fig = visualize_dim_red(vis_mds, labels, figsize=(10,6)) """ Explanation: Another method for visualizing data is a MDS-based approach. This is fastest, but does not produce the most clean visualizations. End of explanation """
info-370/classification
knn/INFO370-KNN_Exercise.ipynb
mit
from sklearn.datasets import load_boston from sklearn.cross_validation import train_test_split from sklearn.preprocessing import scale from sklearn.neighbors import KNeighborsRegressor from sklearn.metrics import mean_squared_error from sklearn.cross_validation import KFold import matplotlib.pyplot as plt import numpy as np %matplotlib inline """ Explanation: Import modules End of explanation """ boston = load_boston() print boston.DESCR """ Explanation: Load data For this exercise, we will be using a dataset of housing prices in Boston during the 1970s. Python's super-awesome sklearn package already has the data we need to get started. Below is the command to load the data. The data is stored as a dictionary. The 'DESCR' is a description of the data and the command for printing it is below. Note all the features we have to work with. From the dictionary, we need the data and the target variable (in this case, housing price). Store these as variables named "data" and "price", respectively. Once you have these, print their shapes to see all checks out with the DESCR. End of explanation """
GoogleCloudPlatform/vertex-ai-samples
notebooks/community/sdk/sdk_automl_image_object_detection_batch.ipynb
apache-2.0
import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG """ Explanation: Vertex SDK: AutoML training image object detection model for batch prediction <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/tree/master/notebooks/official/automl/sdk_automl_image_object_detection_batch.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab </a> </td> <td> <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/master/notebooks/official/automl/sdk_automl_image_object_detection_batch.ipynb"> <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo"> View on GitHub </a> </td> <td> <a href="https://console.cloud.google.com/ai/platform/notebooks/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/master/notebooks/official/automl/sdk_automl_image_object_detection_batch.ipynb"> Open in Google Cloud Notebooks </a> </td> </table> <br/><br/><br/> Overview This tutorial demonstrates how to use the Vertex SDK to create image object detection models and do batch prediction using a Google Cloud AutoML model. Dataset The dataset used for this tutorial is the Salads category of the OpenImages dataset from TensorFlow Datasets. This dataset does not require any feature engineering. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the bounding box locations and corresponding type of salad items in an image from a class of five items: salad, seafood, tomato, baked goods, or cheese. Objective In this tutorial, you create an AutoML image object detection model from a Python script, and then do a batch prediction using the Vertex SDK. You can alternatively create and deploy models using the gcloud command-line tool or online using the Cloud Console. The steps performed include: Create a Vertex Dataset resource. Train the model. View the model evaluation. Make a batch prediction. There is one key difference between using batch prediction and using online prediction: Prediction Service: Does an on-demand prediction for the entire set of instances (i.e., one or more data items) and returns the results in real-time. Batch Prediction Service: Does a queued (batch) prediction for the entire set of instances in the background and stores the results in a Cloud Storage bucket when ready. Costs This tutorial uses billable components of Google Cloud: Vertex AI Cloud Storage Learn about Vertex AI pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage. Set up your local development environment If you are using Colab or Google Cloud Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step. Otherwise, make sure your environment meets this notebook's requirements. You need the following: The Cloud Storage SDK Git Python 3 virtualenv Jupyter notebook running in a virtual environment with Python 3 The Cloud Storage guide to Setting up a Python development environment and the Jupyter installation guide provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions: Install and initialize the SDK. Install Python 3. Install virtualenv and create a virtual environment that uses Python 3. Activate the virtual environment. To install Jupyter, run pip3 install jupyter on the command-line in a terminal shell. To launch Jupyter, run jupyter notebook on the command-line in a terminal shell. Open this notebook in the Jupyter Notebook Dashboard. Installation Install the latest version of Vertex SDK for Python. End of explanation """ ! pip3 install -U google-cloud-storage $USER_FLAG if os.environ["IS_TESTING"]: ! pip3 install --upgrade tensorflow $USER_FLAG """ Explanation: Install the latest GA version of google-cloud-storage library as well. End of explanation """ import os if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) """ Explanation: Restart the kernel Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages. End of explanation """ PROJECT_ID = "[your-project-id]" # @param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:", PROJECT_ID) ! gcloud config set project $PROJECT_ID """ Explanation: Before you begin GPU runtime This tutorial does not require a GPU runtime. Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage. If you are running this notebook locally, you will need to install the Cloud SDK. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook. Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $. End of explanation """ REGION = "us-central1" # @param {type: "string"} """ Explanation: Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you. Americas: us-central1 Europe: europe-west4 Asia Pacific: asia-east1 You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services. Learn more about Vertex AI regions End of explanation """ from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") """ Explanation: Timestamp If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial. End of explanation """ # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. import os import sys # If on Google Cloud Notebook, then don't execute this code if not os.path.exists("/opt/deeplearning/metadata/env_version"): if "google.colab" in sys.modules: from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this notebook locally, replace the string below with the # path to your service account key and run this cell to authenticate your GCP # account. elif not os.getenv("IS_TESTING"): %env GOOGLE_APPLICATION_CREDENTIALS '' """ Explanation: Authenticate your Google Cloud account If you are using Google Cloud Notebooks, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, follow these steps: In the Cloud Console, go to the Create service account key page. Click Create service account. In the Service account name field, enter a name, and click Create. In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex" into the filter box, and select Vertex Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin. Click Create. A JSON file that contains your key downloads to your local environment. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell. End of explanation """ BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"} if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]": BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP """ Explanation: Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions. Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization. End of explanation """ ! gsutil mb -l $REGION $BUCKET_NAME """ Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket. End of explanation """ ! gsutil ls -al $BUCKET_NAME """ Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents: End of explanation """ import google.cloud.aiplatform as aip """ Explanation: Set up variables Next, set up some variables used throughout the tutorial. Import libraries and define constants End of explanation """ aip.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME) """ Explanation: Initialize Vertex SDK for Python Initialize the Vertex SDK for Python for your project and corresponding bucket. End of explanation """ IMPORT_FILE = "gs://cloud-samples-data/vision/salads.csv" """ Explanation: Tutorial Now you are ready to start creating your own AutoML image object detection model. Location of Cloud Storage training data. Now set the variable IMPORT_FILE to the location of the CSV index file in Cloud Storage. End of explanation """ if "IMPORT_FILES" in globals(): FILE = IMPORT_FILES[0] else: FILE = IMPORT_FILE count = ! gsutil cat $FILE | wc -l print("Number of Examples", int(count[0])) print("First 10 rows") ! gsutil cat $FILE | head """ Explanation: Quick peek at your data This tutorial uses a version of the Salads dataset that is stored in a public Cloud Storage bucket, using a CSV index file. Start by doing a quick peek at the data. You count the number of examples by counting the number of rows in the CSV index file (wc -l) and then peek at the first few rows. End of explanation """ dataset = aip.ImageDataset.create( display_name="Salads" + "_" + TIMESTAMP, gcs_source=[IMPORT_FILE], import_schema_uri=aip.schema.dataset.ioformat.image.bounding_box, ) print(dataset.resource_name) """ Explanation: Create the Dataset Next, create the Dataset resource using the create method for the ImageDataset class, which takes the following parameters: display_name: The human readable name for the Dataset resource. gcs_source: A list of one or more dataset index files to import the data items into the Dataset resource. import_schema_uri: The data labeling schema for the data items. This operation may take several minutes. End of explanation """ dag = aip.AutoMLImageTrainingJob( display_name="salads_" + TIMESTAMP, prediction_type="object_detection", multi_label=False, model_type="CLOUD", base_model=None, ) print(dag) """ Explanation: Create and run training pipeline To train an AutoML model, you perform two steps: 1) create a training pipeline, and 2) run the pipeline. Create training pipeline An AutoML training pipeline is created with the AutoMLImageTrainingJob class, with the following parameters: display_name: The human readable name for the TrainingJob resource. prediction_type: The type task to train the model for. classification: An image classification model. object_detection: An image object detection model. multi_label: If a classification task, whether single (False) or multi-labeled (True). model_type: The type of model for deployment. CLOUD: Deployment on Google Cloud CLOUD_HIGH_ACCURACY_1: Optimized for accuracy over latency for deployment on Google Cloud. CLOUD_LOW_LATENCY_: Optimized for latency over accuracy for deployment on Google Cloud. MOBILE_TF_VERSATILE_1: Deployment on an edge device. MOBILE_TF_HIGH_ACCURACY_1:Optimized for accuracy over latency for deployment on an edge device. MOBILE_TF_LOW_LATENCY_1: Optimized for latency over accuracy for deployment on an edge device. base_model: (optional) Transfer learning from existing Model resource -- supported for image classification only. The instantiated object is the DAG (directed acyclic graph) for the training job. End of explanation """ model = dag.run( dataset=dataset, model_display_name="salads_" + TIMESTAMP, training_fraction_split=0.8, validation_fraction_split=0.1, test_fraction_split=0.1, budget_milli_node_hours=20000, disable_early_stopping=False, ) """ Explanation: Run the training pipeline Next, you run the DAG to start the training job by invoking the method run, with the following parameters: dataset: The Dataset resource to train the model. model_display_name: The human readable name for the trained model. training_fraction_split: The percentage of the dataset to use for training. test_fraction_split: The percentage of the dataset to use for test (holdout data). validation_fraction_split: The percentage of the dataset to use for validation. budget_milli_node_hours: (optional) Maximum training time specified in unit of millihours (1000 = hour). disable_early_stopping: If True, training maybe completed before using the entire budget if the service believes it cannot further improve on the model objective measurements. The run method when completed returns the Model resource. The execution of the training pipeline will take upto 60 minutes. End of explanation """ # Get model resource ID models = aip.Model.list(filter="display_name=salads_" + TIMESTAMP) # Get a reference to the Model Service client client_options = {"api_endpoint": f"{REGION}-aiplatform.googleapis.com"} model_service_client = aip.gapic.ModelServiceClient(client_options=client_options) model_evaluations = model_service_client.list_model_evaluations( parent=models[0].resource_name ) model_evaluation = list(model_evaluations)[0] print(model_evaluation) """ Explanation: Review model evaluation scores After your model has finished training, you can review the evaluation scores for it. First, you need to get a reference to the new model. As with datasets, you can either use the reference to the model variable you created when you deployed the model or you can list all of the models in your project. End of explanation """ test_items = !gsutil cat $IMPORT_FILE | head -n2 cols_1 = str(test_items[0]).split(",") cols_2 = str(test_items[1]).split(",") if len(cols_1) == 11: test_item_1 = str(cols_1[1]) test_label_1 = str(cols_1[2]) test_item_2 = str(cols_2[1]) test_label_2 = str(cols_2[2]) else: test_item_1 = str(cols_1[0]) test_label_1 = str(cols_1[1]) test_item_2 = str(cols_2[0]) test_label_2 = str(cols_2[1]) print(test_item_1, test_label_1) print(test_item_2, test_label_2) """ Explanation: Send a batch prediction request Send a batch prediction to your deployed model. Get test item(s) Now do a batch prediction to your Vertex model. You will use arbitrary examples out of the dataset as a test items. Don't be concerned that the examples were likely used in training the model -- we just want to demonstrate how to make a prediction. End of explanation """ file_1 = test_item_1.split("/")[-1] file_2 = test_item_2.split("/")[-1] ! gsutil cp $test_item_1 $BUCKET_NAME/$file_1 ! gsutil cp $test_item_2 $BUCKET_NAME/$file_2 test_item_1 = BUCKET_NAME + "/" + file_1 test_item_2 = BUCKET_NAME + "/" + file_2 """ Explanation: Copy test item(s) For the batch prediction, copy the test items over to your Cloud Storage bucket. End of explanation """ import json import tensorflow as tf gcs_input_uri = BUCKET_NAME + "/test.jsonl" with tf.io.gfile.GFile(gcs_input_uri, "w") as f: data = {"content": test_item_1, "mime_type": "image/jpeg"} f.write(json.dumps(data) + "\n") data = {"content": test_item_2, "mime_type": "image/jpeg"} f.write(json.dumps(data) + "\n") print(gcs_input_uri) ! gsutil cat $gcs_input_uri """ Explanation: Make the batch input file Now make a batch input file, which you will store in your local Cloud Storage bucket. The batch input file can be either CSV or JSONL. You will use JSONL in this tutorial. For JSONL file, you make one dictionary entry per line for each data item (instance). The dictionary contains the key/value pairs: content: The Cloud Storage path to the image. mime_type: The content type. In our example, it is a jpeg file. For example: {'content': '[your-bucket]/file1.jpg', 'mime_type': 'jpeg'} End of explanation """ batch_predict_job = model.batch_predict( job_display_name="salads_" + TIMESTAMP, gcs_source=gcs_input_uri, gcs_destination_prefix=BUCKET_NAME, sync=False, ) print(batch_predict_job) """ Explanation: Make the batch prediction request Now that your Model resource is trained, you can make a batch prediction by invoking the batch_predict() method, with the following parameters: job_display_name: The human readable name for the batch prediction job. gcs_source: A list of one or more batch request input files. gcs_destination_prefix: The Cloud Storage location for storing the batch prediction resuls. sync: If set to True, the call will block while waiting for the asynchronous batch job to complete. End of explanation """ batch_predict_job.wait() """ Explanation: Wait for completion of batch prediction job Next, wait for the batch job to complete. Alternatively, one can set the parameter sync to True in the batch_predict() method to block until the batch prediction job is completed. End of explanation """ import json import tensorflow as tf bp_iter_outputs = batch_predict_job.iter_outputs() prediction_results = list() for blob in bp_iter_outputs: if blob.name.split("/")[-1].startswith("prediction"): prediction_results.append(blob.name) tags = list() for prediction_result in prediction_results: gfile_name = f"gs://{bp_iter_outputs.bucket.name}/{prediction_result}" with tf.io.gfile.GFile(name=gfile_name, mode="r") as gfile: for line in gfile.readlines(): line = json.loads(line) print(line) break """ Explanation: Get the predictions Next, get the results from the completed batch prediction job. The results are written to the Cloud Storage output bucket you specified in the batch prediction request. You call the method iter_outputs() to get a list of each Cloud Storage file generated with the results. Each file contains one or more prediction requests in a JSON format: content: The prediction request. prediction: The prediction response. ids: The internal assigned unique identifiers for each prediction request. displayNames: The class names for each class label. bboxes: The bounding box of each detected object. End of explanation """ delete_all = True if delete_all: # Delete the dataset using the Vertex dataset object try: if "dataset" in globals(): dataset.delete() except Exception as e: print(e) # Delete the model using the Vertex model object try: if "model" in globals(): model.delete() except Exception as e: print(e) # Delete the endpoint using the Vertex endpoint object try: if "endpoint" in globals(): endpoint.delete() except Exception as e: print(e) # Delete the AutoML or Pipeline trainig job try: if "dag" in globals(): dag.delete() except Exception as e: print(e) # Delete the custom trainig job try: if "job" in globals(): job.delete() except Exception as e: print(e) # Delete the batch prediction job using the Vertex batch prediction object try: if "batch_predict_job" in globals(): batch_predict_job.delete() except Exception as e: print(e) # Delete the hyperparameter tuning job using the Vertex hyperparameter tuning object try: if "hpt_job" in globals(): hpt_job.delete() except Exception as e: print(e) if "BUCKET_NAME" in globals(): ! gsutil rm -r $BUCKET_NAME """ Explanation: Cleaning up To clean up all Google Cloud resources used in this project, you can delete the Google Cloud project you used for the tutorial. Otherwise, you can delete the individual resources you created in this tutorial: Dataset Pipeline Model Endpoint AutoML Training Job Batch Job Custom Job Hyperparameter Tuning Job Cloud Storage Bucket End of explanation """
xpharry/Udacity-DLFoudation
tutorials/gan_mnist/Intro_to_GANs_Solution.ipynb
mit
%matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') """ Explanation: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten digits! GANs were first reported on in 2014 from Ian Goodfellow and others in Yoshua Bengio's lab. Since then, GANs have exploded in popularity. Here are a few examples to check out: Pix2Pix CycleGAN A whole list The idea behind GANs is that you have two networks, a generator $G$ and a discriminator $D$, competing against each other. The generator makes fake data to pass to the discriminator. The discriminator also sees real data and predicts if the data it's received is real or fake. The generator is trained to fool the discriminator, it wants to output data that looks as close as possible to real data. And the discriminator is trained to figure out which data is real and which is fake. What ends up happening is that the generator learns to make data that is indistiguishable from real data to the discriminator. The general structure of a GAN is shown in the diagram above, using MNIST images as data. The latent sample is a random vector the generator uses to contruct it's fake images. As the generator learns through training, it figures out how to map these random vectors to recognizable images that can foold the discriminator. The output of the discriminator is a sigmoid function, where 0 indicates a fake image and 1 indicates an real image. If you're interested only in generating new images, you can throw out the discriminator after training. Now, let's see how we build this thing in TensorFlow. End of explanation """ def model_inputs(real_dim, z_dim): inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real') inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z') return inputs_real, inputs_z """ Explanation: Model Inputs First we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input inputs_real and the generator input inputs_z. We'll assign them the appropriate sizes for each of the networks. End of explanation """ def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01): with tf.variable_scope('generator', reuse=reuse): # Hidden layer h1 = tf.layers.dense(z, n_units, activation=None) # Leaky ReLU h1 = tf.maximum(alpha * h1, h1) # Logits and tanh output logits = tf.layers.dense(h1, out_dim) out = tf.tanh(logits) return out, logits """ Explanation: Generator network Here we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values. Variable Scope Here we need to use tf.variable_scope for two reasons. Firstly, we're going to make sure all the variable names start with generator. Similarly, we'll prepend discriminator to the discriminator variables. This will help out later when we're training the separate networks. We could just use tf.name_scope to set the names, but we also want to reuse these networks with different inputs. For the generator, we're going to train it, but also sample from it as we're training and after training. The discriminator will need to share variables between the fake and real input images. So, we can use the reuse keyword for tf.variable_scope to tell TensorFlow to reuse the variables instead of creating new ones if we build the graph again. To use tf.variable_scope, you use a with statement: python with tf.variable_scope('scope_name', reuse=False): # code here Here's more from the TensorFlow documentation to get another look at using tf.variable_scope. Leaky ReLU TensorFlow doesn't provide an operation for leaky ReLUs, so we'll need to make one . For this you can use take the outputs from a linear fully connected layer and pass them to tf.maximum. Typically, a parameter alpha sets the magnitude of the output for negative values. So, the output for negative input (x) values is alpha*x, and the output for positive x is x: $$ f(x) = max(\alpha * x, x) $$ Tanh Output The generator has been found to perform the best with $tanh$ for the generator output. This means that we'll have to rescale the MNIST images to be between -1 and 1, instead of 0 and 1. Along with the $tanh$ output, we also need to return the logits for use in calculating the loss with tf.nn.sigmoid_cross_entropy_with_logits. End of explanation """ def discriminator(x, n_units=128, reuse=False, alpha=0.01): with tf.variable_scope('discriminator', reuse=reuse): # Hidden layer h1 = tf.layers.dense(x, n_units, activation=None) # Leaky ReLU h1 = tf.maximum(alpha * h1, h1) logits = tf.layers.dense(h1, 1, activation=None) out = tf.sigmoid(logits) return out, logits """ Explanation: Discriminator The discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer. End of explanation """ # Size of input image to discriminator input_size = 784 # Size of latent vector to generator z_size = 100 # Sizes of hidden layers in generator and discriminator g_hidden_size = 128 d_hidden_size = 128 # Leak factor for leaky ReLU alpha = 0.01 # Smoothing smooth = 0.1 """ Explanation: Hyperparameters End of explanation """ tf.reset_default_graph() # Create our input placeholders input_real, input_z = model_inputs(input_size, z_size) # Build the model g_model, g_logits = generator(input_z, input_size) # g_model is the generator output d_model_real, d_logits_real = discriminator(input_real) d_model_fake, d_logits_fake = discriminator(g_model, reuse=True) """ Explanation: Build network Now we're building the network from the functions defined above. First is to get our inputs, input_real, input_z from model_inputs using the sizes of the input and z. Then, we'll create the generator, generator(input_z, input_size). This builds the generator with the appropriate input and output sizes. Then the discriminators. We'll build two of them, one for real data and one for fake data. Since we want the weights to be the same for both real and fake data, we need to reuse the variables. For the fake data, we're getting it from the generator as g_model. So the real data discriminator is discriminator(input_real) while the fake discriminator is discriminator(g_model, reuse=True). End of explanation """ # Calculate losses d_loss_real = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_logits_real) * (1 - smooth))) d_loss_fake = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_logits_real))) d_loss = d_loss_real + d_loss_fake g_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_logits_fake))) """ Explanation: Discriminator and Generator Losses Now we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropys, which we can get with tf.nn.sigmoid_cross_entropy_with_logits. We'll also wrap that in tf.reduce_mean to get the mean for all the images in the batch. So the losses will look something like python tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels)) For the real image logits, we'll use d_logits_real which we got from the discriminator in the cell above. For the labels, we want them to be all ones, since these are all real images. To help the discriminator generalize better, the labels are reduced a bit from 1.0 to 0.9, for example, using the parameter smooth. This is known as label smoothing, typically used with classifiers to improve performance. In TensorFlow, it looks something like labels = tf.ones_like(tensor) * (1 - smooth) The discriminator loss for the fake data is similar. The logits are d_logits_fake, which we got from passing the generator output to the discriminator. These fake logits are used with labels of all zeros. Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that. Finally, the generator losses are using d_logits_fake, the fake image logits. But, now the labels are all ones. The generator is trying to fool the discriminator, so it wants to discriminator to output ones for fake images. End of explanation """ # Optimizers learning_rate = 0.002 # Get the trainable_variables, split into G and D parts t_vars = tf.trainable_variables() g_vars = [var for var in t_vars if var.name.startswith('generator')] d_vars = [var for var in t_vars if var.name.startswith('discriminator')] d_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list=d_vars) g_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list=g_vars) """ Explanation: Optimizers We want to update the generator and discriminator variables separately. So we need to get the variables for each part build optimizers for the two parts. To get all the trainable variables, we use tf.trainable_variables(). This creates a list of all the variables we've defined in our graph. For the generator optimizer, we only want to generator variables. Our past selves were nice and used a variable scope to start all of our generator variable names with generator. So, we just need to iterate through the list from tf.trainable_variables() and keep variables to start with generator. Each variable object has an attribute name which holds the name of the variable as a string (var.name == 'weights_0' for instance). We can do something similar with the discriminator. All the variables in the discriminator start with discriminator. Then, in the optimizer we pass the variable lists to var_list in the minimize method. This tells the optimizer to only update the listed variables. Something like tf.train.AdamOptimizer().minimize(loss, var_list=var_list) will only train the variables in var_list. End of explanation """ !mkdir checkpoints batch_size = 100 epochs = 100 samples = [] losses = [] # Only save generator variables saver = tf.train.Saver(var_list=g_vars) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for e in range(epochs): for ii in range(mnist.train.num_examples//batch_size): batch = mnist.train.next_batch(batch_size) # Get images, reshape and rescale to pass to D batch_images = batch[0].reshape((batch_size, 784)) batch_images = batch_images*2 - 1 # Sample random noise for G batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size)) # Run optimizers _ = sess.run(d_train_opt, feed_dict={input_real: batch_images, input_z: batch_z}) _ = sess.run(g_train_opt, feed_dict={input_z: batch_z}) # At the end of each epoch, get the losses and print them out train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images}) train_loss_g = g_loss.eval({input_z: batch_z}) print("Epoch {}/{}...".format(e+1, epochs), "Discriminator Loss: {:.4f}...".format(train_loss_d), "Generator Loss: {:.4f}".format(train_loss_g)) # Save losses to view after training losses.append((train_loss_d, train_loss_g)) # Sample from generator as we're training for viewing afterwards sample_z = np.random.uniform(-1, 1, size=(16, z_size)) gen_samples, _ = sess.run( generator(input_z, input_size, reuse=True), feed_dict={input_z: sample_z}) samples.append(gen_samples) saver.save(sess, './checkpoints/generator.ckpt') # Save training generator samples with open('train_samples.pkl', 'wb') as f: pkl.dump(samples, f) """ Explanation: Training End of explanation """ fig, ax = plt.subplots() losses = np.array(losses) plt.plot(losses.T[0], label='Discriminator') plt.plot(losses.T[1], label='Generator') plt.title("Training Losses") plt.legend() """ Explanation: Training loss Here we'll check out the training losses for the generator and discriminator. End of explanation """ def view_samples(epoch, samples): fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True) for ax, img in zip(axes.flatten(), samples[epoch]): ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) im = ax.imshow(img.reshape((28,28)), cmap='Greys_r') return fig, axes # Load samples from generator taken while training with open('train_samples.pkl', 'rb') as f: samples = pkl.load(f) """ Explanation: Generator samples from training Here we can view samples of images from the generator. First we'll look at images taken while training. End of explanation """ _ = view_samples(-1, samples) """ Explanation: These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 1, 7, 3, 2. Since this is just a sample, it isn't representative of the full range of images this generator can make. End of explanation """ rows, cols = 10, 6 fig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True) for sample, ax_row in zip(samples[::int(len(samples)/rows)], axes): for img, ax in zip(sample[::int(len(sample)/cols)], ax_row): ax.imshow(img.reshape((28,28)), cmap='Greys_r') ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) """ Explanation: Below I'm showing the generated images as the network was training, every 10 epochs. With bonus optical illusion! End of explanation """ saver = tf.train.Saver(var_list=g_vars) with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) sample_z = np.random.uniform(-1, 1, size=(16, z_size)) gen_samples, _ = sess.run( generator(input_z, input_size, reuse=True), feed_dict={input_z: sample_z}) _ = view_samples(0, [gen_samples]) """ Explanation: It starts out as all noise. Then it learns to make only the center white and the rest black. You can start to see some number like structures appear out of the noise like 1s and 9s. Sampling from the generator We can also get completely new images from the generator by using the checkpoint we saved after training. We just need to pass in a new latent vector $z$ and we'll get new samples! End of explanation """
kungsik/text_fabric_sample
tutorial_1.ipynb
gpl-3.0
from tf.fabric import Fabric """ Explanation: Text-Fabric Api 활용 예제 본 파일은 Text-Fabric Api를 활용하여 성서 검색 프로그램을 만들기 위한 시범 예제 페이지입니다. - 라이브러리 불러오기 End of explanation """ ETCBC = 'hebrew/etcbc4c' PHONO = 'hebrew/phono' TF = Fabric( modules=[ETCBC, PHONO], silent=False ) """ Explanation: - 데이터베이스 파일 로드 etcbc4c는 히브리어 텍스트, phono는 음역 텍스트 End of explanation """ api = TF.load(''' sp lex voc_utf8 g_word trailer qere qere_trailer language freq_lex gloss mother ''') api.makeAvailableIn(globals()) """ Explanation: - api 목록 로드. 여기에는 다양한 형태의 데이터를 로드함. 그리고 api 활성화 End of explanation """ verseNode = T.nodeFromSection(('Genesis', 1, 1)) print(verseNode) """ Explanation: 1. 창세기1:1 텍스트 뽑아오기 T.nodeFromSection: 책,장,절 데이터를 입력하면 해당하는 node를 가져옴. 아래의 예는 창세기 1:1의 node를 불러오는 예임. End of explanation """ print(T.text(L.d(verseNode, otype='word'))) """ Explanation: 이 verse의 node를 이용하여 이 node에 포함되어 있는 word 단위의 node를 가져와서 텍스트(T.text) api를 이용하여 구절을 출력할 수 있다. L.d()는 verse node의 하위 단위를 선택할 수 있다. 그 하위 단위 가운데 word를 선택한다. T.text()는 해당 node를 텍스트로 출력하는 기능을 한다. End of explanation """ book = 'Genesis' chp = 1 chpNode = T.nodeFromSection((book, chp)) print(chpNode) """ Explanation: 2. 창세기 1장 텍스트 뽑아오기 창세기 1장을 입력하면 아래와 같은 node를 얻을 수 있다. End of explanation """ print(T.text(L.d(chpNode, otype='word'))) verseNum = T.sectionFromNode(verseNode) print('{} {}'.format(verseNum[2], T.text(L.d(verseNode, otype='word')))) """ Explanation: 위 1장의 node의 하위 단위인 word를 선택하여 출력하면 창세기 1장 전체가 출력된다. End of explanation """ verseNodes = L.d(chpNode, otype='verse') print(verseNodes) for v in verseNodes: verseNum = T.sectionFromNode(v) verseTxt = T.text(L.d(v, otype='word')) print('{} {} \n'.format(verseNum[2], verseTxt)) """ Explanation: 이제까지의 내용을 응용해서 각 verse에 절 수를 붙일 수 있다. 챕터 노드의 하위에 있는 verse 노드를 모두 선택한다(tuple 형식으로 리턴) T.sectionFromNode를 이용하여 구절 번호를 불러온다. (Genesis, 1, 1) 형식으로 리턴 각 절 단위의 단어들을 출력한다. End of explanation """
cgpotts/cs224u
feature_attribution.ipynb
apache-2.0
__author__ = "Christopher Potts" __version__ = "CS224u, Stanford, Spring 2022" """ Explanation: Feature attribution End of explanation """ !pip install captum """ Explanation: Contents Overview InputXGradients Selectivity examples Simple feed-forward classifier example Bag-of-words classifier for the SST BERT example Overview This notebook is an experimental extension of the CS224u course code. It focuses on the Integrated Gradients method for feature attribution, with comparisons to the "inputs $\times$ gradients" method. To run the notebook, first install the Captum library: End of explanation """ import torch def grad_x_input(model, X, targets=None): """Implementation using PyTorch directly.""" X.requires_grad = True y = model(X) y = y if targets is None else y[list(range(len(y))), targets] (grads, ) = torch.autograd.grad(y.unbind(), X) return grads * X from captum.attr import InputXGradient def captum_grad_x_input(model, X, target): """Captum-based implementation.""" X.requires_grad = True amod = InputXGradient(model) return amod.attribute(X, target=target) """ Explanation: This is not currently a required installation (but it will be in future years). InputXGradients For both implementations, the forward method of model is used. X is an (m x n) tensor of attributions. Use targets=None for models with scalar outputs, else supply a LongTensor giving a label for each example. End of explanation """ import numpy as np import torch import torch.nn as nn from captum.attr import IntegratedGradients from captum.attr import InputXGradient class SelectivityAssessor(nn.Module): """Model used by Sundararajan et al, section 2.1 to show that input * gradients violates their selectivity axiom. """ def __init__(self): super().__init__() self.relu = nn.ReLU() def forward(self, X): return 1.0 - self.relu(1.0 - X) sel_mod = SelectivityAssessor() """ Explanation: Selectivity examples End of explanation """ X_sel = torch.FloatTensor([[0.0], [2.0]]) """ Explanation: Simple inputs with just one feature: End of explanation """ sel_mod(X_sel) """ Explanation: The outputs for our two examples differ: End of explanation """ captum_grad_x_input(sel_mod, X_sel, target=None) """ Explanation: However, InputXGradient assigns the same importance to the feature across the two examples, violating selectivity: End of explanation """ ig_sel = IntegratedGradients(sel_mod) sel_baseline = torch.FloatTensor([[0.0]]) ig_sel.attribute(X_sel, sel_baseline) """ Explanation: Integrated gradients addresses the problem by averaging gradients across all interpolated representations between the baseline and the actual input: End of explanation """ def ig_reference_implementation(model, x, base, m=50): vals = [] for k in range(m): # Interpolated representation: xx = (base + (k/m)) * (x - base) # Gradient for the interpolated example: xx.requires_grad = True y = model(xx) (grads, ) = torch.autograd.grad(y.unbind(), xx) vals.append(grads) return (1 / m) * torch.cat(vals).sum(axis=0) * (x - base) ig_reference_implementation(sel_mod, torch.FloatTensor([[2.0]]), sel_baseline) """ Explanation: A toy implementation to help bring out what is happening: End of explanation """ from captum.attr import IntegratedGradients from sklearn.datasets import make_classification from sklearn.feature_selection import mutual_info_classif from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split import torch from torch_shallow_neural_classifier import TorchShallowNeuralClassifier X_cls, y_cls = make_classification( n_samples=5000, n_classes=3, n_features=5, n_informative=3, n_redundant=0, random_state=42) """ Explanation: Simple feed-forward classifier example End of explanation """ mutual_info_classif(X_cls, y_cls) X_cls_train, X_cls_test, y_cls_train, y_cls_test = train_test_split(X_cls, y_cls) classifier = TorchShallowNeuralClassifier() _ = classifier.fit(X_cls_train, y_cls_train) cls_preds = classifier.predict(X_cls_test) accuracy_score(y_cls_test, cls_preds) classifier_ig = IntegratedGradients(classifier.model) classifier_baseline = torch.zeros(1, X_cls_train.shape[1]) """ Explanation: The classification problem has two uninformative features: End of explanation """ classifier_attrs = classifier_ig.attribute( torch.FloatTensor(X_cls_test), classifier_baseline, target=torch.LongTensor(y_cls_test)) """ Explanation: Integrated gradients with respect to the actual labels: End of explanation """ classifier_attrs.mean(axis=0) """ Explanation: Average attribution is low for the two uninformative features: End of explanation """ from collections import Counter from captum.attr import IntegratedGradients from nltk.corpus import stopwords from operator import itemgetter import os from sklearn.metrics import classification_report import torch from torch_shallow_neural_classifier import TorchShallowNeuralClassifier import sst SST_HOME = os.path.join("data", "sentiment") """ Explanation: Bag-of-words classifier for the SST End of explanation """ stopwords = set(stopwords.words('english')) def phi(text): return Counter([w for w in text.lower().split() if w not in stopwords]) def fit_mlp(X, y): mod = TorchShallowNeuralClassifier(early_stopping=True) mod.fit(X, y) return mod experiment = sst.experiment( sst.train_reader(SST_HOME), phi, fit_mlp, sst.dev_reader(SST_HOME)) """ Explanation: Bag-of-word featurization with stopword removal to make this a little easier to study: End of explanation """ sst_classifier = experiment['model'] """ Explanation: Trained model: End of explanation """ sst_classifier.classes_ y_sst_test = [sst_classifier.classes_.index(label) for label in experiment['assess_datasets'][0]['y']] sst_preds = [sst_classifier.classes_.index(label) for label in experiment['predictions'][0]] """ Explanation: Captum needs to have labels as indices rather than strings: End of explanation """ X_sst_test = experiment['assess_datasets'][0]['X'] """ Explanation: Our featurized test set: End of explanation """ fnames = experiment['train_dataset']['vectorizer'].get_feature_names() """ Explanation: Feature names to help with analyses: End of explanation """ sst_ig = IntegratedGradients(sst_classifier.model) """ Explanation: Integrated gradients: End of explanation """ sst_baseline = torch.zeros(1, experiment['train_dataset']['X'].shape[1]) """ Explanation: All-0s baseline: End of explanation """ sst_attrs = sst_ig.attribute( torch.FloatTensor(X_sst_test), sst_baseline, target=torch.LongTensor(sst_preds)) """ Explanation: Attributions with respect to the model's predictions: End of explanation """ def error_analysis(gold=1, predicted=2): err_ind = [i for i, (g, p) in enumerate(zip(y_sst_test, sst_preds)) if g == gold and p == predicted] attr_lookup = create_attr_lookup(sst_attrs[err_ind]) return attr_lookup, err_ind def create_attr_lookup(attrs): mu = attrs.mean(axis=0).detach().numpy() return sorted(zip(fnames, mu), key=itemgetter(1), reverse=True) sst_attrs_lookup, sst_err_ind = error_analysis(gold=1, predicted=2) sst_attrs_lookup[: 5] """ Explanation: Helper functions for error analysis: End of explanation """ ex_ind = sst_err_ind[0] experiment['assess_datasets'][0]['raw_examples'][ex_ind] ex_attr_lookup = create_attr_lookup(sst_attrs[ex_ind:ex_ind+1]) [(f, a) for f, a in ex_attr_lookup if a != 0] """ Explanation: Error analysis for a specific example: End of explanation """ import torch import torch.nn.functional as F from transformers import AutoModelForSequenceClassification, AutoTokenizer from captum.attr import LayerIntegratedGradients from captum.attr import visualization as viz hf_weights_name = 'cardiffnlp/twitter-roberta-base-sentiment' hf_tokenizer = AutoTokenizer.from_pretrained(hf_weights_name) hf_model = AutoModelForSequenceClassification.from_pretrained(hf_weights_name) def hf_predict_one_proba(text): input_ids = hf_tokenizer.encode( text, add_special_tokens=True, return_tensors='pt') hf_model.eval() with torch.no_grad(): logits = hf_model(input_ids)[0] preds = F.softmax(logits, dim=1) hf_model.train() return preds.squeeze(0) def hf_ig_encodings(text): pad_id = hf_tokenizer.pad_token_id cls_id = hf_tokenizer.cls_token_id sep_id = hf_tokenizer.sep_token_id input_ids = hf_tokenizer.encode(text, add_special_tokens=False) base_ids = [pad_id] * len(input_ids) input_ids = [cls_id] + input_ids + [sep_id] base_ids = [cls_id] + base_ids + [sep_id] return torch.LongTensor([input_ids]), torch.LongTensor([base_ids]) def hf_ig_analyses(text2class): data = [] for text, true_class in text2class.items(): score_vis = hf_ig_analysis_one(text, true_class) data.append(score_vis) viz.visualize_text(data) def hf_ig_analysis_one(text, true_class): # Option to look at different layers: # layer = model.roberta.encoder.layer[0] # layer = model.roberta.embeddings.word_embeddings layer = hf_model.roberta.embeddings def ig_forward(inputs): return hf_model(inputs).logits ig = LayerIntegratedGradients(ig_forward, layer) input_ids, base_ids = hf_ig_encodings(text) attrs, delta = ig.attribute( input_ids, base_ids, target=true_class, return_convergence_delta=True) # Summarize and z-score normalize the attributions # for each representation in `layer`: scores = attrs.sum(dim=-1).squeeze(0) scores = (scores - scores.mean()) / scores.norm() # Intuitive tokens to help with analysis: raw_input = hf_tokenizer.convert_ids_to_tokens(input_ids.tolist()[0]) # RoBERTa-specific clean-up: raw_input = [x.strip("Ġ") for x in raw_input] # Predictions for comparisons: pred_probs = hf_predict_one_proba(text) pred_class = pred_probs.argmax() score_vis = viz.VisualizationDataRecord( word_attributions=scores, pred_prob=pred_probs.max(), pred_class=pred_class, true_class=true_class, attr_class=None, attr_score=attrs.sum(), raw_input_ids=raw_input, convergence_score=delta) return score_vis score_vis = hf_ig_analyses({ "They said it would be great, and they were right.": 2, "They said it would be great, and they were wrong.": 0, "They were right to say it would be great.": 2, "They were wrong to say it would be great.": 0, "They said it would be stellar, and they were correct.": 2, "They said it would be stellar, and they were incorrect.": 0}) """ Explanation: BERT example End of explanation """
bio-guoda/guoda-examples
ids_in_bhl/ids_demo.ipynb
mit
idigbio_full = sqlContext.read.parquet("../2016spr/data/idigbio/occurrence.txt.parquet") bhl_full = sqlContext.read.parquet("../guoda-datasets/BHL/data/bhl-20160516.parquet") # This replaces the datasets with ones that are a small subset #bhl = bhl_full.sample(fraction=0.01, withReplacement=False) #idigbio = idigbio_full.sample(fraction=0.001, withReplacement=False) bhl = sqlContext.createDataFrame(bhl_full.head(100)) idigbio = sqlContext.createDataFrame(idigbio_full.head(10000)) bhl.cache() idigbio.cache() print("defined") """ Explanation: Loading Data The datasets below are on local disk and are in some scratch directories. Final datasets will be in HDFS End of explanation """ idigbio.registerTempTable("idbtable") # Demonstrate using SQL syntax for working with Spark dataframes ids = sqlContext.sql(""" SELECT `http://rs.tdwg.org/dwc/terms/occurrenceID` as id FROM idbtable WHERE `http://rs.tdwg.org/dwc/terms/occurrenceID` != '' GROUP BY `http://rs.tdwg.org/dwc/terms/occurrenceID` """) # This triggers running the group by and takes a few seconds print(ids.count()) """ Explanation: Building a list of IDs From iDigBio data, make a list of unique identifiers to try to find in BHL. While there are lots of identifiers in fields, we're going to guess that the Darwin Core catalogNumber field would be the most likely to be found so only that field will be used to start. Later, other fields could be examined. End of explanation """ print(8000000*180000/1000000/60/60) """ Explanation: Search for those IDs With the list of ids, go find them in BHL OCR text. Final data structure should be a list of IDs with the added column containing a list of item IDs where the iDigBio id is found and perhaps a column for the count of the items IDs in the list which is probably what we'll end up sorting on. The naive approach would be to take each document and check it for each id in turn. That would be about: End of explanation """ def unicode_split(s): if s is not None: return s.split() else: return [] unicode_split_udf = sql.udf(unicode_split, types.ArrayType(types.StringType())) words = bhl.select(sql.explode(unicode_split_udf(bhl.ocrtext)).alias('word'), bhl.itemid) print(words.head(20)) print(words.count()) """ Explanation: hours of work asuming we could perform 1M searches per seond. Instead, let's make a list of unique words in BHL which items those words come from. Then we can join that list to the list of catalog numbers and use aggregate functions to have our answer. Tokenizing BHL into words To do that, first we need to tokenize each document and for that we need a tokenizer. We'll just use spliting on whitespace as something simple. This builds a list of word & item ID combinations End of explanation """ # could also use df.distinct() if we didn't want the counts words_summary = words.select(words.word, words.itemid).groupBy(words.word, words.itemid).count() print(words_summary.head()) print(words_summary.count()) """ Explanation: Summarize words words right now is all the words in the item but wer really only need to keep unique words since we're looking for specific terms. We can run distinct on this list. End of explanation """ joined = ids.join(words_summary, ids.id == words_summary.word, 'inner') print(joined.head(20)) print(joined.count()) """ Explanation: Joining to perform the search Now we have a list of unique words in each item and a list of ids we're looking for. Let's join them and see if we have any exact matches. End of explanation """
woobe/odsc_h2o_machine_learning
py_04a_classification_basics.ipynb
apache-2.0
# Start and connect to a local H2O cluster import h2o h2o.init(nthreads = -1) """ Explanation: Machine Learning with H2O - Tutorial 4a: Classification Models (Basics) <hr> Objective: This tutorial explains how to build classification models with four different H2O algorithms. <hr> Titanic Dataset: Source: https://www.kaggle.com/c/titanic/data <hr> Algorithms: GLM DRF GBM DNN <hr> Full Technical Reference: http://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/modeling.html <br> End of explanation """ # Import Titanic data (local CSV) titanic = h2o.import_file("kaggle_titanic.csv") titanic.head(5) # Convert 'Survived' and 'Pclass' to categorical values titanic['Survived'] = titanic['Survived'].asfactor() titanic['Pclass'] = titanic['Pclass'].asfactor() titanic['Survived'].table() titanic['Pclass'].table() titanic['Sex'].table() titanic['Age'].hist() titanic['SibSp'].hist() titanic['Parch'].hist() titanic['Fare'].hist() titanic['Embarked'].table() # Define features (or predictors) manually features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] # Split the H2O data frame into training/test sets # so we can evaluate out-of-bag performance titanic_split = titanic.split_frame(ratios = [0.8], seed = 1234) titanic_train = titanic_split[0] # using 80% for training titanic_test = titanic_split[1] # using the rest 20% for out-of-bag evaluation titanic_train.shape titanic_test.shape """ Explanation: <br> End of explanation """ # Build a Generalized Linear Model (GLM) with default settings # Import the function for GLM from h2o.estimators.glm import H2OGeneralizedLinearEstimator # Set up GLM for binary classification glm_default = H2OGeneralizedLinearEstimator(family = 'binomial', model_id = 'glm_default') # Use .train() to build the model glm_default.train(x = features, y = 'Survived', training_frame = titanic_train) # Check the model performance on training dataset glm_default # Check the model performance on test dataset glm_default.model_performance(titanic_test) """ Explanation: <br> Generalized Linear Model End of explanation """ # Build a Distributed Random Forest (DRF) model with default settings # Import the function for DRF from h2o.estimators.random_forest import H2ORandomForestEstimator # Set up DRF for regression # Add a seed for reproducibility drf_default = H2ORandomForestEstimator(model_id = 'drf_default', seed = 1234) # Use .train() to build the model drf_default.train(x = features, y = 'quality', training_frame = wine_train) # Check the DRF model summary drf_default # Check the model performance on test dataset drf_default.model_performance(wine_test) """ Explanation: <br> Distributed Random Forest End of explanation """ # Build a Gradient Boosting Machines (GBM) model with default settings # Import the function for GBM from h2o.estimators.gbm import H2OGradientBoostingEstimator # Set up GBM for regression # Add a seed for reproducibility gbm_default = H2OGradientBoostingEstimator(model_id = 'gbm_default', seed = 1234) # Use .train() to build the model gbm_default.train(x = features, y = 'quality', training_frame = wine_train) # Check the GBM model summary gbm_default # Check the model performance on test dataset gbm_default.model_performance(wine_test) """ Explanation: <br> Gradient Boosting Machines End of explanation """ # Build a Deep Learning (Deep Neural Networks, DNN) model with default settings # Import the function for DNN from h2o.estimators.deeplearning import H2ODeepLearningEstimator # Set up DNN for regression dnn_default = H2ODeepLearningEstimator(model_id = 'dnn_default') # (not run) Change 'reproducible' to True if you want to reproduce the results # The model will be built using a single thread (could be very slow) # dnn_default = H2ODeepLearningEstimator(model_id = 'dnn_default', reproducible = True) # Use .train() to build the model dnn_default.train(x = features, y = 'quality', training_frame = wine_train) # Check the DNN model summary dnn_default # Check the model performance on test dataset dnn_default.model_performance(wine_test) """ Explanation: <br> H2O Deep Learning End of explanation """ # Use GLM model to make predictions yhat_test_glm = glm_default.predict(wine_test) yhat_test_glm.head(5) # Use DRF model to make predictions yhat_test_drf = drf_default.predict(wine_test) yhat_test_drf.head(5) # Use GBM model to make predictions yhat_test_gbm = gbm_default.predict(wine_test) yhat_test_gbm.head(5) # Use DNN model to make predictions yhat_test_dnn = dnn_default.predict(wine_test) yhat_test_dnn.head(5) """ Explanation: <br> Making Predictions End of explanation """
intellimath/pyaxon
examples/axon_with_python.ipynb
mit
from __future__ import print_function from axon import loads, dumps from pprint import pprint """ Explanation: AXON is eXtended Object Notation. It's a simple notation of objects, documents and data. It's also a text based serialization format in first place. It tries to combine the best of JSON, XML and YAML. pyaxon is reference implementation of the library for processing AXON with python. <!-- TEASER_END --> End of explanation """ text = '''\ note { from: "Pooh" to: "Bee" posted: 2006-08-15T17:30 heading: "Honey" "Don't forget to get me honey!" } ''' vals = loads(text) """ Explanation: There are two API functions loads/dumps for loading/dumping from/to unicode string. By default loading and dumping are safe. By the word "safe" we mean that there is no user code is executed while loading and dumping. Unicode strings are converted only into python objects of given types. There is "unsafe" mode too. It allows to transform unicode string into user defined objects and to dump objects into unicode string under user control. But this is the topic of another post. Simple example End of explanation """ ob = vals[0] type(ob) """ Explanation: Here vals is always list of objects. End of explanation """ print(type(ob.__attrs__)) print(ob.__attrs__) """ Explanation: We see that the message is converted to the instance of class Element. Attribute vals.mapping is dictionary containing objects's attributes: End of explanation """ [(attr, getattr(ob, attr)) for attr in ob.__attrs__] """ Explanation: Attributes of the object are accessable by methods get/set: End of explanation """ print(ob[0]) """ Explanation: Element objects has content - list of values. They are accessible by python's sequence protocol. In our case the first value is the message body of the note. End of explanation """ print(dumps([ob])) """ Explanation: For dumping objects there are three modes. First mode is compact: End of explanation """ print(dumps([ob], pretty=1)) """ Explanation: Second mode is pretty dumping mode with indentations and without braces: End of explanation """ print(dumps([ob], pretty=1, braces=1)) """ Explanation: Third mode is pretty dumping mode with indentation and braces: End of explanation """ text = """\ {note: { from: "Pooh" to: "Bee" posted: 2006-08-15T17:30 heading: "Honey" body: "Don't forget to get me honey!" }} """ vals = loads(text) """ Explanation: At the end let's consider JSON-like representation too: End of explanation """ pprint(vals) """ Explanation: It has converted into python dicts: End of explanation """ print(dumps(vals)) """ Explanation: Compact dump is pretty small in size. End of explanation """ print(dumps(vals, pretty=1)) """ Explanation: Dumping in pretty mode is also pretty formatted. End of explanation """ text = '''\ { topic: [ &1 {python: "Python related"} &2 {axon: "AXON related"} &3 {json: "JSON related"} ] posts: [ { id: 1 topic: *1 date: 2012-01-02T12:15+03 body:"..." } { id: 2 topic: *2 date: 2012-01-12T09:25+03 body:"..." } { id: 3 topic: *3 date: 2012-02-08T10:35+03 body:"..." } ] } ''' vals = loads(text) pprint(vals) """ Explanation: JSON-like objects are pretty dumps only in indented form with braces. JSON-like example Let's consider now JSON-like example with crossreferences and datetimes: End of explanation """ assert vals[0]['topic'][0] is vals[0]['posts'][0]['topic'] assert vals[0]['topic'][1] is vals[0]['posts'][1]['topic'] assert vals[0]['topic'][2] is vals[0]['posts'][2]['topic'] """ Explanation: It's easy to see that crossreference links just works: End of explanation """ print(dumps(vals, pretty=1, crossref=1, sorted=0)) """ Explanation: Pretty dump looks like this one: End of explanation """ text = '''\ html { xmlns:"http://www.w3.org/1999/xhtml" head { title {"Form Example"} link { rel:"stylesheet" href: "formstyle.css" type: "text/css" }} body { h1 {"Form Example"} form { action: "sample.py" div { class: "formin" "(a)" input {type:"text" name:"text1" value:"A textbox"}} div { class: "formin" "(b)" input {type:"text" size:6 maxlength:10 name:"text2"}} div { class: "formb" "(c)" input {type:"submit" value:"Go!"}} } } } ''' vals = loads(text) val = vals[0] print(val) """ Explanation: Note that sorted parameter defines whether to sort keys in dict. XML-like example End of explanation """ print(type(val)) print(val.__attrs__) head, body = val[0], val[1] print(type(head)) title, link = head print(title) print(link) h1, form = body print(h1) print(form.__vals__) div1, div2, div3 = form print(div1.__attrs__) label1, input1 = div1 print(label1) print(input1) print(div2.__attrs__) label2, input2 = div2 print(label2) print(input2) print(type(div3)) print(div3.__attrs__) label3, input3 = div3 print(label3) print(input3) print(dumps([val], pretty=1)) print(dumps([val], pretty=1, braces=1)) """ Explanation: Let's examine the value: End of explanation """ text = '''\ dataset { fields: ("id" "date" "time" "territory_id" "A" "B" "C") (1 2012-01-10 12:35 17 3.14 22 33500) (2 2012-01-11 13:05 27 1.25 32 11500) (3 2012-01-12 10:45 -17 -2.26 -12 44700) } ''' ob = loads(text)[0] print(ob.__tag__) pprint(ob.__attrs__) pprint(ob.__vals__, width=132) print("\nPretty form of dataset:") print(dumps([ob], pretty=1, hsize=10)) from collections import namedtuple Datarow = namedtuple("Datarow", ob.fields) rows = [] for line in ob: print(type(line), line) rows.append(Datarow(*line)) print("\n") for row in rows: print(type(row), row) """ Explanation: Dataset example Let's consider simple tabular dataset: End of explanation """
quantopian/research_public
notebooks/data/quandl.cboe_vxv/notebook.ipynb
apache-2.0
# For use in Quantopian Research, exploring interactively from quantopian.interactive.data.quandl import cboe_vxv as dataset # import data operations from odo import odo # import other libraries we will use import pandas as pd # Let's use blaze to understand the data a bit using Blaze dshape() dataset.dshape # And how many rows are there? # N.B. we're using a Blaze function to do this, not len() dataset.count() # Let's see what the data looks like. We'll grab the first three rows. dataset[:3] """ Explanation: CBOE VXV Index In this notebook, we'll take a look at the CBOE VXV Index dataset, available on the Quantopian Store. This dataset spans 04 Dec 2007 through the current day. This data has a daily frequency. CBOE VXV is a constant measure of 3-month implied volatility of the S&P 500 Index options Notebook Contents There are two ways to access the data and you'll find both of them listed below. Just click on the section you'd like to read through. <a href='#interactive'><strong>Interactive overview</strong></a>: This is only available on Research and uses blaze to give you access to large amounts of data. Recommended for exploration and plotting. <a href='#pipeline'><strong>Pipeline overview</strong></a>: Data is made available through pipeline which is available on both the Research & Backtesting environment. Recommended for custom factor development and moving back & forth between research/backtesting. Limits One key caveat: we limit the number of results returned from any given expression to 10,000 to protect against runaway memory usage. To be clear, you have access to all the data server side. We are limiting the size of the responses back from Blaze. With preamble in place, let's get started: <a id='interactive'></a> Interactive Overview Accessing the data with Blaze and Interactive on Research Partner datasets are available on Quantopian Research through an API service known as Blaze. Blaze provides the Quantopian user with a convenient interface to access very large datasets, in an interactive, generic manner. Blaze provides an important function for accessing these datasets. Some of these sets are many millions of records. Bringing that data directly into Quantopian Research directly just is not viable. So Blaze allows us to provide a simple querying interface and shift the burden over to the server side. It is common to use Blaze to reduce your dataset in size, convert it over to Pandas and then to use Pandas for further computation, manipulation and visualization. Helpful links: * Query building for Blaze * Pandas-to-Blaze dictionary * SQL-to-Blaze dictionary. Once you've limited the size of your Blaze object, you can convert it to a Pandas DataFrames using: from odo import odo odo(expr, pandas.DataFrame) To see how this data can be used in your algorithm, search for the Pipeline Overview section of this notebook or head straight to <a href='#pipeline'>Pipeline Overview</a> End of explanation """ # Plotting this DataFrame df = odo(dataset, pd.DataFrame) df.head(5) # So we can plot it, we'll set the index as the `asof_date` df['asof_date'] = pd.to_datetime(df['asof_date']) df = df.set_index(['asof_date']) df.head(5) import matplotlib.pyplot as plt df['open_'].plot(label=str(dataset)) plt.ylabel(str(dataset)) plt.legend() plt.title("Graphing %s since %s" % (str(dataset), min(df.index))) """ Explanation: Let's go over the columns: - open: open price for VXV - high: daily high for VXV - low: daily low for VXV - close: close price for VXV - asof_date: the timeframe to which this data applies - timestamp: this is our timestamp on when we registered the data. We've done much of the data processing for you. Fields like timestamp are standardized across all our Store Datasets, so the datasets are easy to combine. We can select columns and rows with ease. Below, we'll do a simple plot. End of explanation """ # Import necessary Pipeline modules from quantopian.pipeline import Pipeline from quantopian.research import run_pipeline from quantopian.pipeline.factors import AverageDollarVolume # Import the datasets available from quantopian.pipeline.data.quandl import cboe_vxv """ Explanation: <a id='pipeline'></a> Pipeline Overview Accessing the data in your algorithms & research The only method for accessing partner data within algorithms running on Quantopian is via the pipeline API. Different data sets work differently but in the case of this data, you can add this data to your pipeline as follows: Import the data set here from quantopian.pipeline.data.quandl import cboe_vxv Then in intialize() you could do something simple like adding the raw value of one of the fields to your pipeline: pipe.add(cboe_vxv.open_.latest, 'open_vxv') Pipeline usage is very similar between the backtester and Research so let's go over how to import this data through pipeline and view its outputs. End of explanation """ print "Here are the list of available fields per dataset:" print "---------------------------------------------------\n" def _print_fields(dataset): print "Dataset: %s\n" % dataset.__name__ print "Fields:" for field in list(dataset.columns): print "%s - %s" % (field.name, field.dtype) print "\n" _print_fields(cboe_vxv) print "---------------------------------------------------\n" """ Explanation: Now that we've imported the data, let's take a look at which fields are available for each dataset. You'll find the dataset, the available fields, and the datatypes for each of those fields. End of explanation """ pipe = Pipeline() pipe.add(cboe_vxv.open_.latest, 'open_vxv') # Setting some basic liquidity strings (just for good habit) dollar_volume = AverageDollarVolume(window_length=20) top_1000_most_liquid = dollar_volume.rank(ascending=False) < 1000 pipe.set_screen(top_1000_most_liquid & cboe_vxv.open_.latest.notnan()) # The show_graph() method of pipeline objects produces a graph to show how it is being calculated. pipe.show_graph(format='png') # run_pipeline will show the output of your pipeline pipe_output = run_pipeline(pipe, start_date='2013-11-01', end_date='2013-11-25') pipe_output """ Explanation: Now that we know what fields we have access to, let's see what this data looks like when we run it through Pipeline. This is constructed the same way as you would in the backtester. For more information on using Pipeline in Research view this thread: https://www.quantopian.com/posts/pipeline-in-research-build-test-and-visualize-your-factors-and-filters End of explanation """ # This section is only importable in the backtester from quantopian.algorithm import attach_pipeline, pipeline_output # General pipeline imports from quantopian.pipeline import Pipeline from quantopian.pipeline.factors import AverageDollarVolume # For use in your algorithms via the pipeline API from quantopian.pipeline.data.quandl import cboe_vxv def make_pipeline(): # Create our pipeline pipe = Pipeline() # Screen out penny stocks and low liquidity securities. dollar_volume = AverageDollarVolume(window_length=20) is_liquid = dollar_volume.rank(ascending=False) < 1000 # Create the mask that we will use for our percentile methods. base_universe = (is_liquid) # Add the datasets available pipe.add(cboe_vxv.open_.latest, 'vxv_open') # Set our pipeline screens pipe.set_screen(is_liquid) return pipe def initialize(context): attach_pipeline(make_pipeline(), "pipeline") def before_trading_start(context, data): results = pipeline_output('pipeline') """ Explanation: Here, you'll notice that each security is mapped to the corresponding value, so you could grab any security to get what you need. Taking what we've seen from above, let's see how we'd move that into the backtester. End of explanation """
sdpython/ensae_teaching_cs
_doc/notebooks/sklearn_ensae_course/06_unsupervised_dimreduction.ipynb
mit
from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target """ Explanation: 2A.ML101.6: Unsupervised Learning: Dimensionality Reduction and Visualization Unsupervised learning is interested in situations in which X is available, but not y: data without labels. A typical use case is to find hiden structure in the data. Source: Course on machine learning with scikit-learn by Gaël Varoquaux Dimensionality Reduction: PCA Dimensionality reduction is the task of deriving a set of new artificial features that is smaller than the original feature set while retaining most of the variance of the original data. Here we'll use a common but powerful dimensionality reduction technique called Principal Component Analysis (PCA). We'll perform PCA on the iris dataset that we saw before: End of explanation """ from sklearn.decomposition import PCA pca = PCA(n_components=2, whiten=True) pca.fit(X) """ Explanation: PCA is performed using linear combinations of the original features using a truncated Singular Value Decomposition of the matrix X so as to project the data onto a base of the top singular vectors. If the number of retained components is 2 or 3, PCA can be used to visualize the dataset. End of explanation """ pca.components_ """ Explanation: Once fitted, the pca model exposes the singular vectors in the components_ attribute: End of explanation """ pca.explained_variance_ratio_ pca.explained_variance_ratio_.sum() """ Explanation: Other attributes are available as well: End of explanation """ X_pca = pca.transform(X) """ Explanation: Let us project the iris dataset along those first two dimensions: End of explanation """ X_pca.mean(axis=0) X_pca.std(axis=0) """ Explanation: PCA normalizes and whitens the data, which means that the data is now centered on both components with unit variance: End of explanation """ import numpy as np np.corrcoef(X_pca.T) """ Explanation: Furthermore, the samples components do no longer carry any linear correlation: End of explanation """ %matplotlib inline import matplotlib.pyplot as plt target_ids = range(len(iris.target_names)) plt.figure() for i, c, label in zip(target_ids, 'rgbcmykw', iris.target_names): plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) plt.legend(); """ Explanation: We can visualize the projection using pylab End of explanation """ from sklearn.datasets import make_s_curve X, y = make_s_curve(n_samples=1000) from mpl_toolkits.mplot3d import Axes3D ax = plt.axes(projection='3d') ax.scatter3D(X[:, 0], X[:, 1], X[:, 2], c=y) ax.view_init(10, -60) """ Explanation: Note that this projection was determined without any information about the labels (represented by the colors): this is the sense in which the learning is unsupervised. Nevertheless, we see that the projection gives us insight into the distribution of the different flowers in parameter space: notably, iris setosa is much more distinct than the other two species. Note also that the default implementation of PCA computes the singular value decomposition (SVD) of the full data matrix, which is not scalable when both n_samples and n_features are big (more that a few thousands). If you are interested in a number of components that is much smaller than both n_samples and n_features, consider using sklearn.decomposition.RandomizedPCA instead. Manifold Learning One weakness of PCA is that it cannot detect non-linear features. A set of algorithms known as Manifold Learning have been developed to address this deficiency. A canonical dataset used in Manifold learning is the S-curve, which we briefly saw in an earlier section: End of explanation """ X_pca = PCA(n_components=2).fit_transform(X) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y); """ Explanation: This is a 2-dimensional dataset embedded in three dimensions, but it is embedded in such a way that PCA cannot discover the underlying data orientation: End of explanation """ from sklearn.manifold import LocallyLinearEmbedding, Isomap lle = LocallyLinearEmbedding(n_neighbors=15, n_components=2, method='modified') X_lle = lle.fit_transform(X) plt.scatter(X_lle[:, 0], X_lle[:, 1], c=y); iso = Isomap(n_neighbors=15, n_components=2) X_iso = iso.fit_transform(X) plt.scatter(X_iso[:, 0], X_iso[:, 1], c=y); """ Explanation: Manifold learning algorithms, however, available in the sklearn.manifold submodule, are able to recover the underlying 2-dimensional manifold: End of explanation """ from sklearn.datasets import load_digits digits = load_digits() # ... """ Explanation: Exercise: Dimension reduction of digits Apply PCA, LocallyLinearEmbedding, and Isomap to project the data to two dimensions. Which visualization technique separates the classes most cleanly? End of explanation """ from sklearn.decomposition import PCA from sklearn.manifold import Isomap, LocallyLinearEmbedding plt.figure(figsize=(14, 4)) for i, est in enumerate([PCA(n_components=2, whiten=True), Isomap(n_components=2, n_neighbors=10), LocallyLinearEmbedding(n_components=2, n_neighbors=10, method='modified')]): plt.subplot(131 + i) projection = est.fit_transform(digits.data) plt.scatter(projection[:, 0], projection[:, 1], c=digits.target) plt.title(est.__class__.__name__) """ Explanation: Solution: End of explanation """
dietmarw/EK5312_ElectricalMachines
Chapman/Ch6-Problem_6-02.ipynb
unlicense
%pylab notebook """ Explanation: Excercises Electric Machinery Fundamentals Chapter 6 Problem 6-2 End of explanation """ fse = 60.0 # [Hz] p = 2.0 s = 0.025 """ Explanation: Description Answer the questions in Problem 6-1 for a 480-V three-phase two-pole 60-Hz induction motor running at a slip of 0.025. End of explanation """ n_sync = 120*fse / p print(''' n_sync = {:.0f} r/min ==================='''.format(n_sync)) """ Explanation: SOLUTION (a) The speed of the magnetic fields is: $$n_\text{sync} = \frac{120f_{se}}{p}$$ End of explanation """ n_m = (1 - s) * n_sync print(''' n_m = {:.0f} r/min ================'''.format(n_m)) """ Explanation: (b) The speed of the rotor is: $$n_m = (1-s)n_\text{sync}$$ End of explanation """ n_slip = s * n_sync print(''' n_slip = {:.0f} r/min ================='''.format(n_slip)) """ Explanation: (c) The slip speed of the rotor is: $$n_\text{slip} = s\cdot n_\text{sync}$$ End of explanation """ fre = p * n_slip / 120 print(''' fre = {:.1f} Hz ============'''.format(fre)) """ Explanation: (d) The rotor frequency is: $$f_{re} = \frac{p\cdot n_\text{slip}}{120}$$ End of explanation """
flmath-dirty/matrixes_in_erlang
jupyter/results.ipynb
mit
LoadedTable.head() """ Explanation: Introduction Test scenarios descriptions The LoadedTable contains statistics gathered from running the script that generates a matrix (Width x Height) and then runs with the fprof following tests for each representation of matrix and sizes: The tests categories: one_rows_sums - sum of values from each row in the matrix one_cols_sums - sum of values from each row in the matrix get_value - gets each value from the matrix once separetly set_value - sets each value from the matrix once separetly Matrixes are represented as follow: - sofs: Set of the sets module is a way of representing relations (in strictly mathematical sense). In this case the matrix is represented as a relation (a function) F where domain is constructed from coordinates which is related to the matrix entry value ({x,y} F Value). To get values in specific row we define equivalence relation aRb iff thera are {x,y1} F a {x,y2} F b. This relation divides antidomain in abbstract classes. If we sum elements belonging to the abstract class with element {x,_} we will get sum of the elements from this specific row. We use the same logic to receive abstrac classes for columns. digraph: We have a directed graph where each value is stored in vertex with the coordinate {x,y}. Aside of that each column and row has dedicated vertex with edges from corresponding coordinate vertexes directed at it to speed up rows and columns sums calculations. array: The matrix is represented as a tuple {Width, Height, Array}, where the array has size Width * Height, all operations are done with simply calculating positions of the values in the array. big tuple: The matrix is represented as a tuple {Width, Height, BigTuple} where the BigTuple is tuple used in the same way as the Array from previous point (note: arrays indexing starts from 0). map: A quite fresh data structure in Erlang, we map coordinates {x,y} to values. List of the lists: Each of sublists of the list contains elements representing values in the row. Since it visually resembles a matrix, it is quite often abused by coders. Heavy usage of lists module. I have run tests on the square matrixes of sizes 50x50, 100x100, 1000x1000. For some of the 1000x1000 tests fprof logs exceeded the dedicated 2TB disk size. For those the values are missing. End of explanation """ from scipy import stats from functools import reduce AggregatedTable = (LoadedTable.groupby(['Test type','Matrix representation'])['Execution time'] .apply(list).reset_index(name='Execution Times List')) """ Explanation: Preliminary processing End of explanation """ AggregatedTable.head() """ Explanation: Create aggregation table with execution time values for different size of matrixes stored in one list. End of explanation """ AggregatedTable['Harmonic Average'] = AggregatedTable['Execution Times List'].apply( lambda x: stats.hmean(x) if (len(x) == 3) else np.inf) AggregatedTable['Max'] = AggregatedTable['Execution Times List'].apply( lambda x: max(x) if (len(x) == 3) else np.inf) AggregatedTable['Min'] = AggregatedTable['Execution Times List'].apply(min) AggregatedTable.head() """ Explanation: Each list should have 3 values, if one is missing it means it exceeded testing capability of my equipment, and can be considered infinite. Also add columns with minimum values, maximum values and harmonic averages (since standard average would be too susceptible to outliers here). End of explanation """ GetValue = ( AggregatedTable .loc[AggregatedTable['Test type']=='get_value'] .loc[:,['Matrix representation','Harmonic Average','Max','Min']] ) GetValue = GetValue.set_index('Matrix representation') from jupyter_extensions.matplotlib.sawed_bar_plot import sawed_bar_plot sawed_bar_plot(GetValue) """ Explanation: Comparing operations Retrieving values Lets compare execution times for retrieving values. End of explanation """ SetValue = ( AggregatedTable .loc[AggregatedTable['Test type']=='set_value'] .loc[:,['Matrix representation','Harmonic Average','Max','Min']] ) SetValue = SetValue.set_index('Matrix representation') sawed_bar_plot(SetValue) """ Explanation: It occurs that lists of the list and set of sets implementation is extremely inefficient at retrieving values. The list of the lists sounds obvious since to get element in the middle we need to traverse to middle list representing row and then again in the row traverse to the middle element which gives O(n^2) access time. The sofs occurs to be a trap, if you will read documentation you will see elegant (from mathematician point of view) relation algebra. But if you go inside the source code you will find that module extensively uses lists:fold which translates implementation to the list of lists scenario in the best case. We can probaly make the first conclusion and an advice here: Don't abuse sofs, remember map is actually relation too (precisely function, but noone can forbid you from returning lists or other containers). Other implementations look resonable. The are some suprises, like the better perfomance of big tuples than arrays. Let see set_value functions perfomances. Storing values End of explanation """ sawed_bar_plot(SetValue,50000) """ Explanation: The lists of lists and softs are outclassed even for small matrixes like 10x10. As we suspected the big_tuple is much worse at setting values since it is immutable and setting one value means copying whole tuple. We can notice that the array even if it is more efficient has some values above the rift, lets change a little perspective: End of explanation """ sawed_bar_plot(SetValue,500) """ Explanation: Lets zoom a little bit to see small values. End of explanation """ OneColsSums = ( AggregatedTable .loc[AggregatedTable['Test type']=='one_cols_sums'] .loc[:,['Matrix representation','Harmonic Average','Max','Min']] ) OneColsSums = OneColsSums.set_index('Matrix representation') sawed_bar_plot(OneColsSums,200) """ Explanation: The array is much better than tuple, but both are magnitude worse than directed graph and matrix. It is now worth mentioning that digraph are implemented as an ets table which suggest a fixed overhead at first, but good efficiency for big tables. Still implementation with maps (build in ERTS) is faster even for 1000x1000 matrixes. We will investigate execution times increse further in the document. Since digraph represented as an ets database is quite efficient is worth to ask and keep in mind a question: if we can craft matrix representation with ets table that will be more efficient than map. I will come back to this question at the end of this document. The need for this small research occured during implemetation of a statistics gathering module. It was important to be able to calculate sums of specific counters. Usually in that case the best way is to make interface to some c or python application which support fast calculating. But this increases the complexity of the product, which should be usually avoided. Let check a performance of columns summation. Summing columns End of explanation """ OneRowsSums = ( AggregatedTable .loc[AggregatedTable['Test type']=='one_rows_sums'] .loc[:,['Matrix representation','Harmonic Average','Max','Min']] ) OneRowsSums = OneRowsSums.set_index('Matrix representation') sawed_bar_plot(OneRowsSums) """ Explanation: It is very confusing result, both array and tuple calculates the needed n indexes (in very C style) and sum extracted values (should be o(n^2), n calculations times n columns to calculate), still array is slower for big numbers than map which has to try to find value with hash (o(log(n)*n^2)), suggesting some inefficiency in implementation. Summing rows Lets look at summing rows: End of explanation """ AggregatedTableRestricted = AggregatedTable[ (AggregatedTable['Matrix representation']!='matrix_as_list_of_lists') & (AggregatedTable['Matrix representation']!='matrix_as_sofs')] AggregatedTableRestricted.head() Minimums = ( AggregatedTableRestricted .loc[:,['Test type','Matrix representation','Min']] ) #Minimums.groupby(['Test type','Matrix representation']) Minimums = Minimums.set_index(['Test type','Matrix representation']) Minimums.head() TestTypes = Minimums.index.get_level_values('Test type').unique().tolist() #MatrixRepresentations = Minimums.index.get_level_values('Matrix representation').unique().tolist() Plot = Minimums.unstack().plot(kind='bar',figsize=(12,9)) Plot.set_xticklabels(TestTypes,rotation="horizontal") handles, labels=Plot.get_legend_handles_labels() labels = [Label[6:-1] for Label in labels] Plot.legend(handles,labels) plt.show() """ Explanation: Results are similar to the previous, with exception of the list of the list, which has obvious advantage since the dominating operation is summation of the list implemented as a linked list. Anyway since setting a value is extremly expensive, this implementation is still not really good. Matrix size comparisons Small matrixes Lets remove the sofs and the lists of lists from further considerations. The next thing we should consider is which implementation is the best for small matrixes. End of explanation """ Maximums = ( AggregatedTableRestricted .loc[:,['Test type','Matrix representation','Max']] ) Maximums = Maximums.set_index(['Test type','Matrix representation']) Maximums.head() TestTypes = Maximums.index.get_level_values('Test type').unique().tolist() Plot = Maximums.unstack().plot(kind='bar',figsize=(12,9)) Plot.set_xticklabels(TestTypes,rotation="horizontal") handles, labels = Plot.get_legend_handles_labels() labels = [Label[6:-1] for Label in labels] Plot.legend(handles,labels) plt.show() """ Explanation: It occurs that for small values a big tuple is quite a good implementation, unlsess we are going to use our matrix for setting heavy tasks, in that case it is better to use map implementation. Now we can see how those implementation efficiency looks for relatively(*) big 1000 x 1000 matrixes. (*) If you really want something big you need to interface other programming language. Big matrixes End of explanation """ Maximums.loc['set_value','matrix_as_big_tuple']=np.nan TestTypes = Maximums.index.get_level_values('Test type').unique().tolist() Plot = Maximums.unstack().plot(kind='bar',figsize=(12,9)) Plot.set_xticklabels(TestTypes,rotation="horizontal") handles, labels=Plot.get_legend_handles_labels() labels = [Label[6:-1] for Label in labels] Plot.legend(handles,labels) plt.show() """ Explanation: It looks that set_value operations on the big tuple are overwhelmingly slow, to the level that they obfuscating our plot. Lets remove them from the result and compare operations that left. End of explanation """ pd.set_option('mode.chained_assignment',None) AggregatedTableRestricted['Scaled Execution Times List'] = AggregatedTableRestricted['Execution Times List'].apply( lambda X: [(z * 100)/X[0] for z in X]) pd.set_option('mode.chained_assignment','warn') AggregatedTableRestricted.head() """ Explanation: So the big tuple with calculated index values occurs not to scale great. It is not suprising, since tuple is immutable, every time you set a new value you need to copy all of them, what makes it beyond redemption when it comes to storing operations. Overall the map implementation is overall winner here, and it is overall recommendated implementation. But before we congratulate ourselves, we can notice that digraph implementation even if it is slower, maybe is only slower because overhead it implements over ets tables, and with futher increase of matrixes sizes it actually become better than maps. Growth acceleration estimation To get a little more insight, that would help us estimate if this scenario happens we should find a way to compare how quickly the time consumption functions grow. Lets try to figure out an acceleration of the resource consumption increase. For each index ([Test type, Matrix representation]) we are getting a function F that mapping the matrixes sizes: - 50 x 50 = 2500 cells = 25h(hecto) - 100 x 100 = 10k (kilo) = 100h - 1000 x 1000 = 1m (mega) into the amount of resources consumed by particular test on that matrix. See the picture below: We want to get a hint how fast the particular function growth will accelerate. We will start from visualising scale of distances we are dealing here with: 25hTo10k = 10k - 25h = <span style="color: violet">3</span> x 25h 10kTo1m = 1m - 10k = 99 x 10k = 99 x 4 x 25h = <span style="color: green">396</span> x 25h For picture above we want to find out <span style="color: teal">the increase of the increase</span> or bind to it the angle <span style="color: red">R</span>. In our simplified calculus we can consider finding an increase as finding derivate. Since one of interpretations of derivate is actually tangens, what we can look for if we want to comparable estimates of <span style="color: red">R</span> we can use tan(<span style="color: red">R</span>) (since tanges is monotonic in $(\frac{-\pi}2, \frac\pi2)$). But before we will try to find <span style="color: red">R</span> values, we need to notice that <span style="color: teal">the increase of the increase</span> to <span style="color: orange">the projected increase</span> ratio is depended on value of the 25h, so does the <span style="color: red">R</span>. We want to remove this sensitivity to initial conditions, to do that we scale all the mappings, so the value of the 25h is the same for each of them. End of explanation """ pd.set_option('mode.chained_assignment',None) AggregatedTableRestricted['ProjectedIncrease'] = AggregatedTableRestricted['Scaled Execution Times List'].apply( lambda x: 396*(x[1]-x[0])) AggregatedTableRestricted['ActualIncrease'] = AggregatedTableRestricted['Scaled Execution Times List'].apply( lambda x: x[2]-x[1]) pd.set_option('mode.chained_assignment','warn') AggregatedTableRestricted.head() """ Explanation: Now by definition: tan(<span style="color: blue">B</span>) = <span style="color: orange">the projected increase</span>/(<span style="color: green">396</span> x 25h) tan(<span style="color: red">R</span>+<span style="color: blue">B</span>) = 10kTo1mValueIncrease/(<span style="color: green">396</span> x 25h) Since denominator is the same we don't need to consider it here. Lets calculate those increases. End of explanation """ import sympy as sp R, B = sp.symbols('R B') tanRplusB = sp.expand_trig(sp.tan(R + B)) tanRplusB """ Explanation: We have tan(<span style="color: red">R</span>+<span style="color: blue">B</span>) and tan(<span style="color: blue">B</span>), but we want to calculate tan(<span style="color: red">R</span>). Fortunately there are identities that can help us with that. End of explanation """ Ratio= tanRplusB.subs(sp.tan(R),R).subs(sp.tan(B),B) C = sp.symbols('C') RatioSolution = sp.solve(sp.Eq(Ratio , C),R) RatioSolution FinalSolution = RatioSolution[0].subs(B,sp.tan(B)).subs(C,sp.tan(R+B)) FinalSolution """ Explanation: We want to experess tan(<span style="color: red">R</span>). SymPy trigonometric expansion/simplification functions would give us quite complicated answers (including atan function). But we just want to treat tan(<span style="color: red">R</span>) as rational function of the other tanges, so we make substitution. - tan(<span style="color: red">R</span>+<span style="color: blue">B</span>) = C - tan(<span style="color: blue">B</span>) = B - tan(<span style="color: red">R</span>) = R End of explanation """ sp.simplify(FinalSolution-sp.tan(R)) == 0 """ Explanation: Double check that result is actually valid: End of explanation """ pd.set_option('mode.chained_assignment',None) AggregatedTableRestricted['TanB'] = AggregatedTableRestricted['ProjectedIncrease'].apply( lambda x: x/396) AggregatedTableRestricted['TanAplusB'] = AggregatedTableRestricted['ActualIncrease'].apply( lambda x: x/396) AggregatedTableRestricted['TanA'] = ( (AggregatedTableRestricted['TanAplusB']-AggregatedTableRestricted['TanB'])/((AggregatedTableRestricted['TanAplusB']*AggregatedTableRestricted['TanB'])+1)) pd.set_option('mode.chained_assignment','warn') Diffs = ( AggregatedTableRestricted .loc[:,['Test type','Matrix representation','TanA']] ) #Minimums.groupby(['Test type','Matrix representation']) Diffs = Diffs.set_index(['Test type','Matrix representation']) TestTypes = Diffs.index.get_level_values('Test type').unique().tolist() Plot = Diffs.unstack().plot(kind='bar',figsize=(12,9)) Plot.set_xticklabels(TestTypes,rotation="horizontal") handles, labels=Plot.get_legend_handles_labels() labels = [Label[7:-1] for Label in labels] Plot.legend(handles,labels) plt.show() """ Explanation: Lets apply the result equation on our data: End of explanation """
DallasTrinkle/Onsager
examples/Garnet.ipynb
mit
import sys sys.path.extend(['../']) import numpy as np import onsager.crystal as crystal import onsager.OnsagerCalc as onsager """ Explanation: Garnet correlation coefficients Comparing to correlation coefficients from William D. Carlson and Clark R. Wilson, Phys Chem Minerals 43, 363-369 (2016) doi:10.1007/s00269-016-0800-2 Garnet structure includes pyrope, which we use as our example structure, with space group 230 (Ia3d) with stoichiometry Mg<sub>3</sub>Al<sub>2</sub>Si<sub>3</sub>O<sub>12</sub>. The occupied Wyckoff positions for this are (lattice constant $a_0$=1.1459 nm): | Wykcoff site | chemistry | position | |--------------|-----------|----------| |24c |Mg |1/8 0 1/4 | |16a |Al |0 0 0 | |24d |Si |3/8 0 1/4 | |96h |O |.03284 .05014 .65330| Data from G. V. Gibbs and J. V. Smith, "Refinement of the crystal structure of synthetic pyrope." American Mineralogist 50 2023-2039 (1965), PDF. End of explanation """ # a0 = 1.1459 # alatt = a0*np.eye(3) a0 = 1. alatt = a0*np.array([[-0.5,0.5,0.5],[0.5,-0.5,0.5],[0.5,0.5,-0.5]]) invlatt = np.array([[0,1,1],[1,0,1],[1,1,0]]) x,y,z = (.03284,.05014,.65330) uMg = ((1/8,0,1/4),(3/8,0,3/4),(1/4,1/8,0),(3/4,3/8,0), (0,1/4,1/8),(0,3/4,3/8),(7/8,0,3/4),(5/8,0,1/4), (3/4,7/8,0),(1/4,5/8,0),(0,3/4,7/8),(0,1/4,5/8)) uAl = ((0,0,0),(1/2,0,1/2),(0,1/2,1/2),(1/2,1/2,0), (3/4,1/4,1/4),(3/4,3/4,3/4),(1/4,1/4,3/4),(1/4,3/4,1/4)) uSi = ((3/8,0,1/4),(1/8,0,3/4),(1/4,3/8,0),(3/4,1/8,0), (0,1/4,3/8),(0,3/4,1/8),(3/4,5/8,0),(3/4,3/8,1/2), (1/8,1/2,1/4),(7/8,0,1/4),(0,1/4,7/8),(1/2,1/4,1/8)) uO = ((x,y,z),(-x+1/2,-y,z+1/2),(-x,y+1/2,-z+1/2),(x+1/2,-y+1/2,-z), (z,x,y),(z+1/2,-x+1/2,-y),(-z+1/2,-x,y+1/2),(-z,x+1/2,-y+1/2), (y,z,x),(-y,z+1/2,-x+1/2),(y+1/2,-z+1/2,-x),(-y+1/2,-z,x+1/2), (y+3/4,x+1/4,-z+1/4),(-y+3/4,-x+3/4,-z+3/4),(y+1/4,-x+1/4,z+3/4),(-y+1/4,x+3/4,z+1/4), (x+3/4,z+1/4,-y+1/4),(-x+1/4,z+3/4,y+1/4),(-x+3/4,-z+3/4,-y+3/4),(x+1/4,-z+1/4,y+3/4), (z+3/4,y+1/4,-x+1/4),(z+1/4,-y+1/4,x+3/4),(-z+1/4,y+3/4,x+1/4),(-z+3/4,-y+3/4,-x+3/4), (-x,-y,-z),(x+1/2,y,-z+1/2),(x,-y+1/2,z+1/2),(-x+1/2,y+1/2,z), (-z,-x,-y),(-z+1/2,x+1/2,y),(z+1/2,x,-y+1/2),(z,-x+1/2,y+1/2), (-y,-z,-x),(y,-z+1/2,x+1/2),(-y+1/2,z+1/2,x),(y+1/2,z,-x+1/2), (-y+1/4,-x+3/4,z+3/4),(y+1/4,x+1/4,z+1/4),(-y+3/4,x+3/4,-z+1/4),(y+3/4,-x+1/4,-z+3/4), (-x+1/4,-z+3/4,y+3/4),(x+3/4,-z+1/4,-y+3/4),(x+1/4,z+1/4,y+1/4),(-x+3/4,z+3/4,-y+1/4), (-z+1/4,-y+3/4,x+3/4),(-z+3/4,y+3/4,-x+1/4),(z+3/4,-y+1/4,-x+3/4),(z+1/4,y+1/4,x+1/4)) # tovec = lambda x: np.array(x) # tovec2 = lambda x: np.array((x[0]+1/2,x[1]+1/2,x[2]+1/2)) tovec = lambda x: np.dot(invlatt, x) pyrope = crystal.Crystal(alatt, [[vec(w) for w in ulist for vec in (tovec,)] for ulist in (uMg, uAl, uSi, uO)], ['Mg','Al','Si','O']) # print(pyrope) """ Explanation: Create garnet crystal (lattice constant in nm). Wyckoff positions cut and pasted from Bilbao crystallographic server. End of explanation """ chem = 0 # 0 is the index corresponding to our Mg atom in the crystal cutoff = 0.31*a0 # had been 0.51*a0 sitelist = pyrope.sitelist(chem) jumpnetwork = pyrope.jumpnetwork(chem, cutoff) Mgdiffuser = onsager.VacancyMediated(pyrope, chem, sitelist, jumpnetwork, 1) print(Mgdiffuser) """ Explanation: Next, we construct a diffuser based on vacancies for our Mg ion. We need to create a sitelist (which will be the Wyckoff positions) and a jumpnetwork for the transitions between the sites. There are tags that correspond to the unique states and transitions in the diffuser. The first cutoff is $\sim 0.31a_0$, but that connects half of the Mg cation sites to each other; increasing the cutoff to $\sim 0.51a_0$ introduces a second network that completes the connections. End of explanation """ for jlist in jumpnetwork: Z = 0 dx2 = np.zeros((3,3)) for (i,j), dx in jlist: if i==0: Z += 1 dx2 += np.outer(dx,dx) print("coordination number:", Z) print(dx2) print("1/3 Tr dx dx:", dx2.trace()/3) print("dx^2:", np.dot(dx,dx)) """ Explanation: Quick analysis on our jump network: What is the connectivity, $Z$? What is the individual contribution to $\mathbf{\delta x}\otimes\mathbf{\delta x}$? And 1/3 Tr (which will be the symmetrized contribution)? What is the squared magnitude $\delta x^2$? End of explanation """ nu0 = 0.25 Etrans = 0. # we don't need to use the tags, since there's only one site and jump type, and # we want to build a tracer. Mgthermodict = {'preV': np.ones(len(sitelist)), 'eneV': np.zeros(len(sitelist)), 'preT0': nu0*np.ones(len(jumpnetwork)), 'eneT0': Etrans*np.ones(len(jumpnetwork))} Mgthermodict.update(Mgdiffuser.maketracerpreene(**Mgthermodict)) for k,v in Mgthermodict.items(): print('{}: {}'.format(k, v)) """ Explanation: Next, we assemble our data: the energies and prefactors, for a V<sub>Mg</sub> in pyrope for our representative states and transitions: these are the first states in the lists, which are also identified by the tags above. As we are computing a tracer, we make the choice to set $\nu_0 = 1/Z$ where $Z=4$ is the coordination number. End of explanation """ Lvv, Lss, Lsv, L1vv = Mgdiffuser.Lij(*Mgdiffuser.preene2betafree(1, **Mgthermodict)) print(Lvv) print(Lss) print(Lsv) print(L1vv) print("Correlation coefficient:", -Lss[0,0]/Lsv[0,0]) """ Explanation: We compute the Onsager matrices, and look at $-L_\text{ss}/L_\text{sv}$ to get our correlation coefficient. Note: we can define $f$ (for our tracer) as the ratio of $L_\text{ss}$ to $Z (\delta x)^2 w_2 c_\text{v}c_\text{s}/6 = \frac{1}{16}\nu_0 a_0^2$ in this case, the same as what we get for $L_\text{vv}$ and $-L_\text{sv}$. End of explanation """ # tabulated data from paper CarlsonWilsonGFdata = \ {(0,0,0): 2.30796022, (2,1,1): 1.30807261, (3,3,2): 0.80669536, (4,2,0): 0.40469085, (4,4,4): 0.50242046, (5,3,2): 0.56195744, (6,1,1): 0.56071092, (6,4,0): 0.22460654, (6,5,3): 0.42028488, (6,5,5): 0.40137897, (7,2,1): 0.44437878, (8,0,0): 0.41938675} print('CW index\tdx match\tGF (FT eval)\tGF(CW stoch.)\terror') GF = Mgdiffuser.GFcalc # get our GF calculator; should already have rates set basis = pyrope.basis[chem] x0 = np.dot(alatt, basis[0]) for vec,gCW in CarlsonWilsonGFdata.items(): dx0 = np.array(vec,dtype=float)/8 nmatch, Gave, Gmatch = 0, 0, {} for g in pyrope.G: dx = np.dot(g.cartrot, dx0) j = pyrope.cart2pos(x0+dx)[1] if j is not None and j[0]==chem and j[1]<6: G = GF(0, j[1], dx) Gmatch[tuple((8*dx).astype(int))] = G nmatch += 1 Gave += G Gave /= nmatch for t,G in Gmatch.items(): print('{}\t{}\t{:.12f}\t{:.8f}\t{:.4e}'.format(vec, t, -G, gCW, abs(G+gCW))) print('{}\taverage value\t{:.12f}\t{:.8f}\t{:.4e}'.format(vec, -Gave, gCW, abs(Gave+gCW))) """ Explanation: Compare with tabulated GF data from Carlson and Wilson paper. They use the notation $(l,m,n)$ for a $\mathbf{\delta x}$ vector that is $a_0(l\hat x+m\hat y+n\hat z)/8$. We will need to find a corresponding site that lands at that displacement from our origin site. Unfortunately, it looks like in two cases ((800), (444)) there are two distinct sites that are mapped in that displacement vector, which have different GF values; the CW reported values appear to be the averaged values. In two other cases, ((640), (420)) the reported values are half of what the computed values are here. As Carlson and Wilson used a stochastic approach to compute their GF values, all of their other data has errors $\sim 10^{-4}$. End of explanation """
cathalmccabe/PYNQ
pynq/notebooks/common/programming_pybind11.ipynb
bsd-3-clause
from pynq.lib import pybind11 """ Explanation: Programming C/C++ using Pybind11 In this notebook we will show how to leverage Pybind11 to develop normal C/C++ program in Jupyter environment. This is a unique feature added by the pynq package. Compared to the SWIG binding, Pybind11 supports C++ program; therefore it is the recommended way for binding C/C++ programs with Python interfaces. End of explanation """ %%pybind11 example1 #include <iostream> #include <string> using namespace std; const string greeting = "Hello, PYNQ."; int multiply(int a, int b) { return a*b; } double multiply_half(double c){ return c*0.5; } """ Explanation: Example 1: Simple functions Let's first look at a very simple example. With the magic pybind11, we can specify the desired Python module name example1. Under the hood: 1. The C++ program (example1.cpp) is generated. 2. The C++ program is compiled into a shared object file (example1.cpython-36m-&lt;arch&gt;.so). The compilation process can take around 20 seconds, so please be patient. End of explanation """ import example1 example1.multiply(2,3) example1.greeting example1.multiply_half(0.5) """ Explanation: Then we can easily import the module and call the C++ functions as if they are available as Python functions. End of explanation """ %%pybind11 example2 #include <iostream> #include <string> class Pet { public: Pet(const std::string &name) : name(name) { } void setName(const std::string &name_) { name = name_; } const std::string &getName() const { return name; } private: std::string name; }; class Dog : public Pet { public: Dog(const std::string &name) : Pet(name) { } std::string bark() const { return "woof!"; } }; """ Explanation: Note: you can change the C++ program and recompile, but for Jupyter notebook to reload the new context, you will need to restart the kernel for changes to take effect. Example 2: Classes Maybe you are tired of the simple C program, so let's look at how we deal with classes in C++ code. We will use the example in Pybind11 documentation. Compare to the original C++ code, all we have to do is to add the magic %%pybind11 example2 in the following cell. End of explanation """ import example2 p = example2.Pet('Alice') p.setName("Bob") p.getName() d = example2.Dog('Dave') d.bark() """ Explanation: Now we should be able to use the class as if it is implemented in Python. Notice we are not binding the private attribute name as a property (in principle you should be able to do so with Pybind11); this is because it may not be clear what its setter and getter functions are. So we just use its setter and getter explicitly. End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/ec-earth-consortium/cmip6/models/ec-earth3-veg/atmos.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-veg', 'atmos') """ Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: EC-EARTH3-VEG Topic: Atmos Sub-Topics: Dynamical Core, Radiation, Turbulence Convection, Microphysics Precipitation, Cloud Scheme, Observation Simulation, Gravity Waves, Solar, Volcanos. Properties: 156 (127 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:53:59 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties --&gt; Overview 2. Key Properties --&gt; Resolution 3. Key Properties --&gt; Timestepping 4. Key Properties --&gt; Orography 5. Grid --&gt; Discretisation 6. Grid --&gt; Discretisation --&gt; Horizontal 7. Grid --&gt; Discretisation --&gt; Vertical 8. Dynamical Core 9. Dynamical Core --&gt; Top Boundary 10. Dynamical Core --&gt; Lateral Boundary 11. Dynamical Core --&gt; Diffusion Horizontal 12. Dynamical Core --&gt; Advection Tracers 13. Dynamical Core --&gt; Advection Momentum 14. Radiation 15. Radiation --&gt; Shortwave Radiation 16. Radiation --&gt; Shortwave GHG 17. Radiation --&gt; Shortwave Cloud Ice 18. Radiation --&gt; Shortwave Cloud Liquid 19. Radiation --&gt; Shortwave Cloud Inhomogeneity 20. Radiation --&gt; Shortwave Aerosols 21. Radiation --&gt; Shortwave Gases 22. Radiation --&gt; Longwave Radiation 23. Radiation --&gt; Longwave GHG 24. Radiation --&gt; Longwave Cloud Ice 25. Radiation --&gt; Longwave Cloud Liquid 26. Radiation --&gt; Longwave Cloud Inhomogeneity 27. Radiation --&gt; Longwave Aerosols 28. Radiation --&gt; Longwave Gases 29. Turbulence Convection 30. Turbulence Convection --&gt; Boundary Layer Turbulence 31. Turbulence Convection --&gt; Deep Convection 32. Turbulence Convection --&gt; Shallow Convection 33. Microphysics Precipitation 34. Microphysics Precipitation --&gt; Large Scale Precipitation 35. Microphysics Precipitation --&gt; Large Scale Cloud Microphysics 36. Cloud Scheme 37. Cloud Scheme --&gt; Optical Cloud Properties 38. Cloud Scheme --&gt; Sub Grid Scale Water Distribution 39. Cloud Scheme --&gt; Sub Grid Scale Ice Distribution 40. Observation Simulation 41. Observation Simulation --&gt; Isscp Attributes 42. Observation Simulation --&gt; Cosp Attributes 43. Observation Simulation --&gt; Radar Inputs 44. Observation Simulation --&gt; Lidar Inputs 45. Gravity Waves 46. Gravity Waves --&gt; Orographic Gravity Waves 47. Gravity Waves --&gt; Non Orographic Gravity Waves 48. Solar 49. Solar --&gt; Solar Pathways 50. Solar --&gt; Solar Constant 51. Solar --&gt; Orbital Parameters 52. Solar --&gt; Insolation Ozone 53. Volcanos 54. Volcanos --&gt; Volcanoes Treatment 1. Key Properties --&gt; Overview Top level key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of atmosphere model code (CAM 4.0, ARPEGE 3.2,...) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_family') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "AGCM" # "ARCM" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Model Family Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of atmospheric model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.basic_approximations') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "primitive equations" # "non-hydrostatic" # "anelastic" # "Boussinesq" # "hydrostatic" # "quasi-hydrostatic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Basic approximations made in the atmosphere. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.horizontal_resolution_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Resolution Characteristics of the model resolution 2.1. Horizontal Resolution Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of the model grid, e.g. T42, N48. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Canonical Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Expression quoted for gross comparisons of resolution, e.g. 2.5 x 3.75 degrees lat-lon. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.range_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Range Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Range of horizontal resolution with spatial details, eg. 1 deg (Equator) - 0.5 deg End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 2.4. Number Of Vertical Levels Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of vertical levels resolved on the computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.high_top') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 2.5. High Top Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the atmosphere have a high-top? High-Top atmospheres have a fully resolved stratosphere with a model top above the stratopause. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_dynamics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Timestepping Characteristics of the atmosphere model time stepping 3.1. Timestep Dynamics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep for the dynamics, e.g. 30 min. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_shortwave_radiative_transfer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.2. Timestep Shortwave Radiative Transfer Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for the shortwave radiative transfer, e.g. 1.5 hours. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_longwave_radiative_transfer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.3. Timestep Longwave Radiative Transfer Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for the longwave radiative transfer, e.g. 3 hours. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.orography.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "present day" # "modified" # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Orography Characteristics of the model orography 4.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of the orography. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.orography.changes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "related to ice sheets" # "related to tectonics" # "modified mean" # "modified variance if taken into account in model (cf gravity waves)" # TODO - please enter value(s) """ Explanation: 4.2. Changes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N If the orography type is modified describe the time adaptation changes. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Grid --&gt; Discretisation Atmosphere grid discretisation 5.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of grid discretisation in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "spectral" # "fixed grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6. Grid --&gt; Discretisation --&gt; Horizontal Atmosphere discretisation in the horizontal 6.1. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "finite elements" # "finite volumes" # "finite difference" # "centered finite difference" # TODO - please enter value(s) """ Explanation: 6.2. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_order') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "second" # "third" # "fourth" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6.3. Scheme Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation function order End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.horizontal_pole') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "filter" # "pole rotation" # "artificial island" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6.4. Horizontal Pole Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Horizontal discretisation pole singularity treatment End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.grid_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Gaussian" # "Latitude-Longitude" # "Cubed-Sphere" # "Icosahedral" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6.5. Grid Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal grid type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.vertical.coordinate_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "isobaric" # "sigma" # "hybrid sigma-pressure" # "hybrid pressure" # "vertically lagrangian" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 7. Grid --&gt; Discretisation --&gt; Vertical Atmosphere discretisation in the vertical 7.1. Coordinate Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Type of vertical coordinate system End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Dynamical Core Characteristics of the dynamical core 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of atmosphere dynamical core End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the dynamical core of the model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.timestepping_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Adams-Bashforth" # "explicit" # "implicit" # "semi-implicit" # "leap frog" # "multi-step" # "Runge Kutta fifth order" # "Runge Kutta second order" # "Runge Kutta third order" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.3. Timestepping Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestepping framework type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "surface pressure" # "wind components" # "divergence/curl" # "temperature" # "potential temperature" # "total water" # "water vapour" # "water liquid" # "water ice" # "total water moments" # "clouds" # "radiation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.4. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of the model prognostic variables End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_boundary_condition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "sponge layer" # "radiation boundary condition" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 9. Dynamical Core --&gt; Top Boundary Type of boundary layer at the top of the model 9.1. Top Boundary Condition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary condition End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_heat') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.2. Top Heat Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary heat treatment End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_wind') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.3. Top Wind Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary wind treatment End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.lateral_boundary.condition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "sponge layer" # "radiation boundary condition" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10. Dynamical Core --&gt; Lateral Boundary Type of lateral boundary condition (if the model is a regional model) 10.1. Condition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Type of lateral boundary condition End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.diffusion_horizontal.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11. Dynamical Core --&gt; Diffusion Horizontal Horizontal diffusion scheme 11.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Horizontal diffusion scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.diffusion_horizontal.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "iterated Laplacian" # "bi-harmonic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.2. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal diffusion scheme method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Heun" # "Roe and VanLeer" # "Roe and Superbee" # "Prather" # "UTOPIA" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12. Dynamical Core --&gt; Advection Tracers Tracer advection scheme 12.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Tracer advection scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.scheme_characteristics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Eulerian" # "modified Euler" # "Lagrangian" # "semi-Lagrangian" # "cubic semi-Lagrangian" # "quintic semi-Lagrangian" # "mass-conserving" # "finite volume" # "flux-corrected" # "linear" # "quadratic" # "quartic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12.2. Scheme Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Tracer advection scheme characteristics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.conserved_quantities') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "dry mass" # "tracer mass" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12.3. Conserved Quantities Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Tracer advection scheme conserved quantities End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.conservation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "conservation fixer" # "Priestley algorithm" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12.4. Conservation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Tracer advection scheme conservation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "VanLeer" # "Janjic" # "SUPG (Streamline Upwind Petrov-Galerkin)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13. Dynamical Core --&gt; Advection Momentum Momentum advection scheme 13.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Momentum advection schemes name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_characteristics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "2nd order" # "4th order" # "cell-centred" # "staggered grid" # "semi-staggered grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.2. Scheme Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Momentum advection scheme characteristics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_staggering_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Arakawa B-grid" # "Arakawa C-grid" # "Arakawa D-grid" # "Arakawa E-grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.3. Scheme Staggering Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Momentum advection scheme staggering type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.conserved_quantities') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Angular momentum" # "Horizontal momentum" # "Enstrophy" # "Mass" # "Total energy" # "Vorticity" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.4. Conserved Quantities Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Momentum advection scheme conserved quantities End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.conservation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "conservation fixer" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.5. Conservation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Momentum advection scheme conservation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.aerosols') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "sulphate" # "nitrate" # "sea salt" # "dust" # "ice" # "organic" # "BC (black carbon / soot)" # "SOA (secondary organic aerosols)" # "POM (particulate organic matter)" # "polar stratospheric ice" # "NAT (nitric acid trihydrate)" # "NAD (nitric acid dihydrate)" # "STS (supercooled ternary solution aerosol particle)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 14. Radiation Characteristics of the atmosphere radiation process 14.1. Aerosols Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Aerosols whose radiative effect is taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15. Radiation --&gt; Shortwave Radiation Properties of the shortwave radiation scheme 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of shortwave radiation in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.spectral_integration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "wide-band model" # "correlated-k" # "exponential sum fitting" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.3. Spectral Integration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Shortwave radiation scheme spectral integration End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.transport_calculation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "two-stream" # "layer interaction" # "bulk" # "adaptive" # "multi-stream" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.4. Transport Calculation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Shortwave radiation transport calculation methods End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.spectral_intervals') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.5. Spectral Intervals Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Shortwave radiation scheme number of spectral intervals End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.greenhouse_gas_complexity') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CO2" # "CH4" # "N2O" # "CFC-11 eq" # "CFC-12 eq" # "HFC-134a eq" # "Explicit ODSs" # "Explicit other fluorinated gases" # "O3" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16. Radiation --&gt; Shortwave GHG Representation of greenhouse gases in the shortwave radiation scheme 16.1. Greenhouse Gas Complexity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Complexity of greenhouse gases whose shortwave radiative effects are taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.ODS') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CFC-12" # "CFC-11" # "CFC-113" # "CFC-114" # "CFC-115" # "HCFC-22" # "HCFC-141b" # "HCFC-142b" # "Halon-1211" # "Halon-1301" # "Halon-2402" # "methyl chloroform" # "carbon tetrachloride" # "methyl chloride" # "methylene chloride" # "chloroform" # "methyl bromide" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.2. ODS Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Ozone depleting substances whose shortwave radiative effects are explicitly taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.other_flourinated_gases') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HFC-134a" # "HFC-23" # "HFC-32" # "HFC-125" # "HFC-143a" # "HFC-152a" # "HFC-227ea" # "HFC-236fa" # "HFC-245fa" # "HFC-365mfc" # "HFC-43-10mee" # "CF4" # "C2F6" # "C3F8" # "C4F10" # "C5F12" # "C6F14" # "C7F16" # "C8F18" # "c-C4F8" # "NF3" # "SF6" # "SO2F2" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.3. Other Flourinated Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Other flourinated gases whose shortwave radiative effects are explicitly taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17. Radiation --&gt; Shortwave Cloud Ice Shortwave radiative properties of ice crystals in clouds 17.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with cloud ice crystals End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "bi-modal size distribution" # "ensemble of ice crystals" # "mean projected area" # "ice water path" # "crystal asymmetry" # "crystal aspect ratio" # "effective crystal radius" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud ice crystals in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud ice crystals in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18. Radiation --&gt; Shortwave Cloud Liquid Shortwave radiative properties of liquid droplets in clouds 18.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with cloud liquid droplets End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud droplet number concentration" # "effective cloud droplet radii" # "droplet size distribution" # "liquid water path" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud liquid droplets in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "geometric optics" # "Mie theory" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud liquid droplets in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_inhomogeneity.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Monte Carlo Independent Column Approximation" # "Triplecloud" # "analytic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 19. Radiation --&gt; Shortwave Cloud Inhomogeneity Cloud inhomogeneity in the shortwave radiation scheme 19.1. Cloud Inhomogeneity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method for taking into account horizontal cloud inhomogeneity End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 20. Radiation --&gt; Shortwave Aerosols Shortwave radiative properties of aerosols 20.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with aerosols End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "number concentration" # "effective radii" # "size distribution" # "asymmetry" # "aspect ratio" # "mixing state" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 20.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of aerosols in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 20.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to aerosols in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_gases.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 21. Radiation --&gt; Shortwave Gases Shortwave radiative properties of gases 21.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with gases End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 22. Radiation --&gt; Longwave Radiation Properties of the longwave radiation scheme 22.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of longwave radiation in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 22.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the longwave radiation scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.spectral_integration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "wide-band model" # "correlated-k" # "exponential sum fitting" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 22.3. Spectral Integration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Longwave radiation scheme spectral integration End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.transport_calculation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "two-stream" # "layer interaction" # "bulk" # "adaptive" # "multi-stream" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 22.4. Transport Calculation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Longwave radiation transport calculation methods End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.spectral_intervals') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 22.5. Spectral Intervals Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Longwave radiation scheme number of spectral intervals End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.greenhouse_gas_complexity') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CO2" # "CH4" # "N2O" # "CFC-11 eq" # "CFC-12 eq" # "HFC-134a eq" # "Explicit ODSs" # "Explicit other fluorinated gases" # "O3" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23. Radiation --&gt; Longwave GHG Representation of greenhouse gases in the longwave radiation scheme 23.1. Greenhouse Gas Complexity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Complexity of greenhouse gases whose longwave radiative effects are taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.ODS') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CFC-12" # "CFC-11" # "CFC-113" # "CFC-114" # "CFC-115" # "HCFC-22" # "HCFC-141b" # "HCFC-142b" # "Halon-1211" # "Halon-1301" # "Halon-2402" # "methyl chloroform" # "carbon tetrachloride" # "methyl chloride" # "methylene chloride" # "chloroform" # "methyl bromide" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23.2. ODS Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Ozone depleting substances whose longwave radiative effects are explicitly taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.other_flourinated_gases') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HFC-134a" # "HFC-23" # "HFC-32" # "HFC-125" # "HFC-143a" # "HFC-152a" # "HFC-227ea" # "HFC-236fa" # "HFC-245fa" # "HFC-365mfc" # "HFC-43-10mee" # "CF4" # "C2F6" # "C3F8" # "C4F10" # "C5F12" # "C6F14" # "C7F16" # "C8F18" # "c-C4F8" # "NF3" # "SF6" # "SO2F2" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23.3. Other Flourinated Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Other flourinated gases whose longwave radiative effects are explicitly taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 24. Radiation --&gt; Longwave Cloud Ice Longwave radiative properties of ice crystals in clouds 24.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with cloud ice crystals End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.physical_reprenstation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "bi-modal size distribution" # "ensemble of ice crystals" # "mean projected area" # "ice water path" # "crystal asymmetry" # "crystal aspect ratio" # "effective crystal radius" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 24.2. Physical Reprenstation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud ice crystals in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 24.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud ice crystals in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25. Radiation --&gt; Longwave Cloud Liquid Longwave radiative properties of liquid droplets in clouds 25.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with cloud liquid droplets End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud droplet number concentration" # "effective cloud droplet radii" # "droplet size distribution" # "liquid water path" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud liquid droplets in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "geometric optics" # "Mie theory" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud liquid droplets in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_inhomogeneity.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Monte Carlo Independent Column Approximation" # "Triplecloud" # "analytic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 26. Radiation --&gt; Longwave Cloud Inhomogeneity Cloud inhomogeneity in the longwave radiation scheme 26.1. Cloud Inhomogeneity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method for taking into account horizontal cloud inhomogeneity End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 27. Radiation --&gt; Longwave Aerosols Longwave radiative properties of aerosols 27.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with aerosols End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "number concentration" # "effective radii" # "size distribution" # "asymmetry" # "aspect ratio" # "mixing state" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 27.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of aerosols in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 27.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to aerosols in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_gases.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 28. Radiation --&gt; Longwave Gases Longwave radiative properties of gases 28.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with gases End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 29. Turbulence Convection Atmosphere Convective Turbulence and Clouds 29.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of atmosphere convection and turbulence End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Mellor-Yamada" # "Holtslag-Boville" # "EDMF" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 30. Turbulence Convection --&gt; Boundary Layer Turbulence Properties of the boundary layer turbulence scheme 30.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Boundary layer turbulence scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "TKE prognostic" # "TKE diagnostic" # "TKE coupled with water" # "vertical profile of Kz" # "non-local diffusion" # "Monin-Obukhov similarity" # "Coastal Buddy Scheme" # "Coupled with convection" # "Coupled with gravity waves" # "Depth capped at cloud base" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 30.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Boundary layer turbulence scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.closure_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 30.3. Closure Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Boundary layer turbulence scheme closure order End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.counter_gradient') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 30.4. Counter Gradient Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Uses boundary layer turbulence scheme counter gradient End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 31. Turbulence Convection --&gt; Deep Convection Properties of the deep convection scheme 31.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Deep convection scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mass-flux" # "adjustment" # "plume ensemble" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Deep convection scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CAPE" # "bulk" # "ensemble" # "CAPE/WFN based" # "TKE/CIN based" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.3. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Deep convection scheme method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "vertical momentum transport" # "convective momentum transport" # "entrainment" # "detrainment" # "penetrative convection" # "updrafts" # "downdrafts" # "radiative effect of anvils" # "re-evaporation of convective precipitation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.4. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical processes taken into account in the parameterisation of deep convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.microphysics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "tuning parameter based" # "single moment" # "two moment" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.5. Microphysics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Microphysics scheme for deep convection. Microphysical processes directly control the amount of detrainment of cloud hydrometeor and water vapor from updrafts End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 32. Turbulence Convection --&gt; Shallow Convection Properties of the shallow convection scheme 32.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Shallow convection scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mass-flux" # "cumulus-capped boundary layer" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 32.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N shallow convection scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "same as deep (unified)" # "included in boundary layer turbulence" # "separate diagnosis" # TODO - please enter value(s) """ Explanation: 32.3. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 shallow convection scheme method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "convective momentum transport" # "entrainment" # "detrainment" # "penetrative convection" # "re-evaporation of convective precipitation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 32.4. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical processes taken into account in the parameterisation of shallow convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.microphysics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "tuning parameter based" # "single moment" # "two moment" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 32.5. Microphysics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Microphysics scheme for shallow convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 33. Microphysics Precipitation Large Scale Cloud Microphysics and Precipitation 33.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of large scale cloud microphysics and precipitation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_precipitation.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 34. Microphysics Precipitation --&gt; Large Scale Precipitation Properties of the large scale precipitation scheme 34.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name of the large scale precipitation parameterisation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_precipitation.hydrometeors') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "liquid rain" # "snow" # "hail" # "graupel" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 34.2. Hydrometeors Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Precipitating hydrometeors taken into account in the large scale precipitation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_cloud_microphysics.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 35. Microphysics Precipitation --&gt; Large Scale Cloud Microphysics Properties of the large scale cloud microphysics scheme 35.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name of the microphysics parameterisation scheme used for large scale clouds. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_cloud_microphysics.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mixed phase" # "cloud droplets" # "cloud ice" # "ice nucleation" # "water vapour deposition" # "effect of raindrops" # "effect of snow" # "effect of graupel" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 35.2. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Large scale cloud microphysics processes End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 36. Cloud Scheme Characteristics of the cloud scheme 36.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of the atmosphere cloud scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 36.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the cloud scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.atmos_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "atmosphere_radiation" # "atmosphere_microphysics_precipitation" # "atmosphere_turbulence_convection" # "atmosphere_gravity_waves" # "atmosphere_solar" # "atmosphere_volcano" # "atmosphere_cloud_simulator" # TODO - please enter value(s) """ Explanation: 36.3. Atmos Coupling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Atmosphere components that are linked to the cloud scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.uses_separate_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 36.4. Uses Separate Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Different cloud schemes for the different types of clouds (convective, stratiform and boundary layer) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "entrainment" # "detrainment" # "bulk cloud" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 36.5. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Processes included in the cloud scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.prognostic_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 36.6. Prognostic Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the cloud scheme a prognostic scheme? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.diagnostic_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 36.7. Diagnostic Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the cloud scheme a diagnostic scheme? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud amount" # "liquid" # "ice" # "rain" # "snow" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 36.8. Prognostic Variables Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List the prognostic variables used by the cloud scheme, if applicable. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.optical_cloud_properties.cloud_overlap_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "random" # "maximum" # "maximum-random" # "exponential" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 37. Cloud Scheme --&gt; Optical Cloud Properties Optical cloud properties 37.1. Cloud Overlap Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Method for taking into account overlapping of cloud layers End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.optical_cloud_properties.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37.2. Cloud Inhomogeneity Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Method for taking into account cloud inhomogeneity End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # TODO - please enter value(s) """ Explanation: 38. Cloud Scheme --&gt; Sub Grid Scale Water Distribution Sub-grid scale water distribution 38.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.function_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 38.2. Function Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution function name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.function_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 38.3. Function Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution function type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.convection_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "coupled with deep" # "coupled with shallow" # "not coupled with convection" # TODO - please enter value(s) """ Explanation: 38.4. Convection Coupling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Sub-grid scale water distribution coupling with convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # TODO - please enter value(s) """ Explanation: 39. Cloud Scheme --&gt; Sub Grid Scale Ice Distribution Sub-grid scale ice distribution 39.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.function_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 39.2. Function Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution function name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.function_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 39.3. Function Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution function type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.convection_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "coupled with deep" # "coupled with shallow" # "not coupled with convection" # TODO - please enter value(s) """ Explanation: 39.4. Convection Coupling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Sub-grid scale ice distribution coupling with convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 40. Observation Simulation Characteristics of observation simulation 40.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of observation simulator characteristics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.isscp_attributes.top_height_estimation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "no adjustment" # "IR brightness" # "visible optical depth" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 41. Observation Simulation --&gt; Isscp Attributes ISSCP Characteristics 41.1. Top Height Estimation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Cloud simulator ISSCP top height estimation methodUo End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.isscp_attributes.top_height_direction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "lowest altitude level" # "highest altitude level" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 41.2. Top Height Direction Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator ISSCP top height direction End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.run_configuration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Inline" # "Offline" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 42. Observation Simulation --&gt; Cosp Attributes CFMIP Observational Simulator Package attributes 42.1. Run Configuration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP run configuration End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_grid_points') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 42.2. Number Of Grid Points Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of grid points End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_sub_columns') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 42.3. Number Of Sub Columns Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of sub-cloumns used to simulate sub-grid variability End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 42.4. Number Of Levels Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of levels End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.frequency') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 43. Observation Simulation --&gt; Radar Inputs Characteristics of the cloud radar simulator 43.1. Frequency Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar frequency (Hz) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "surface" # "space borne" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 43.2. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.gas_absorption') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 43.3. Gas Absorption Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar uses gas absorption End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.effective_radius') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 43.4. Effective Radius Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar uses effective radius End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.lidar_inputs.ice_types') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "ice spheres" # "ice non-spherical" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 44. Observation Simulation --&gt; Lidar Inputs Characteristics of the cloud lidar simulator 44.1. Ice Types Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator lidar ice type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.lidar_inputs.overlap') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "max" # "random" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 44.2. Overlap Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Cloud simulator lidar overlap End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 45. Gravity Waves Characteristics of the parameterised gravity waves in the atmosphere, whether from orography or other sources. 45.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of gravity wave parameterisation in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.sponge_layer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Rayleigh friction" # "Diffusive sponge layer" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 45.2. Sponge Layer Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sponge layer in the upper levels in order to avoid gravity wave reflection at the top. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "continuous spectrum" # "discrete spectrum" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 45.3. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background wave distribution End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.subgrid_scale_orography') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "effect on drag" # "effect on lifting" # "enhanced topography" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 45.4. Subgrid Scale Orography Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Subgrid scale orography effects taken into account. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 46. Gravity Waves --&gt; Orographic Gravity Waves Gravity waves generated due to the presence of orography 46.1. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the orographic gravity wave scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.source_mechanisms') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "linear mountain waves" # "hydraulic jump" # "envelope orography" # "low level flow blocking" # "statistical sub-grid scale variance" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 46.2. Source Mechanisms Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Orographic gravity wave source mechanisms End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.calculation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "non-linear calculation" # "more than two cardinal directions" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 46.3. Calculation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Orographic gravity wave calculation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.propagation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "linear theory" # "non-linear theory" # "includes boundary layer ducting" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 46.4. Propagation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Orographic gravity wave propogation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.dissipation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "total wave" # "single wave" # "spectral" # "linear" # "wave saturation vs Richardson number" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 46.5. Dissipation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Orographic gravity wave dissipation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 47. Gravity Waves --&gt; Non Orographic Gravity Waves Gravity waves generated by non-orographic processes. 47.1. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the non-orographic gravity wave scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.source_mechanisms') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "convection" # "precipitation" # "background spectrum" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 47.2. Source Mechanisms Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Non-orographic gravity wave source mechanisms End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.calculation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "spatially dependent" # "temporally dependent" # TODO - please enter value(s) """ Explanation: 47.3. Calculation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Non-orographic gravity wave calculation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.propagation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "linear theory" # "non-linear theory" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 47.4. Propagation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Non-orographic gravity wave propogation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.dissipation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "total wave" # "single wave" # "spectral" # "linear" # "wave saturation vs Richardson number" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 47.5. Dissipation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Non-orographic gravity wave dissipation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 48. Solar Top of atmosphere solar insolation characteristics 48.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of solar insolation of the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_pathways.pathways') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "SW radiation" # "precipitating energetic particles" # "cosmic rays" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 49. Solar --&gt; Solar Pathways Pathways for solar forcing of the atmosphere 49.1. Pathways Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Pathways for the solar forcing of the atmosphere model domain End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed" # "transient" # TODO - please enter value(s) """ Explanation: 50. Solar --&gt; Solar Constant Solar constant and top of atmosphere insolation characteristics 50.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of the solar constant. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.fixed_value') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 50.2. Fixed Value Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If the solar constant is fixed, enter the value of the solar constant (W m-2). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.transient_characteristics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 50.3. Transient Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 solar constant transient characteristics (W m-2) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed" # "transient" # TODO - please enter value(s) """ Explanation: 51. Solar --&gt; Orbital Parameters Orbital parameters and top of atmosphere insolation characteristics 51.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of orbital parameters End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.fixed_reference_date') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 51.2. Fixed Reference Date Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Reference date for fixed orbital parameters (yyyy) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.transient_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 51.3. Transient Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of transient orbital parameters End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.computation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Berger 1978" # "Laskar 2004" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 51.4. Computation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method used for computing orbital parameters. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.insolation_ozone.solar_ozone_impact') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 52. Solar --&gt; Insolation Ozone Impact of solar insolation on stratospheric ozone 52.1. Solar Ozone Impact Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does top of atmosphere insolation impact on stratospheric ozone? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.volcanos.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 53. Volcanos Characteristics of the implementation of volcanoes 53.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of the implementation of volcanic effects in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.volcanos.volcanoes_treatment.volcanoes_implementation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "high frequency solar constant anomaly" # "stratospheric aerosols optical thickness" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 54. Volcanos --&gt; Volcanoes Treatment Treatment of volcanoes in the atmosphere 54.1. Volcanoes Implementation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How volcanic effects are modeled in the atmosphere. End of explanation """
alexandrnikitin/algorithm-sandbox
courses/DAT256x/Module01/01-06-Factorization.ipynb
mit
from random import randint x = randint(1,100) y = randint(1,100) (2*x*y**2)*(-3*x*y) == -6*x**2*y**3 """ Explanation: Factorization Factorization is the process of restating an expression as the product of two expressions (in other words, expressions multiplied together). For example, you can make the value 16 by performing the following multiplications of integer numbers: - 1 x 16 - 2 x 8 - 4 x 4 Another way of saying this is that 1, 2, 4, 8, and 16 are all factors of 16. Factors of Polynomial Expressions We can apply the same logic to polynomial expressions. For example, consider the following monomial expression: \begin{equation}-6x^{2}y^{3} \end{equation} You can get this value by performing the following multiplication: \begin{equation}(2xy^{2})(-3xy) \end{equation} Run the following Python code to test this with arbitrary x and y values: End of explanation """ from random import randint x = randint(1,100) y = randint(1,100) (x + 2)*(2*x**2 - 3*y + 2) == 2*x**3 + 4*x**2 - 3*x*y + 2*x - 6*y + 4 """ Explanation: So, we can say that 2xy<sup>2</sup> and -3xy are both factors of -6x<sup>2</sup>y<sup>3</sup>. This also applies to polynomials with more than one term. For example, consider the following expression: \begin{equation}(x + 2)(2x^{2} - 3y + 2) = 2x^{3} + 4x^{2} - 3xy + 2x - 6y + 4 \end{equation} Based on this, x+2 and 2x<sup>2</sup> - 3y + 2 are both factors of 2x<sup>3</sup> + 4x<sup>2</sup> - 3xy + 2x - 6y + 4. (and if you don't believe me, you can try this with random values for x and y with the following Python code): End of explanation """ from random import randint x = randint(1,100) y = randint(1,100) print((3*x*y)*(5*x) == 15*x**2*y) print((3*x*y)*(3*y**2) == 9*x*y**3) """ Explanation: Greatest Common Factor Of course, these may not be the only factors of -6x<sup>2</sup>y<sup>3</sup>, just as 8 and 2 are not the only factors of 16. Additionally, 2 and 8 aren't just factors of 16; they're factors of other numbers too - for example, they're both factors of 24 (because 2 x 12 = 24 and 8 x 3 = 24). Which leads us to the question, what is the highest number that is a factor of both 16 and 24? Well, let's look at all the numbers that multiply evenly into 12 and all the numbers that multiply evenly into 24: | 16 | 24 | |--------|--------| | 1 x 16 | 1 x 24 | | 2 x 8 | 2 x 12 | | | 3 x 8 | | 4 x 4 | 4 x 6 | The highest value that is a multiple of both 16 and 24 is 8, so 8 is the Greatest Common Factor (or GCF) of 16 and 24. OK, let's apply that logic to the following expressions: \begin{equation}15x^{2}y\;\;\;\;\;\;\;\;9xy^{3}\end{equation} So what's the greatest common factor of these two expressions? It helps to break the expressions into their consitituent components. Let's deal with the coefficients first; we have 15 and 9. The highest value that divides evenly into both of these is 3 (3 x 5 = 15 and 3 x 3 = 9). Now let's look at the x terms; we have x<sup>2</sup> and x. The highest value that divides evenly into both is these is x (x goes into x once and into x<sup>2</sup> x times). Finally, for our y terms, we have y and y<sup>3</sup>. The highest value that divides evenly into both is these is y (y goes into y once and into y<sup>3</sup> y&bull;y times). Putting all of that together, the GCF of both of our expression is: \begin{equation}3xy\end{equation} An easy shortcut to identifying the GCF of an expression that includes variables with exponentials is that it will always consist of: - The largest numeric factor of the numeric coefficients in the polynomial expressions (in this case 3) - The smallest exponential of each variable (in this case, x and y, which technically are x<sup>1</sup> and y<sup>1</sup>. You can check your answer by dividing the original expressions by the GCF to find the coefficent expressions for the GCF (in other words, how many times the GCF divides into the original expression). The result, when multiplied by the GCF will always produce the original expression. So in this case, we need to perform the following divisions: \begin{equation}\frac{15x^{2}y}{3xy}\;\;\;\;\;\;\;\;\frac{9xy^{3}}{3xy}\end{equation} These fractions simplify to 5x and 3y<sup>2</sup>, giving us the following calculations to prove our factorization: \begin{equation}3xy(5x) = 15x^{2}y\end{equation} \begin{equation}3xy(3y^{2}) = 9xy^{3}\end{equation} Let's try both of those in Python: End of explanation """ from random import randint x = randint(1,100) y = randint(1,100) (6*x + 15*y) == (3*(2*x) + 3*(5*y)) == (3*(2*x + 5*y)) """ Explanation: Distributing Factors Let's look at another example. Here is a binomial expression: \begin{equation}6x + 15y \end{equation} To factor this, we need to find an expression that divides equally into both of these expressions. In this case, we can use 3 to factor the coefficents, because 3 &bull; 2x = 6x and 3&bull; 5y = 15y, so we can write our original expression as: \begin{equation}6x + 15y = 3(2x) + 3(5y) \end{equation} Now, remember the distributive property? It enables us to multiply each term of an expression by the same factor to calculate the product of the expression multiplied by the factor. We can factor-out the common factor in this expression to distribute it like this: \begin{equation}6x + 15y = 3(2x) + 3(5y) = \mathbf{3(2x + 5y)} \end{equation} Let's prove to ourselves that these all evaluate to the same thing: End of explanation """ from random import randint x = randint(1,100) y = randint(1,100) (15*x**2*y + 9*x*y**3) == (3*x*y*(5*x + 3*y**2)) """ Explanation: For something a little more complex, let's return to our previous example. Suppose we want to add our original 15x<sup>2</sup>y and 9xy<sup>3</sup> expressions: \begin{equation}15x^{2}y + 9xy^{3}\end{equation} We've already calculated the common factor, so we know that: \begin{equation}3xy(5x) = 15x^{2}y\end{equation} \begin{equation}3xy(3y^{2}) = 9xy^{3}\end{equation} Now we can factor-out the common factor to produce a single expression: \begin{equation}15x^{2}y + 9xy^{3} = \mathbf{3xy(5x + 3y^{2})}\end{equation} And here's the Python test code: End of explanation """ from random import randint x = randint(1,100) (x**2 - 9) == (x - 3)*(x + 3) """ Explanation: So you might be wondering what's so great about being able to distribute the common factor like this. The answer is that it can often be useful to apply a common factor to multiple terms in order to solve seemingly complex problems. For example, consider this: \begin{equation}x^{2} + y^{2} + z^{2} = 127\end{equation} Now solve this equation: \begin{equation}a = 5x^{2} + 5y^{2} + 5z^{2}\end{equation} At first glance, this seems tricky because there are three unknown variables, and even though we know that their squares add up to 127, we don't know their individual values. However, we can distribute the common factor and apply what we do know. Let's restate the problem like this: \begin{equation}a = 5(x^{2} + y^{2} + z^{2})\end{equation} Now it becomes easier to solve, because we know that the expression in parenthesis is equal to 127, so actually our equation is: \begin{equation}a = 5(127)\end{equation} So a is 5 times 127, which is 635 Formulae for Factoring Squares There are some useful ways that you can employ factoring to deal with expressions that contain squared values (that is, values with an exponential of 2). Differences of Squares Consider the following expression: \begin{equation}x^{2} - 9\end{equation} The constant 9 is 3<sup>2</sup>, so we could rewrite this as: \begin{equation}x^{2} - 3^{2}\end{equation} Whenever you need to subtract one squared term from another, you can use an approach called the difference of squares, whereby we can factor a<sup>2</sup> - b<sup>2</sup> as (a - b)(a + b); so we can rewrite the expression as: \begin{equation}(x - 3)(x + 3)\end{equation} Run the code below to check this: End of explanation """ from random import randint a = randint(1,100) b = randint(1,100) a**2 + b**2 + (2*a*b) == (a + b)**2 """ Explanation: Perfect Squares A perfect square is a number multiplied by itself, for example 3 multipled by 3 is 9, so 9 is a perfect square. When working with equations, the ability to factor between polynomial expressions and binomial perfect square expressions can be a useful tool. For example, consider this expression: \begin{equation}x^{2} + 10x + 25\end{equation} We can use 5 as a common factor to rewrite this as: \begin{equation}(x + 5)(x + 5)\end{equation} So what happened here? Well, first we found a common factor for our coefficients: 5 goes into 10 twice and into 25 five times (in other words, squared). Then we just expressed this factoring as a multiplication of two identical binomials (x + 5)(x + 5). Remember the rule for multiplication of polynomials is to multiple each term in the first polynomial by each term in the second polynomial and then add the results; so you can do this to verify the factorization: x &bull; x = x<sup>2</sup> x &bull; 5 = 5x 5 &bull; x = 5x 5 &bull; 5 = 25 When you combine the two 5x terms we get back to our original expression of x<sup>2</sup> + 10x + 25. Now we have an expression multipled by itself; in other words, a perfect square. We can therefore rewrite this as: \begin{equation}(x + 5)^{2}\end{equation} Factorization of perfect squares is a useful technique, as you'll see when we start to tackle quadratic equations in the next section. In fact, it's so useful that it's worth memorizing its formula: \begin{equation}(a + b)^{2} = a^{2} + b^{2}+ 2ab \end{equation} In our example, the a terms is x and the b terms is 5, and in standard form, our equation x<sup>2</sup> + 10x + 25 is actually a<sup>2</sup> + 2ab + b<sup>2</sup>. The operations are all additions, so the order isn't actually important! Run the following code with random values for a and b to verify that the formula works: End of explanation """
tensorflow/docs-l10n
site/en-snapshot/agents/tutorials/1_dqn_tutorial.ipynb
apache-2.0
#@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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2021 The TF-Agents Authors. End of explanation """ !sudo apt-get update !sudo apt-get install -y xvfb ffmpeg freeglut3-dev !pip install 'imageio==2.4.0' !pip install pyvirtualdisplay !pip install tf-agents[reverb] !pip install pyglet from __future__ import absolute_import, division, print_function import base64 import imageio import IPython import matplotlib import matplotlib.pyplot as plt import numpy as np import PIL.Image import pyvirtualdisplay import reverb import tensorflow as tf from tf_agents.agents.dqn import dqn_agent from tf_agents.drivers import py_driver from tf_agents.environments import suite_gym from tf_agents.environments import tf_py_environment from tf_agents.eval import metric_utils from tf_agents.metrics import tf_metrics from tf_agents.networks import sequential from tf_agents.policies import py_tf_eager_policy from tf_agents.policies import random_tf_policy from tf_agents.replay_buffers import reverb_replay_buffer from tf_agents.replay_buffers import reverb_utils from tf_agents.trajectories import trajectory from tf_agents.specs import tensor_spec from tf_agents.utils import common # Set up a virtual display for rendering OpenAI gym environments. display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() tf.version.VERSION """ Explanation: Train a Deep Q Network with TF-Agents <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/agents/tutorials/1_dqn_tutorial"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png" /> View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/1_dqn_tutorial.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/agents/blob/master/docs/tutorials/1_dqn_tutorial.ipynb"> <img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/agents/docs/tutorials/1_dqn_tutorial.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> Introduction This example shows how to train a DQN (Deep Q Networks) agent on the Cartpole environment using the TF-Agents library. It will walk you through all the components in a Reinforcement Learning (RL) pipeline for training, evaluation and data collection. To run this code live, click the 'Run in Google Colab' link above. Setup If you haven't installed the following dependencies, run: End of explanation """ num_iterations = 20000 # @param {type:"integer"} initial_collect_steps = 100 # @param {type:"integer"} collect_steps_per_iteration = 1# @param {type:"integer"} replay_buffer_max_length = 100000 # @param {type:"integer"} batch_size = 64 # @param {type:"integer"} learning_rate = 1e-3 # @param {type:"number"} log_interval = 200 # @param {type:"integer"} num_eval_episodes = 10 # @param {type:"integer"} eval_interval = 1000 # @param {type:"integer"} """ Explanation: Hyperparameters End of explanation """ env_name = 'CartPole-v0' env = suite_gym.load(env_name) """ Explanation: Environment In Reinforcement Learning (RL), an environment represents the task or problem to be solved. Standard environments can be created in TF-Agents using tf_agents.environments suites. TF-Agents has suites for loading environments from sources such as the OpenAI Gym, Atari, and DM Control. Load the CartPole environment from the OpenAI Gym suite. End of explanation """ #@test {"skip": true} env.reset() PIL.Image.fromarray(env.render()) """ Explanation: You can render this environment to see how it looks. A free-swinging pole is attached to a cart. The goal is to move the cart right or left in order to keep the pole pointing up. End of explanation """ print('Observation Spec:') print(env.time_step_spec().observation) print('Reward Spec:') print(env.time_step_spec().reward) """ Explanation: The environment.step method takes an action in the environment and returns a TimeStep tuple containing the next observation of the environment and the reward for the action. The time_step_spec() method returns the specification for the TimeStep tuple. Its observation attribute shows the shape of observations, the data types, and the ranges of allowed values. The reward attribute shows the same details for the reward. End of explanation """ print('Action Spec:') print(env.action_spec()) """ Explanation: The action_spec() method returns the shape, data types, and allowed values of valid actions. End of explanation """ time_step = env.reset() print('Time step:') print(time_step) action = np.array(1, dtype=np.int32) next_time_step = env.step(action) print('Next time step:') print(next_time_step) """ Explanation: In the Cartpole environment: observation is an array of 4 floats: the position and velocity of the cart the angular position and velocity of the pole reward is a scalar float value action is a scalar integer with only two possible values: 0 — "move left" 1 — "move right" End of explanation """ train_py_env = suite_gym.load(env_name) eval_py_env = suite_gym.load(env_name) """ Explanation: Usually two environments are instantiated: one for training and one for evaluation. End of explanation """ train_env = tf_py_environment.TFPyEnvironment(train_py_env) eval_env = tf_py_environment.TFPyEnvironment(eval_py_env) """ Explanation: The Cartpole environment, like most environments, is written in pure Python. This is converted to TensorFlow using the TFPyEnvironment wrapper. The original environment's API uses Numpy arrays. The TFPyEnvironment converts these to Tensors to make it compatible with Tensorflow agents and policies. End of explanation """ fc_layer_params = (100, 50) action_tensor_spec = tensor_spec.from_spec(env.action_spec()) num_actions = action_tensor_spec.maximum - action_tensor_spec.minimum + 1 # Define a helper function to create Dense layers configured with the right # activation and kernel initializer. def dense_layer(num_units): return tf.keras.layers.Dense( num_units, activation=tf.keras.activations.relu, kernel_initializer=tf.keras.initializers.VarianceScaling( scale=2.0, mode='fan_in', distribution='truncated_normal')) # QNetwork consists of a sequence of Dense layers followed by a dense layer # with `num_actions` units to generate one q_value per available action as # its output. dense_layers = [dense_layer(num_units) for num_units in fc_layer_params] q_values_layer = tf.keras.layers.Dense( num_actions, activation=None, kernel_initializer=tf.keras.initializers.RandomUniform( minval=-0.03, maxval=0.03), bias_initializer=tf.keras.initializers.Constant(-0.2)) q_net = sequential.Sequential(dense_layers + [q_values_layer]) """ Explanation: Agent The algorithm used to solve an RL problem is represented by an Agent. TF-Agents provides standard implementations of a variety of Agents, including: DQN (used in this tutorial) REINFORCE DDPG TD3 PPO SAC The DQN agent can be used in any environment which has a discrete action space. At the heart of a DQN Agent is a QNetwork, a neural network model that can learn to predict QValues (expected returns) for all actions, given an observation from the environment. We will use tf_agents.networks. to create a QNetwork. The network will consist of a sequence of tf.keras.layers.Dense layers, where the final layer will have 1 output for each possible action. End of explanation """ optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) train_step_counter = tf.Variable(0) agent = dqn_agent.DqnAgent( train_env.time_step_spec(), train_env.action_spec(), q_network=q_net, optimizer=optimizer, td_errors_loss_fn=common.element_wise_squared_loss, train_step_counter=train_step_counter) agent.initialize() """ Explanation: Now use tf_agents.agents.dqn.dqn_agent to instantiate a DqnAgent. In addition to the time_step_spec, action_spec and the QNetwork, the agent constructor also requires an optimizer (in this case, AdamOptimizer), a loss function, and an integer step counter. End of explanation """ eval_policy = agent.policy collect_policy = agent.collect_policy """ Explanation: Policies A policy defines the way an agent acts in an environment. Typically, the goal of reinforcement learning is to train the underlying model until the policy produces the desired outcome. In this tutorial: The desired outcome is keeping the pole balanced upright over the cart. The policy returns an action (left or right) for each time_step observation. Agents contain two policies: agent.policy — The main policy that is used for evaluation and deployment. agent.collect_policy — A second policy that is used for data collection. End of explanation """ random_policy = random_tf_policy.RandomTFPolicy(train_env.time_step_spec(), train_env.action_spec()) """ Explanation: Policies can be created independently of agents. For example, use tf_agents.policies.random_tf_policy to create a policy which will randomly select an action for each time_step. End of explanation """ example_environment = tf_py_environment.TFPyEnvironment( suite_gym.load('CartPole-v0')) time_step = example_environment.reset() random_policy.action(time_step) """ Explanation: To get an action from a policy, call the policy.action(time_step) method. The time_step contains the observation from the environment. This method returns a PolicyStep, which is a named tuple with three components: action — the action to be taken (in this case, 0 or 1) state — used for stateful (that is, RNN-based) policies info — auxiliary data, such as log probabilities of actions End of explanation """ #@test {"skip": true} def compute_avg_return(environment, policy, num_episodes=10): total_return = 0.0 for _ in range(num_episodes): time_step = environment.reset() episode_return = 0.0 while not time_step.is_last(): action_step = policy.action(time_step) time_step = environment.step(action_step.action) episode_return += time_step.reward total_return += episode_return avg_return = total_return / num_episodes return avg_return.numpy()[0] # See also the metrics module for standard implementations of different metrics. # https://github.com/tensorflow/agents/tree/master/tf_agents/metrics """ Explanation: Metrics and Evaluation The most common metric used to evaluate a policy is the average return. The return is the sum of rewards obtained while running a policy in an environment for an episode. Several episodes are run, creating an average return. The following function computes the average return of a policy, given the policy, environment, and a number of episodes. End of explanation """ compute_avg_return(eval_env, random_policy, num_eval_episodes) """ Explanation: Running this computation on the random_policy shows a baseline performance in the environment. End of explanation """ table_name = 'uniform_table' replay_buffer_signature = tensor_spec.from_spec( agent.collect_data_spec) replay_buffer_signature = tensor_spec.add_outer_dim( replay_buffer_signature) table = reverb.Table( table_name, max_size=replay_buffer_max_length, sampler=reverb.selectors.Uniform(), remover=reverb.selectors.Fifo(), rate_limiter=reverb.rate_limiters.MinSize(1), signature=replay_buffer_signature) reverb_server = reverb.Server([table]) replay_buffer = reverb_replay_buffer.ReverbReplayBuffer( agent.collect_data_spec, table_name=table_name, sequence_length=2, local_server=reverb_server) rb_observer = reverb_utils.ReverbAddTrajectoryObserver( replay_buffer.py_client, table_name, sequence_length=2) """ Explanation: Replay Buffer In order to keep track of the data collected from the environment, we will use Reverb, an efficient, extensible, and easy-to-use replay system by Deepmind. It stores experience data when we collect trajectories and is consumed during training. This replay buffer is constructed using specs describing the tensors that are to be stored, which can be obtained from the agent using agent.collect_data_spec. End of explanation """ agent.collect_data_spec agent.collect_data_spec._fields """ Explanation: For most agents, collect_data_spec is a named tuple called Trajectory, containing the specs for observations, actions, rewards, and other items. End of explanation """ #@test {"skip": true} py_driver.PyDriver( env, py_tf_eager_policy.PyTFEagerPolicy( random_policy, use_tf_function=True), [rb_observer], max_steps=initial_collect_steps).run(train_py_env.reset()) """ Explanation: Data Collection Now execute the random policy in the environment for a few steps, recording the data in the replay buffer. Here we are using 'PyDriver' to run the experience collecting loop. You can learn more about TF Agents driver in our drivers tutorial. End of explanation """ # For the curious: # Uncomment to peel one of these off and inspect it. # iter(replay_buffer.as_dataset()).next() """ Explanation: The replay buffer is now a collection of Trajectories. End of explanation """ # Dataset generates trajectories with shape [Bx2x...] dataset = replay_buffer.as_dataset( num_parallel_calls=3, sample_batch_size=batch_size, num_steps=2).prefetch(3) dataset iterator = iter(dataset) print(iterator) # For the curious: # Uncomment to see what the dataset iterator is feeding to the agent. # Compare this representation of replay data # to the collection of individual trajectories shown earlier. # iterator.next() """ Explanation: The agent needs access to the replay buffer. This is provided by creating an iterable tf.data.Dataset pipeline which will feed data to the agent. Each row of the replay buffer only stores a single observation step. But since the DQN Agent needs both the current and next observation to compute the loss, the dataset pipeline will sample two adjacent rows for each item in the batch (num_steps=2). This dataset is also optimized by running parallel calls and prefetching data. End of explanation """ #@test {"skip": true} try: %%time except: pass # (Optional) Optimize by wrapping some of the code in a graph using TF function. agent.train = common.function(agent.train) # Reset the train step. agent.train_step_counter.assign(0) # Evaluate the agent's policy once before training. avg_return = compute_avg_return(eval_env, agent.policy, num_eval_episodes) returns = [avg_return] # Reset the environment. time_step = train_py_env.reset() # Create a driver to collect experience. collect_driver = py_driver.PyDriver( env, py_tf_eager_policy.PyTFEagerPolicy( agent.collect_policy, use_tf_function=True), [rb_observer], max_steps=collect_steps_per_iteration) for _ in range(num_iterations): # Collect a few steps and save to the replay buffer. time_step, _ = collect_driver.run(time_step) # Sample a batch of data from the buffer and update the agent's network. experience, unused_info = next(iterator) train_loss = agent.train(experience).loss step = agent.train_step_counter.numpy() if step % log_interval == 0: print('step = {0}: loss = {1}'.format(step, train_loss)) if step % eval_interval == 0: avg_return = compute_avg_return(eval_env, agent.policy, num_eval_episodes) print('step = {0}: Average Return = {1}'.format(step, avg_return)) returns.append(avg_return) """ Explanation: Training the agent Two things must happen during the training loop: collect data from the environment use that data to train the agent's neural network(s) This example also periodicially evaluates the policy and prints the current score. The following will take ~5 minutes to run. End of explanation """ #@test {"skip": true} iterations = range(0, num_iterations + 1, eval_interval) plt.plot(iterations, returns) plt.ylabel('Average Return') plt.xlabel('Iterations') plt.ylim(top=250) """ Explanation: Visualization Plots Use matplotlib.pyplot to chart how the policy improved during training. One iteration of Cartpole-v0 consists of 200 time steps. The environment gives a reward of +1 for each step the pole stays up, so the maximum return for one episode is 200. The charts shows the return increasing towards that maximum each time it is evaluated during training. (It may be a little unstable and not increase monotonically each time.) End of explanation """ def embed_mp4(filename): """Embeds an mp4 file in the notebook.""" video = open(filename,'rb').read() b64 = base64.b64encode(video) tag = ''' <video width="640" height="480" controls> <source src="data:video/mp4;base64,{0}" type="video/mp4"> Your browser does not support the video tag. </video>'''.format(b64.decode()) return IPython.display.HTML(tag) """ Explanation: Videos Charts are nice. But more exciting is seeing an agent actually performing a task in an environment. First, create a function to embed videos in the notebook. End of explanation """ def create_policy_eval_video(policy, filename, num_episodes=5, fps=30): filename = filename + ".mp4" with imageio.get_writer(filename, fps=fps) as video: for _ in range(num_episodes): time_step = eval_env.reset() video.append_data(eval_py_env.render()) while not time_step.is_last(): action_step = policy.action(time_step) time_step = eval_env.step(action_step.action) video.append_data(eval_py_env.render()) return embed_mp4(filename) create_policy_eval_video(agent.policy, "trained-agent") """ Explanation: Now iterate through a few episodes of the Cartpole game with the agent. The underlying Python environment (the one "inside" the TensorFlow environment wrapper) provides a render() method, which outputs an image of the environment state. These can be collected into a video. End of explanation """ create_policy_eval_video(random_policy, "random-agent") """ Explanation: For fun, compare the trained agent (above) to an agent moving randomly. (It does not do as well.) End of explanation """
shawger/uc-dand
P3/Wrangle OpenStreetMap Data.ipynb
gpl-3.0
#Creates and uses sample file if True USE_SAMPLE = False k = 10 inputFile = "calgary_canada.osm" sampleFile = "calgary_canada_sample.osm" if USE_SAMPLE: import createTestFile createTestFile.createTestFile(inputFile,sampleFile,k) print '%s created from %s for testing.' % (sampleFile,inputFile) # For the rest of the project the sample file can be used instead of the orginal file inputFile = sampleFile """ Explanation: Calgary Coffee Shops By: Nick Shaw Date: 2016-07-13 Project: P3 from the Udacity Data Analyst Nano Degree Introduction This report details the investigation of coffee shops in Calgary Canada using data from OpenStreetMap.org. Specifically, the following questions are answered: What does the map data look like? Size of file, number of elements, number of nodes, number of ways and number of unique users. Where does coffee shop rank as an cuisine? What users have added the most kind of coffee shops? What are the most common coffee shop chains? What are the names, phone numbers and postal codes of all the coffee shops. The investigation will be conducted using python and mongodb. For the python, not all code will be shown in this notebook and can be found in the file osmToMongo.py in the project folder. The project folder is hosted on github here. Source Data The data was downloaded with a pre-made xml osm file from MapZen. Here is the link. In the project folder, the file is calgary_canada.osm. For testing, a sample of calgary_canada.osm was made using createTestFile.py, which was provided as part of this project. The resulting file is calgary_canada_sample.osm End of explanation """ import osmToMongo from pymongo import MongoClient data = osmToMongo.process_map(inputFile) osmToMongo.loadIntoMongoDB(data) """ Explanation: Load from xml to mongobd Load the data from xml and convert to json so it can be loaded into mongodb. osmToMongo.py handles the conversion to json as well as the cleaning of the data. End of explanation """ client = MongoClient('localhost', 27017) db = client.p3 """ Explanation: While converting the data, 2 kinds of cleaning will happen. Pre-processing: This happens before data is converted to json. Mainly, it is making consistent and valid keys. Post-processing: Once an element is converted to JSON, it will be cleaned according to different rules. Pre-processing Cleaning To start, the following rules were applied. 'created' index for elements. Elements have attributes related to their creation ("version", "changeset", "timestamp", "user", "uid"). These are combined into a sub-document with the index 'created' 'pos' index. For elements with lat and lon (latitude and longitude) attributes, they will be combined into an float list (2 elements) and given the index of 'pos'. Valid keys. Elements have sub elements called 'tags'. Each tag has a key (k) and value (v). Before changing to json the keys need to be checked. Keys can only have lowercase letter or an _. For tags with a single ':', a sub-document is created with the string before the ':' being the key in the main document and string after the ':' being the key in the sub-document. Address is a special. There are records with addr:<something>, and instead of using addr for the key, address will be used. Applying these rules, 15289 tags were dropped (pre_process_log_v0.txt). Here is a sample: Bad tag key, not added: geobase:datasetName Bad tag key, not added: geobase:acquisitionTechnique Bad tag key, not added: geobase:datasetName Bad tag key, not added: geobase:acquisitionTechnique Bad tag key, not added: catmp-RoadID Bad tag key, not added: catmp-RoadID Bad tag key, not added: catmp-RoadID Tags with keys like geobase:acquisitionTechnique and geobase:datasetName were being dropped because they had a capital letter. These appear to be using a naming standard that separates words using capital letters to start words. I added logic to instead use _ to divide these words. For example, datasetName becomes dataset_name. I added code to replace - with _ and to make all words lower cases (after _ were added where applicable) Regex code to find lowerCase letters followed be upper case letters, then mode to make the replacement ```python lowerUpper = re.compile(r'([a-z])([A-Z])') def replaceLowerUpper(match): lower = str(match.group(1)) upper = str(match.group(2)) return lower + "" + upper.lower() ``` Code inside shape_element (in osmToMongo.py), which converts an xml element to a json document. k is the key for a tag. ```python k = re.sub(lowerUpper,replaceLowerUpper,k) k = k.lower() k = str.replace(k,"-","") ``` After adding the code, there were 1181 dropped tags due to key name (pre_process_log_v2.txt). Here is a sample: Bad tag key, not added: addr:housenumber:first:right Bad tag key, not added: name_1 Bad tag key, not added: geobase:route_name1:en Bad tag key, not added: addr:housenumber:first:right Bad tag key, not added: addr:housenumber:last:right Bad tag key, not added: addr:housenumber:first:right Bad tag key, not added: addr:housenumber:last:right Post-processing Cleaning I wanted to focus on a few things to help with my questions. Make sure things are properly classified as coffee shops. Make sure phone numbers are in a standard format Make sure postal codes are in a standard format Note: For auditing, I added some new fields. In practice, I would take this code (or comment it out) once I was satisfied with the data, as there is no need for it once the data is clean. For the auditing of the data I will run some queries on the db using the python mongodb driver. Connect to the database with the driver first. End of explanation """ cafePipeline = [{"$match" : {"amenity":"cafe"}}] coffeePipeline = [{"$match" : {"cuisine" :"coffee_shop"}}] cafeNoCoffeePipeline = [{"$match" : {"$and" : [{"amenity":"cafe"},{"cuisine" :{"$ne":"coffee_shop"}}] }}] coffeeNoCafePipeline = [{"$match" : {"$and" : [{"amenity": {"$ne":"cafe"}},{"cuisine" :"coffee_shop"}] }}] print "Places with cafe as amenity: %d" % len(list(db.maps.aggregate(cafePipeline))) print "Places with coffee_shop as cuisine: %d" % len(list(db.maps.aggregate(coffeePipeline))) print "Places with cafe as amenity but not coffee_shop as cuisine: %d" % len(list(db.maps.aggregate(cafeNoCoffeePipeline))) print "Places with coffee_shop as cuisine but not cafe as amenity: %d" % len(list(db.maps.aggregate(coffeeNoCafePipeline))) """ Explanation: Coffee Shop Classification For coffee shops there are different ways of classification. The 'amenity' will be 'cafe' and/or the 'cuisine' will be 'coffee_shop'. Not all are the same. Here is what I mean. End of explanation """ #Query all documents with something in the 'phone_format' field, group by the phone format, #count and sort by the number in each format formatPipeline = [{"$match" : {"phone_format":{"$exists":{"$ne":"null"}}}}, {"$group": { "_id": "$phone_format", "total" : {"$sum":1}}}, {"$sort": { "total": -1}}] results = list(db.maps.aggregate(formatPipeline)) for r in results: print '%s : %d' % (r['_id'],r['total']) """ Explanation: To start with, running this code on the full dataset I got (the output changed after adding cleaning logic): Places with cafe as amenity: 190 Places with coffee_shop as cuisine: 78 Places with cafe as amenity but not coffee_shop as cuisine: 121 Places with coffee_shop as cuisine but not cafe as amenity: 9 To clean this up, I want all coffee shops to look the same. To do this I decided that I would make it so all cafe's have the cuisine coffee_shop and from here on, to use the field, 'cuisine' to to the research. The follow code is included in the code for cleaning a document: ```python if('amenity' in d and d['amenity'] == 'cafe'): d['cuisine'] = 'coffee_shop' ``` After adding this code, the output for the 'Coffee Audit' was: Places with cafe as amenity: 190 Places with coffee_shop as cuisine: 199 Places with cafe as amenity but not coffee_shop as cuisine: 0 Places with coffee_shop as cuisine but not cafe as amenity: 9 Now {'cuisine' : 'coffee_shop'} includes all the coffee shops. Phone Numbers Check the format of the phone numbers, pick a standard (the most used maybe) then convert all to that standard. During the clean stage, add a field to all documents that has the format of the number. D is digit Eg (###) ###-#### Code in cleanDocument: python if('phone' in d): d['phone_format'] = re.sub('[0-9]', '#', d['phone']) print d['phone_format'] Now run a query to see the common formats. End of explanation """ formatPipeline = [{"$match" : {"address.post_format":{"$exists":{"$ne":"null"}}}}, {"$group": { "_id": "$address.post_format", "total" : {"$sum":1}}}, {"$sort": { "total": -1}}] results = list(db.maps.aggregate(formatPipeline)) for r in results: print '%s : %d' % (r['_id'],r['total']) """ Explanation: From the first run of this, here are the first 5 results: ``` +#-###-###-#### : 135 (###) ###-#### : 47 +# ### ### #### : 25 -###-#### : 21 (###)###-#### : 10 ``` I will use the first format as a template and put the rest into that format. From my knowledge of Canadian numbers there are 10 digits, not including the country code. If the country code is not included, it is assumed to be 1. All the digits will be extracted (in order), then put into the correct format. The code for cleaning is: ```python if('phone' in d and not phoneNumber.match(d['phone'])): #The phone number with nothing but digits stripped = re.sub('[^0-9]', '', d['phone']) #The number should be of length 10 or 11 #If it is 10, add a 1 to the start if(len(stripped) == 10): stripped = '1' + stripped #Put into the correct format +#-###-###-#### if(len(stripped) == 11): d['phone'] = '+' + stripped[0] \ + '-' + stripped[1:4] \ + '-' + stripped[4:7] \ + '-' + stripped[7:11] ``` and the regex phoneNumber is: python phoneNumber = re.compile(r'^[+][0-9][-][0-9]{3}[-][0-9]{3}[-][0-9]{4}$') Now the results of the phone number query are: ``` +#-###-###-#### : 277 -###-#### ext ## : 1 ``` Much better. For more improvement, figure out a format for extensions. Postal Codes Check the format of the postal code, and make sure all addresses are using postal codes of the same (most common) format. End of explanation """ #Use the collstats fucntion to get the file size and nunmber of elemements stats = db.command("collstats", "maps") total = stats['count'] size = stats['storageSize'] #Use the count function to get the amount of each type nodes = db.maps.find({'type':'node'}).count() ways = db.maps.find({'type':'way'}).count() #Find the unique users query #Group by users, then group and count the results. pipeline = [{"$group": { "_id": "$created.user", "total" : {"$sum":1}}}, {"$group": { "_id": "null", "total" : {"$sum":1}}}] results = list(db.maps.aggregate(pipeline)) uniqueUsers = results[0]['total'] print "\nData Summary" print "==================================" print "Storage Size: %d bytes" % size print "Total number of elements: %d " % total print "Total number of nodes: %d " % nodes print "Total number of ways: %d " % ways print "Total number of unique users: %d " % uniqueUsers """ Explanation: From the first run: ``` U#U #U# : 1112 U#U#U# : 48 UU U#U #U# : 2 U#U #U# : 2 U#U-#U# : 1 U#U#U#;U#U #U# : 1 -###-#### : 1 : 1 U#U : 1 ``` Not so bad. Some of these just need to be thrown away. The only thing acceptable is (without punctuation or spaces is) L#L#L#. Anything without 3 numbers and 3 letters not in that order is not valid. The following code was added to clean the postal codes: ```python if ('address' in d \ and 'postcode' in d['address'] \ and not postCode.match(d['address']['postcode'])): #Remove everything but letter and numbers. Make it upper case stripped = re.sub('[^0-9A-Za-z]', '', d['address']['postcode']).upper() #Check if the stripped (only letters and numbers) post code is valid #Drop it if it isn't if(postCodeStripped.match(stripped)): d['address']['postcode'] = stripped[0:3] + " " + stripped[3:] else: d['address'].pop("postcode", None) ``` Using the regex's: ```python postCode = re.compile(r'^[A-Z][0-9][A-Z][\s][0-9][A-Z][0-9]$') postCodeStripped = re.compile(r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$') ``` After the cleaning code was added this is the output of the audit: U#U #U# : 1163 Good. That's better. Analysis Okay. The data is loaded into the database and cleaned (kind of). Now to run some queries to answer my original questions. What does the map data look like? Size of file, number of elements, number of nodes, number of ways and number of unique users. Answered using the following queries: End of explanation """ #Query how many non null cuisines sorted pipeline = [{"$match" : {"cuisine":{"$exists":{"$ne":"null"}}}}, {"$group": { "_id": "$cuisine", "total" : {"$sum":1}}}, {"$sort": { "total": -1}}] results = list(db.maps.aggregate(pipeline)) print '\nTop 10 cuisine types' i = 0 for result in results: if i < 10: print '%s:%s' % (result['_id'],result['total']) else: break i += 1 """ Explanation: Where does coffee shop rank as an cuisine? Answered using the following query End of explanation """ #Find nodes where cuisine is coffee_shop, then group and count the users (where there is a user) then sort pipeline = [{"$match" : {"cuisine":"coffee_shop"}}, {"$match" : {"created.user":{"$exists":{"$ne":"null"}}}}, {"$group": { "_id": "$created.user", "total" : {"$sum":1}}}, {"$sort": { "total": -1}}] results = list(db.maps.aggregate(pipeline)) print '\nTop 5 coffee lovers' i = 0 for result in results: if i < 5: print '%s:%s' % (result['_id'],result['total']) else: break i += 1 """ Explanation: Coffee shops seem to be the most popular cuisine added. What users have added the most kind of coffee shops? Who likes coffee the most? Let's find out! End of explanation """ #Find nodes where user is AKC, then group and count the cuisines (where there is a user) then sort pipeline = [{"$match" : {"created.user":"AKC"}}, {"$match" : {"cuisine":{"$exists":{"$ne":"null"}}}}, {"$group": { "_id": "$cuisine", "total" : {"$sum":1}}}, {"$sort": { "total": -1}}] results = list(db.maps.aggregate(pipeline)) for result in results: print '%s:%s' % (result['_id'],result['total']) """ Explanation: AKC seems to like coffee a lot. What else do they like? End of explanation """ #Find all coffee shops with names. Group by name and report and sort the count pipeline = [{"$match" : {"cuisine":"coffee_shop"}}, {"$match" : {"name":{"$exists":{"$ne":"null"}}}}, {"$group": { "_id": "$name", "total" : {"$sum":1}}}, {"$sort": { "total": -1}}] results = list(db.maps.aggregate(pipeline)) print '\nTop 10 coffee shops' i = 0 for result in results: if i < 10: print '%s:%s' % (result['_id'],result['total']) else: break i += 1 """ Explanation: I guess AKC just likes adding things to the openmap. Good for them. What are the most common coffee shop chains? Group by the name where cuisine is coffee_shop End of explanation """ #Find node where cuisine is coffee_shop and that have name, address and postal code pipeline = [{"$match" : {"cuisine":"coffee_shop"}}, {"$match" : {"$and": [{"name":{"$exists":{"$ne":"null"}}}, {"phone":{"$exists":{"$ne":"null"}}}, {"address.postcode":{"$exists":{"$ne":"null"}}}]}}] results = list(db.maps.aggregate(pipeline)) for r in results: print "name: %s, phone: %s, postal code: %s" % (r['name'],r['phone'],r['address']['postcode']) """ Explanation: Tim Hortons wins! Wait, there are Starbucks and Starbucks Coffee. They should be the same, and then it would win. In fact there are a few on this list that need cleaning. Good Earth Cafe and Good Earth Coffeehouse and Bakery for example. Cleaning this up would be a future improvement (unless you are a big Timmy's fan). Probably a good way to attack this would be to create a renaming dict, and use it to clean the names of coffee shops (and other kinds of things). Creating the dict would likely be a manual process... What are the names, phone numbers and postal codes of all the coffee shops? End of explanation """
DigitalSlideArchive/HistomicsTK
docs/examples/polygon_merger_from_tiled_masks.ipynb
apache-2.0
import os CWD = os.getcwd() import os import girder_client from pandas import read_csv from histomicstk.annotations_and_masks.polygon_merger import Polygon_merger from histomicstk.annotations_and_masks.masks_to_annotations_handler import ( get_annotation_documents_from_contours, ) """ Explanation: Merging annotations from tiled arrays Overview: This notebook describes how to merge annotations generated by tiled analysis of a whole-slide image. Since tiled analysis is carried out on small tiles, the annotations produced by image segmentation algorithms will be disjoint at the tile boundaries, prohibiting analysis of large structures that span multiple tiles. The example presented below addresses the case where the annotations are stored in an array format that preserves the spatial organization of tiles. This scenario arises when iterating through the columns and rows of a tiled representation of a whole-slide image. Analysis of the organized array format is faster and preferred since the interfaces where annotations need to be merged are known. In cases where where the annotations to be merged do not come from tiled analysis, or where the tile results are not organized, an alternative method based on R-trees provides a slightly slower solution. This extends on some of the work described in Amgad et al, 2019: Mohamed Amgad, Habiba Elfandy, Hagar Hussein, ..., Jonathan Beezley, Deepak R Chittajallu, David Manthey, David A Gutman, Lee A D Cooper, Structured crowdsourcing enables convolutional segmentation of histology images, Bioinformatics, 2019, btz083 This is a sample result: Implementation summary In the tiled array approach the tiles must be rectangular and unrotated. The algorithm used merges polygons in coordinate space so that almost-arbitrarily large structures can be handled without encountering memory issues. The algorithm works as follows: Extract contours from the given masks using functionality from the masks_to_annotations_handler.py, making sure to account for contour offset so that all coordinates are relative to whole-slide image frame. Identify contours that touch tile interfaces. Identify shared edges between tiles. For each shared edge, find contours that neighbor each other (using bounding box location) and verify that they should be paired using shapely. Using 4-connectivity link all pairs of contours that are to be merged. Use morphologic processing to dilate and fill gaps in the linked pairs and then erode to generate the final merged contour. This initial steps ensures that the number of comparisons made is &lt;&lt; n^2. This is important since algorithm complexity plays a key role as whole slide images may contain tens of thousands of annotated structures. Where to look? histomicstk/ |_annotations_and_masks/ |_polygon_merger.py |_tests/ |_ test_polygon_merger.py |_ test_annotations_to_masks_handler.py End of explanation """ APIURL = 'http://candygram.neurology.emory.edu:8080/api/v1/' SAMPLE_SLIDE_ID = '5d586d76bd4404c6b1f286ae' gc = girder_client.GirderClient(apiUrl=APIURL) gc.authenticate(interactive=True) # gc.authenticate(apiKey='kri19nTIGOkWH01TbzRqfohaaDWb6kPecRqGmemb') # read GTCodes dataframe PTESTS_PATH = os.path.join(CWD, '..', '..', 'tests') GTCODE_PATH = os.path.join(PTESTS_PATH, 'test_files', 'sample_GTcodes.csv') GTCodes_df = read_csv(GTCODE_PATH) GTCodes_df.index = GTCodes_df.loc[:, 'group'] # This is where masks for adjacent rois are saved MASK_LOADPATH = os.path.join( PTESTS_PATH,'test_files', 'annotations_and_masks', 'polygon_merger_roi_masks') maskpaths = [ os.path.join(MASK_LOADPATH, j) for j in os.listdir(MASK_LOADPATH) if j.endswith('.png')] """ Explanation: 1. Connect girder client and set parameters End of explanation """ print(Polygon_merger.__doc__) print(Polygon_merger.__init__.__doc__) print(Polygon_merger.run.__doc__) """ Explanation: 2. Polygon merger The Polygon_merger() is the top level function for performing the merging. End of explanation """ GTCodes_df.head() """ Explanation: Required arguments for initialization Ground truth codes file This contains the ground truth codes and information dataframe. This is a dataframe that is indexed by the annotation group name and has the following columns: group: group name of annotation (string), eg. "mostly_tumor" GT_code: int, desired ground truth code (in the mask) Pixels of this value belong to corresponding group (class) color: str, rgb format. eg. rgb(255,0,0). NOTE: Zero pixels have special meaning and do NOT encode specific ground truth class. Instead, they simply mean 'Outside ROI' and should be IGNORED during model training or evaluation. End of explanation """ [os.path.split(j)[1] for j in maskpaths[:5]] """ Explanation: maskpaths These are absolute paths for the masks generated by tiled analysis to be used. End of explanation """ print(Polygon_merger.set_roi_bboxes.__doc__) """ Explanation: Note that the pattern _left-123_ and _top-123_ is assumed to encode the x and y offset of the mask at base magnification. If you prefer some other convention, you will need to manually provide the parameter roi_offsets to the method Polygon_merger.set_roi_bboxes. End of explanation """ pm = Polygon_merger( maskpaths=maskpaths, GTCodes_df=GTCodes_df, discard_nonenclosed_background=True, verbose=1, monitorPrefix='test') contours_df = pm.run() """ Explanation: 3. Initialize and run the merger To keep things clean we discard background contours (in this case, stroma) that are now enclosed with another contour. See docs for masks_to_annotations_handler.py if this is confusing. This is purely aesthetic. End of explanation """ contours_df.head() """ Explanation: This is the result End of explanation """ # deleting existing annotations in target slide (if any) existing_annotations = gc.get('/annotation/item/' + SAMPLE_SLIDE_ID) for ann in existing_annotations: gc.delete('/annotation/%s' % ann['_id']) # get list of annotation documents annotation_docs = get_annotation_documents_from_contours( contours_df.copy(), separate_docs_by_group=True, docnamePrefix='test', verbose=False, monitorPrefix=SAMPLE_SLIDE_ID + ": annotation docs") # post annotations to slide -- make sure it posts without errors for annotation_doc in annotation_docs: resp = gc.post( "/annotation?itemId=" + SAMPLE_SLIDE_ID, json=annotation_doc) """ Explanation: 4. Visualize results on HistomicsTK End of explanation """
GoogleCloudPlatform/ai-notebooks-extended
dataproc-hub-example/build/infrastructure-builder/mig/files/gcs_working_folder/examples/Python/bigquery/Visualizing BigQuery public data.ipynb
apache-2.0
%%bigquery SELECT source_year AS year, COUNT(is_male) AS birth_count FROM `bigquery-public-data.samples.natality` GROUP BY year ORDER BY year DESC LIMIT 15 """ Explanation: Vizualizing BigQuery data in a Jupyter notebook BigQuery is a petabyte-scale analytics data warehouse that you can use to run SQL queries over vast amounts of data in near realtime. Data visualization tools can help you make sense of your BigQuery data and help you analyze the data interactively. You can use visualization tools to help you identify trends, respond to them, and make predictions using your data. In this tutorial, you use the BigQuery Python client library and pandas in a Jupyter notebook to visualize data in the BigQuery natality sample table. Using Jupyter magics to query BigQuery data The BigQuery Python client library provides a magic command that allows you to run queries with minimal code. The BigQuery client library provides a cell magic, %%bigquery. The %%bigquery magic runs a SQL query and returns the results as a pandas DataFrame. The following cell executes a query of the BigQuery natality public dataset and returns the total births by year. End of explanation """ %%bigquery total_births SELECT source_year AS year, COUNT(is_male) AS birth_count FROM `bigquery-public-data.samples.natality` GROUP BY year ORDER BY year DESC LIMIT 15 """ Explanation: The following command to runs the same query, but this time the results are saved to a variable. The variable name, total_births, is given as an argument to the %%bigquery. The results can then be used for further analysis and visualization. End of explanation """ total_births.plot(kind='bar', x='year', y='birth_count'); """ Explanation: The next cell uses the pandas DataFrame.plot method to visualize the query results as a bar chart. See the pandas documentation to learn more about data visualization with pandas. End of explanation """ %%bigquery births_by_weekday SELECT wday, SUM(CASE WHEN is_male THEN 1 ELSE 0 END) AS male_births, SUM(CASE WHEN is_male THEN 0 ELSE 1 END) AS female_births FROM `bigquery-public-data.samples.natality` WHERE wday IS NOT NULL GROUP BY wday ORDER BY wday ASC """ Explanation: Run the following query to retrieve the number of births by weekday. Because the wday (weekday) field allows null values, the query excludes records where wday is null. End of explanation """ births_by_weekday.plot(x='wday'); """ Explanation: Visualize the query results using a line chart. End of explanation """ from google.cloud import bigquery client = bigquery.Client() """ Explanation: Using Python to query BigQuery data Magic commands allow you to use minimal syntax to interact with BigQuery. Behind the scenes, %%bigquery uses the BigQuery Python client library to run the given query, convert the results to a pandas Dataframe, optionally save the results to a variable, and finally display the results. Using the BigQuery Python client library directly instead of through magic commands gives you more control over your queries and allows for more complex configurations. The library's integrations with pandas enable you to combine the power of declarative SQL with imperative code (Python) to perform interesting data analysis, visualization, and transformation tasks. To use the BigQuery Python client library, start by importing the library and initializing a client. The BigQuery client is used to send and receive messages from the BigQuery API. End of explanation """ sql = """ SELECT plurality, COUNT(1) AS count, year FROM `bigquery-public-data.samples.natality` WHERE NOT IS_NAN(plurality) AND plurality > 1 GROUP BY plurality, year ORDER BY count DESC """ df = client.query(sql).to_dataframe() df.head() """ Explanation: Use the Client.query method to run a query. Execute the following cell to run a query to retrieve the annual count of plural births by plurality (2 for twins, 3 for triplets, etc.). End of explanation """ pivot_table = df.pivot(index='year', columns='plurality', values='count') pivot_table.plot(kind='bar', stacked=True, figsize=(15, 7)); """ Explanation: To chart the query results in your DataFrame, run the following cell to pivot the data and create a stacked bar chart of the count of plural births over time. End of explanation """ sql = """ SELECT gestation_weeks, COUNT(1) AS count FROM `bigquery-public-data.samples.natality` WHERE NOT IS_NAN(gestation_weeks) AND gestation_weeks <> 99 GROUP BY gestation_weeks ORDER BY gestation_weeks """ df = client.query(sql).to_dataframe() """ Explanation: Run the following query to retrieve the count of births by the number of gestation weeks. End of explanation """ ax = df.plot(kind='bar', x='gestation_weeks', y='count', figsize=(15,7)) ax.set_title('Count of Births by Gestation Weeks') ax.set_xlabel('Gestation Weeks') ax.set_ylabel('Count'); """ Explanation: Finally, chart the query results in your DataFrame. End of explanation """
Xilinx/PYNQ
boards/Pynq-Z1/base/notebooks/pmod/pmod_dac_adc.ipynb
bsd-3-clause
from pynq.overlays.base import BaseOverlay from pynq.lib import Pmod_ADC, Pmod_DAC """ Explanation: DAC-ADC Pmod Examples using Matplotlib and Widget Contents Pmod DAC-ADC Feedback Tracking the IO Error Error plot with Matplotlib Widget controlled plot Pmod DAC-ADC Feedback This example shows how to use the PmodDA4 DAC and the PmodAD2 ADC on the board, using the board's two Pmod interfaces. The notebook then compares the DAC output to the ADC input and tracks the errors. The errors are plotted using Matplotlib and an XKCD version of the plot is produced (for fun). Finally a slider widget is introduced to control the number of samples displayed in the error plot. Note: The output of the DAC (pin A) must be connected with a wire to the input of the ADC (V1 input). 1. Import hardware libraries and classes End of explanation """ ol = BaseOverlay("base.bit") """ Explanation: 2. Program the ZYNQ PL End of explanation """ dac = Pmod_DAC(ol.PMODB) adc = Pmod_ADC(ol.PMODA) """ Explanation: 3. Instantiate the Pmod peripherals as Python objects End of explanation """ dac.write(0.35) sample = adc.read() print(sample) """ Explanation: 4. Write to DAC, read from ADC, print result End of explanation """ from math import ceil from time import sleep import numpy as np import matplotlib.pyplot as plt from pynq.lib import Pmod_ADC, Pmod_DAC from pynq.overlays.base import BaseOverlay ol = BaseOverlay("base.bit") dac = Pmod_DAC(ol.PMODB) adc = Pmod_ADC(ol.PMODA) delay = 0.0 values = np.linspace(0, 2, 20) samples = [] for value in values: dac.write(value) sleep(delay) sample = adc.read() samples.append(sample[0]) print('Value written: {:4.2f}\tSample read: {:4.2f}\tError: {:+4.4f}'. format(value, sample[0], sample[0]-value)) """ Explanation: Contents Tracking the IO Error Report DAC-ADC Pmod Loopback Measurement Error. End of explanation """ %matplotlib inline X = np.arange(len(values)) plt.bar(X + 0.0, values, facecolor='blue', edgecolor='white', width=0.5, label="Written_to_DAC") plt.bar(X + 0.25, samples, facecolor='red', edgecolor='white', width=0.5, label="Read_from_ADC") plt.title('DAC-ADC Linearity') plt.xlabel('Sample_number') plt.ylabel('Volts') plt.legend(loc='upper left', frameon=False) plt.show() """ Explanation: Contents Error plot with Matplotlib This example shows plots in notebook (rather than in separate window). End of explanation """ from math import ceil from time import sleep import numpy as np import matplotlib.pyplot as plt %matplotlib inline from ipywidgets import interact import ipywidgets as widgets ol = BaseOverlay("base.bit") dac = Pmod_DAC(ol.PMODB) adc = Pmod_ADC(ol.PMODA) def capture_samples(nmbr_of_samples): delay = 0.0 values = np.linspace(0, 2, nmbr_of_samples) samples = [] for value in values: dac.write(value) sleep(delay) sample = adc.read() samples.append(sample[0]) X = np.arange(nmbr_of_samples) plt.bar(X + 0.0, values[:nmbr_of_samples+1], facecolor='blue', edgecolor='white', width=0.5, label="Written_to_DAC") plt.bar(X + 0.25, samples[:nmbr_of_samples+1], facecolor='red', edgecolor='white', width=0.5, label="Read_from_ADC") plt.title('DAC-ADC Linearity') plt.xlabel('Sample_number') plt.ylabel('Volts') plt.legend(loc='upper left', frameon=False) plt.show() _ = interact(capture_samples, nmbr_of_samples=widgets.IntSlider( min=5, max=30, step=5, value=10, continuous_update=False)) """ Explanation: Contents Widget controlled plot In this example, we extend the IO plot with a slider widget to control the number of samples appearing in the output plot. We use the ipwidgets library and the simple interact() method to launch a slider bar. The interact function (ipywidgets.interact) automatically creates user interface (UI) controls for exploring code and data interactively. It is the easiest way to get started using IPython’s widgets. For more details see Using ipwidgets interact() End of explanation """
ProfessorKazarinoff/staticsite
content/code/sympy/sympy_solving_equations-polymer-density-problem.ipynb
gpl-3.0
from sympy import symbols, nonlinsolve """ Explanation: Sympy is a Python package used for solving equations using symbolic math. Let's solve the following problem with SymPy. Given: The density of two different polymer samples $\rho_1$ and $\rho_2$ are measured. $$ \rho_1 = 0.904 \ g/cm^3 $$ $$ \rho_2 = 0.895 \ g/cm^3 $$ The percent crystalinity of the two samples ($\%c_1 $ and $\%c_2$) is known. $$ \%c_1 = 62.8 \% $$ $$ \%c_2 = 54.4 \% $$ The percent crystalinity of a polymer sample is related to the density of 100% amorphus regions ($\rho_a$) and 100% crystaline regions ($\rho_c$) according to: $$ \%crystallinity = \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% $$ Find: Find the density of 100% amorphus regions ($\rho_a$) and the density of 100% crystaline regions ($\rho_c$) for this polymer. Solution: There are a couple functions we need from Sympy. We'll need the symbols function to create our symbolic math variables and we need the nonlinsolve function to solve a system of non-linear equations. End of explanation """ pc, pa, p1, p2, c1, c2 = symbols('pc pa p1 p2 c1 c2') """ Explanation: We need to define six different symbols: $$\rho_c, \rho_a, \rho_1, \rho_2, c_1, c_2$$ End of explanation """ expr1 = ( (pc*(p1-pa) ) / (p1*(pc-pa)) - c1) expr2 = ( (pc*(p2-pa) ) / (p2*(pc-pa)) - c2) """ Explanation: Next we'll create two expressions for our two equations. We can subtract the %crystallinity from the left side of the equation to set the equation to zero. $$ \%crystallinity = \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% $$ $$ \frac{ \rho_c(\rho_s - \rho_a) }{\rho_s(\rho_c - \rho_a) } \times 100 \% - \%crystallinity = 0 $$ Sub in $\rho_s = \rho_1$ and $\rho_s = \rho_2$ to each of the expressions. End of explanation """ expr1 = expr1.subs(p1, 0.904) expr1 = expr1.subs(c1, 0.628) expr1 """ Explanation: Now we'll substitue in the values of $\rho_1 = 0.904$ and $c_1 = 0.628$ into our first expression. End of explanation """ expr2 = expr2.subs(p2, 0.895) expr2 = expr2.subs(c2, 0.544) expr2 """ Explanation: Now we'll substitue our the values of $\rho_2 = 0.895$ and $c_2 = 0.544$ into our second expression. End of explanation """ nonlinsolve([expr1,expr2],[pa,pc]) """ Explanation: To solve the two equations for the to unknows $\rho_a$ and $\rho_b$, use SymPy's nonlinsolve() function. Pass in a list of the two expressions and followed by a list of the two variables to solve for. End of explanation """ sol = nonlinsolve([expr1,expr2],[pa,pc]) type(sol) sol.args sol.args[0] sol.args[0][0] pa = sol.args[0][0] pc = sol.args[0][1] print(f' Density of 100% amorphous polymer, pa = {round(pa,2)} g/cm3') print(f' Density of 100% crystaline polymer, pc = {round(pc,2)} g/cm3') """ Explanation: We see that the value of $\rho_a = 0.840789$ and $\rho_c = 0.94613431$. The solution is a SymPy FiniteSet object. To pull the values of $\rho_a$ and $\rho_c$ out of the FiniteSet, use the syntax sol.args[0][&lt;var num&gt;]. End of explanation """
sidaw/mompy
polynomial_optimization.ipynb
mit
# we are dependent on numpy, sympy and cvxopt. import numpy as np import cvxopt import mompy as mp # just some basic settings and setup mp.cvxsolvers.options['show_progress'] = False from IPython.display import display, Markdown, Math, display_markdown sp.init_printing() def print_problem(obj, constraints = None, moment_constraints = None): display_markdown(mp.problem_to_str(obj,constraints,moment_constraints, False), raw=True) """ Explanation: $\newcommand{\Re}{\mathbb{R}} \newcommand{\EE}{\mathbb{E}}$ Polynomial Optimization and the Generalized Moment Problem Polynomial Optimization The polynomial optimization problem is to $ \begin{align} \text{minimize} \quad &f(x)\ \text{subject to} \quad &g_i(x) \geq 0,\quad i=1,\ldots,N \end{align} $ where $x \in \Re^d$ and $f(x), g_i(x) \in \Re[x]$ are polynomials. We implement the techniques developed by Parrilo et al. and Lasserre et al. where this problem is relaxed to a semidefinite program. In the first part of this worksheet, we show how to solve polynomial optimization problems using mompy where several example problems in the GloptiPoly paper and the solution extraction paper are reproduced. In the second part, we give the simplest example of estimating a mixture model by solving the Generalized Moment Problem (GMP). Some extensions can be found in the extra examples worksheet. This software was used for our paper Estimating mixture models via mixtures of polynomials where we look at some more elaborate settings for the mixture model problem. Other implementation for solving the polynomial optimization problem / and Generalized Moment Problem are GloptiPoly and SOSTOOLS in MATLAB, and ncpol2sdpa in python described here. End of explanation """ x,y = sp.symbols('x,y') f = x**2 + y**2 gs = [x+y>=4, x+y<=4] print_problem(f, gs) sol = mp.solvers.solve_GMP(f, gs) mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 1) """ Explanation: 1) First example End of explanation """ x1,x2 = sp.symbols('x1:3') f = 4*x1**2+x1*x2-4*x2**2-2.1*x1**4+4*x2**4+x1**6/3 print_problem(f) sol = mp.solvers.solve_GMP(f, rounds=1) mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 2) """ Explanation: 2) Unconstrained optimization: the six hump camel back function A plot of this function can be found at library of simutations. MATLAB got the solution $x^ = [0.0898 -0.7127]$ and corresponding optimal values of $f(x^) = -1.0316$ End of explanation """ x1,x2,x3 = sp.symbols('x1:4') f = -(x1 - 1)**2 - (x1 - x2)**2 - (x2 - 3)**2 gs = [1 - (x1 - 1)**2 >= 0, 1 - (x1 - x2)**2 >= 0, 1 - (x2 - 3)**2 >= 0] print_problem(f, gs) sol = mp.solvers.solve_GMP(f, gs, rounds=4) mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 3) """ Explanation: 3) Multiple rounds Generally more rounds are needed to get the correct solutions. End of explanation """ x1,x2,x3 = sp.symbols('x1:4') f = -2*x1 + x2 - x3 gs = [0<=x1, x1<=2, x2>=0, x3>=0, x3<=3, x1+x2+x3<=4, 3*x2+x3<=6,\ 24-20*x1+9*x2-13*x3+4*x1**2 - 4*x1*x2+4*x1*x3+2*x2**2-2*x2*x3+2*x3**2>=0]; hs = []; print_problem(f, gs) sol = mp.solvers.solve_GMP(f, gs, hs, rounds=4) print mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 2) """ Explanation: Yet another example End of explanation """ x1,x2 = sp.symbols('x1:3') f = x1**2 * x2**2 * (x1**2 + x2**2 - 1) + 1./27 print_problem(f) sol = mp.solvers.solve_GMP(f, rounds=7) print mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 4, maxdeg=3) """ Explanation: 4) Motzkin polynomial The Motzkin polynomial is non-negative, but cannot be expressed in sum of squares. It attains global minimum of 0 at $|x_1| = |x_2| = \sqrt{3}/3$ (4 points). The first few relaxations are unbounded and might take a while for cvxopt to realize this. End of explanation """ beta = sp.symbols('beta') beta0 = [1,2]; pi0 = [0.5,0.5] hs = [beta**m - (pi0[0]*beta0[0]**m+pi0[1]*beta0[1]**m) for m in range(1,5)] f = sum([beta**(2*i) for i in range(3)]) # note that hs are the LHS of h==0, whereas gs are sympy inequalities print_problem(f, None, hs) sol = mp.solvers.solve_GMP(f, None, hs) print mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 2, tol = 1e-3) """ Explanation: Generalized Moment Problem (GMP) The GMP is to $ \begin{align} \text{minimize} \quad &f(x)\ \text{subject to} \quad &g_i(x) \geq 0,\quad i=1,\ldots,N\ \quad &\mathcal{L}(h_j(x)) \geq 0,\quad j=1,\ldots,M \end{align} $ where $x \in \Re^d$ and $f(x), g_i(x), h_j(x) \in \Re[x]$ are polynomials, and $\mathcal{L}(\cdot): \Re[x] \mapsto \Re$ is a linear functional. Loosely speaking, we would like a measure $\mu$ to exist so that $\mathcal{L}(h) = \int h\ d\mu$. For details see: Jean B. Lasserre, 2011, Moments, Positive Polynomials and Their Applications Jean B. Lasserre, 2008, A semidefinite programming approach to the generalized problem of moments Estimating mixtures of exponential distributions We are interested in estimating the parameters of a mixture model from some observed moments, possibly with constraints on the parameters. Suppose that we have a mixture of 2 exponential distributions with density function $p(x; \beta) \sim \exp(-x/\beta)/\beta$ in for $x \in [0,\infty)$. Suppose that $\pi_1 = \pi_2 = 0.5$ and $\beta_1 = 1, \beta_2 = 2$. We are allowed to observe moments of the data $\EE[X^n] = {n!}(\pi_1 \beta_1^n + \pi_2 \beta_2^n)$ for $n=1,\ldots,6$. For more details on estimating mixture model using this method, see our paper Estimating mixture models via mixtures of polynomials and see the extra examples worksheet for another easy example on mixture of Gaussians. End of explanation """ gs=[beta>=1] f = sum([beta**(2*i) for i in range(3)]) hs_sub = hs[0:2] print_problem(f, gs, hs_sub) sol = mp.solvers.solve_GMP(f, gs, hs_sub) print mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 2, tol = 1e-3) """ Explanation: Now we try to solve the problem with insufficient moment conditions, but extra constraints on the parameters themselves. End of explanation """
jarvis-fga/Projetos
Problema 2/alexandre/Second Project ML.ipynb
mit
import pandas as pd import numpy as np import matplotlib.pyplot as plt """ Explanation: 1. Descrição do Problema A empresa Amazon deseja obter um sistema inteligente para processar os comentários de seus clientes sobre os seus produtos, podendo classificar tais comentários dentre as categorias: positivo ou negativo. Para isso ela disponibiliza três bases de dados com sentenças rotuladas. 2. Dados Os dados estão organizados em sentença e rótulo, sendo 0 negativo e 1 positivo As bases são provenientes dos seguintes sites: imdb.com amazon.com yelp.com 3. Solução End of explanation """ X_1 = pd.read_csv('amazon_cells_labelled.txt', sep="\t", usecols=[0], header=None) Y_1 = pd.read_csv('amazon_cells_labelled.txt', sep="\t", usecols=[1], header=None) X_2 = pd.read_csv('imdb_labelled.txt', sep="\t", usecols=[0], header=None) Y_2 = pd.read_csv('imdb_labelled.txt', sep="\t", usecols=[1], header=None) X_3 = pd.read_csv('yelp_labelled.txt', sep="\t", usecols=[0], header=None) Y_3 = pd.read_csv('yelp_labelled.txt', sep="\t", usecols=[1], header=None) X = np.concatenate((X_1.values[:,0], X_2.values[:,0]), axis=0) Y = np.concatenate((Y_1.values[:,0], Y_2.values[:,0]), axis=0) X = np.concatenate((X, X_3.values[:,0]), axis=0) Y = np.concatenate((Y, Y_3.values[:,0]), axis=0) """ Explanation: Importing Data End of explanation """ # Treating Sentences allSentences = [] charsSplit = "\\`*_{}[]()>#+-.!$,:&?" charsRemove = ".,-_;\"\'" for x in X : for c in charsSplit: x = x.replace(c, ' '+ c +' ') for c in charsRemove: x = x.replace(c, '') allSentences.append(x.lower() ) allWords = [] for x in allSentences : allWords.extend(x.split(" ")) allWords = list(set(allWords)) allWords.sort() """ Explanation: Creating Dictionary Na variável "charsRemove" são indicados os caracteres a serem removidos do input. Todas as palavras são transformadas para lower case e os caracteres indesejados são removidos. Na variável "allWords", são armazenadas todas as palavras a serem utilizadas. End of explanation """ positiveCount = [0] * len(allWords) negativeCount = [0] * len(allWords) sentenceNumber = 0 for sentenceNumber, sentence in enumerate(allSentences) : for word in sentence.split(" "): wordIndex = allWords.index(word) if (Y[sentenceNumber] == 1): positiveCount[wordIndex] = positiveCount[wordIndex] + 1 else: negativeCount[wordIndex] = negativeCount[wordIndex] + 1 allCount = np.array(positiveCount) + np.array(negativeCount) probPositive = np.divide(positiveCount, allCount) len(allWords) allWordsFiltered = np.array(allWords) len(allWordsFiltered) index_to_remove = [] for index, prob in enumerate(probPositive): if not((prob <= 0.48) or (prob >= 0.52)): index_to_remove.append(index) a = 1 allWordsFiltered = np.delete(allWordsFiltered, index_to_remove) """ Explanation: Removing Words / Features Aqui são removidas as palavras que aparecem menos de 52% como positivo ou como negativo. End of explanation """ allWords = np.array(allWordsFiltered).tolist() X = [] for x in allSentences : sentenceV = [0] * len(allWords) words = x.split(" ") for w in words : try: index = allWords.index(w) sentenceV[index] = 1 #sentenceV[index] + 1 except ValueError: pass X.append(sentenceV) """ Explanation: Sentence to Vector Cria-se um vetor para cada sentença utilizando o dicionário elaborado como base. Este vetor dependerá das palavras contidas em cada uma das sentenças. Cada ocorrência de palavra acarretará em igualarmos o índice associado a 1 (testou-se também incrementando esse valor, mas não foi viável). End of explanation """ from sklearn.cross_validation import cross_val_score cross_val_k = 10 from sklearn.naive_bayes import MultinomialNB clf1 = MultinomialNB() from sklearn.neighbors import KNeighborsClassifier clf2 = KNeighborsClassifier(n_neighbors=5) from sklearn.linear_model import LogisticRegression clf3 = LogisticRegression(penalty='l2', C=1.0) from sklearn.ensemble import VotingClassifier eclf = VotingClassifier(estimators=[('mnb', clf1), ('knn', clf2), ('lr', clf3)], voting='soft', weights=[3,2,2]) accuracy = cross_val_score(eclf, X, Y, cv=cross_val_k, scoring='accuracy').mean() print('Precisão: ', accuracy) """ Explanation: Classifier Model Foram testados uma série de métodos para realizar a classificação dos comentários entre positivo e negativo. O melhor resultado obtido foi utilizando Ensemble, combinando: - Multinomial Naive Bayes (peso 3) - KNN (peso 2) - Logistic Regression (peso 2) End of explanation """
waltervh/BornAgain-tutorial
old/python/tutorial.ipynb
gpl-3.0
from __future__ import print_function """ Explanation: Introduction to Python Useful links BornAgain: http://bornagainproject.org BornAgain tutorial: https://github.com/scgmlz/BornAgain-tutorial Python official tutorial: https://docs.python.org/3/tutorial/ Anaconda Python: https://www.continuum.io/ PyCharm IDE: https://www.jetbrains.com/pycharm/ Note that BornAgain Win/Mac requires Python 2.7 Clone the BornAgain Tutorial Repository From command line: bash git clone https://github.com/scgmlz/BornAgain-tutorial.git Windows/Mac: can also use Github Desktop. Power Users: Build BornAgain with Python 3 Support bash git clone https://github.com/scgmlz/BornAgain.git mkdir build; cd build cmake .. -DCMAKE_BUILD_TYPE=Release -DBORNAGAIN_USE_PYTHON3=ON make &amp;&amp; make install Verify your Python Environment Check the Python version: $ python --version Python 3.5.2 Check for numpy and matplotlib $ python -c "import numpy" $ python -c "import matplotlib" Check for BornAgain Python module $ python -c "import bornagain" Running Python Direct from command line: $ python -c "print 'hello, world'" hello, world Run script from command line: $ echo "print 'hello, world'" &gt; hello.py $ python hello.py hello, world Default interactive interpreter: ``` $ python x = 5 x * x 25 ``` IPython interactive interpreter: $ ipython In [1]: x = 5 In [2]: x * x Out [2]: 25 IPython interactive notebook: $ ipython notebook Jupyter interactive notebook: $ jupyter notebook Run within PyCharm IDE Notebook support is included by default with Anaconda, and can be installed as an optional package on most Linux distros. Python 2.7 vs. 3.5 Compatibility There are a few important differences between Python 2.7 and 3.5. The line below is used to ensure that this notebook remains compatible with both. There is a list of differences between Python 2.7 and 3.5 near the end of this notebook. End of explanation """ # scratch area """ Explanation: Basic Data Types Python has many data types, e.g. * numeric: int, float, complex * string * boolean values, i.e. true and false * sequences: list, tuple * dict Variables are declared via assignment: python x = 5 End of explanation """ # scratch area """ Explanation: Numeric Types Python numeric types are similar to those in other languages such as C/C++. python x = 5 # int x = 10**100 # long (2.7) or int (3.5) x = 3.141592 # float x = 1.0j # complex Note: ordinary machine types can be accessed/manipulated through the ctypes module. End of explanation """ # scratch area """ Explanation: Arithmetic Operations python 3 + 2 # addition 3 - 2 # subtraction 3 * 2 # multiplication 3 ** 2 # exponentiation 3 / 2 # division (warning: int (2.7) or float (3.5)) 3 % 2 # modulus End of explanation """ # scratch area """ Explanation: Exercise Use the Python interpreter to perform some basic arithemetic. Strings python x = "hello" # string enclosed with double quotes y = 'world' # string enclosed with single quotes x + ' ' + y # string concatenation via + "{} + {} = {}".format(5 , 6, 5+6) # string formatting End of explanation """ # scratch area """ Explanation: Lists python x = [1, 2, 3] # initialize list x[1] = 0 # modify element x.append(4) # append to end x.extend([5, 6]) # extend x[3:5] # slice End of explanation """ # scratch area """ Explanation: Tuples Tuples are similar to lists, but are immutable: python x = (1, 2, 3) # initialize a tuple with () x[0] = 4 # will result in error End of explanation """ # scratch area """ Explanation: List Comprehension Comprehension provides a convenient way to create new lists: python [ i for i in range (5) ] # result: [0, 1, 2, 3, 4] [ i**2 for i in range (5) ] # result: [0, 1, 4, 9, 16] the_list = [5, 2, 6, 1] [ i**2 for i in the_list ] # result [25, 4, 36, 1] End of explanation """ # scratch area """ Explanation: Exercise Create a list of floating point numbers and then create a second list which contains the squares of the entries of teh fist list Boolean Values and Comparisons Boolean types take the values True or False. The result of a comparison operator is boolean. python 5 &lt; 6 # evalutes to True 5 &gt;= 6 # evaluates to False 5 == 6 # evaluates to False Logical operations: python True and False # False True or False # True not True # False True ^ False # True (exclusive or) End of explanation """ # scratch area """ Explanation: Functions Functions are defined with def: python def hello(): print 'hello, world' Note: Python uses indentation to denote blocks of code, rather than braces {} as in many other languages. It is common to use either 4 spaces or 2 spaces to indent. It doesn't matter, as long as you are consistent. Use the return keyword for a function which returns a value: python def square(x): return x**2 End of explanation """ for i in range(10): print(i**2) """ Explanation: Loops and Flow Control For loop: End of explanation """ for i in ['hello', 'world']: print(i) """ Explanation: It is also possible to use for..in to iterate through elements of a list: End of explanation """ i = 0 while i < 10: print(i**2) i = i + 1 """ Explanation: While loops have the form while condition: End of explanation """ for i in range(10): if i == 3: continue if i == 7: break print(i) """ Explanation: The keywords break and continue can be used for flow control inside a loop * continue: skip to the next iteration of the loop * break: jump out of the loop entirely End of explanation """ # scratch area """ Explanation: Use the keywords if, elif, else for branching python if 5 &gt; 6: # never reached pass elif 1 &gt; 2: # reached pass else: # never reached pass End of explanation """ # scratch area """ Explanation: Exercise Write a function fib(n) which returns the nth Fibonacci number. The Fibonacci numbers are defined by * fib(0) = fib(1) = 1 * fib(n) = fib(n-1) + fib(n-2) for n &gt;= 2. Exercise ”Write a program that prints the numbers from 1 to 100. But for multiples of three print Fizz instead of the number and for the multiples of five print Buzz. For numbers which are multiples of both three and five print FizzBuzz.” http://wiki.c2.com/?FizzBuzzTest End of explanation """ import math print(math.pi) print(math.sin(math.pi/2.0)) """ Explanation: Modules Load external modules (built-in or user-defined) via import: End of explanation """ import math as m print(m.pi) """ Explanation: Rename modules with as: End of explanation """ from math import pi, sin print(sin(pi/2.0)) # scratch area """ Explanation: Load specific functions or submodules: End of explanation """ import my_module my_module.do_something() """ Explanation: User-defined Modules Any code written in a separate file (with .py extension) can be imported as a module. Suppose we have a script my_module.py which defines a function do_something(). Then we can call it as End of explanation """ # scratch area """ Explanation: Exercise Implement your FizzBuzz solution as a function called FizzBuzz() in a module called fizzbuzz. Check that it works by importing it and calling FizzBuzz() in a separate script. End of explanation """ import numpy as np x = np.array([1, 2, 3, 4]) print(x.sum()) print(x.mean()) """ Explanation: numpy numpy is a module used for numerical calculation. The main data type is numpy.array, which is a multidimensional array of numbers (integer, float, complex). End of explanation """ x = np.array([1, 2, 3, 4]) y = np.array([5, 6, 7, 8]) print(x + y) print(x * y) print(x / y) """ Explanation: The basic arithmetic operations work elementwise on numpy arrays: End of explanation """ x = np.array([1, 2, 3, 4]) print(np.sin(x)) print(np.log(x)) # scratch area """ Explanation: It is also possible to call functions on numpy arrays: End of explanation """ print(np.zeros(4)) print(np.ones(3)) print(np.linspace(-1, 1, num=4)) print(np.random.rand(2)) # scratch area """ Explanation: Generating numpy Arrays numpy arrays can be generated with zeros, ones, linspace, and rand: End of explanation """ import numpy as np from matplotlib import pyplot as plt x = np.linspace(-3.14, 3.14, num=100) y = np.sin(x) plt.plot(x, y) plt.xlabel('x values') plt.ylabel('y') plt.title('y=sin(x)') plt.show() """ Explanation: Plotting with matplotlib We use matplotlib.pyplot for plotting: End of explanation """ x = np.linspace(-10, 10, num=100) y1 = np.sin(x) y2 = np.cos(x) y3 = np.arctan(x) plt.plot(x, y1, x, y2, x, y3) plt.show() """ Explanation: Exercise Create plots the following functions * f(x) = log(x) * f(x) = sqrt(x) * f(x) = x**2 * f(x) = log(1 + x**2) * anything else you might find interesting or challenging Combining Plots Plots can be combined using addition: End of explanation """ x = np.linspace (-1, 1, num =100) y = np.linspace (-1, 1, num =100) xx, yy = np.meshgrid (x, y) z = np.sin(xx**2 + yy**2 + yy) plt.pcolormesh(x, y, z, shading = 'gouraud') plt.show() """ Explanation: todo array manipulation routines numpy.flipud, fliplr, transpose, rot90, flatten, ravel Colormap Plots Plot color maps with pcolormesh: End of explanation """ plt.imshow(z, aspect='auto') plt.show() """ Explanation: Or with imshow: End of explanation """ plt.imshow(np.flipud(z), aspect='auto') plt.show() # scratch area """ Explanation: Note that the image is flipped because images start from top left and go to bottom right. We can fix this with flipud: End of explanation """ from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm %matplotlib inline fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(xx, yy, z, rstride=5, cstride=5, cmap=cm.coolwarm, linewidth=1, antialiased=True) plt.show() """ Explanation: 3D Plots End of explanation """ %matplotlib inline fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_wireframe(xx, yy, z, rstride=5, cstride=5, antialiased=True) plt.show() """ Explanation: 3D Wireframe Plot End of explanation """ # scratch """ Explanation: Gallery of matplotlib Plots See http://matplotlib.org/gallery.html Plotting Exercise Consider the function f(x, y) = exp(x + 1.0j*y) for −4 ≤ x, y ≤ 4. Create colormap and 3d plots of the magnitude, real, and imaginary parts of f. End of explanation """ x = np.linspace(-2, 2, num=100) y = np.linspace(-2, 2, num=100) result = np.flipud(np.array([[u*v for u in x] for v in y])) fig = plt.figure() plt.imshow(result, extent=[x.min(), x.max(), y.min(), y.max()], aspect='auto') plt.show() """ Explanation: Plotting Images End of explanation """ class SomeClass: def __init__ (self, x): self.x = x def doSomething(self): print("my x value is {}".format(self.x)) obj = SomeClass(5) obj.doSomething() # scratch area """ Explanation: Classes Classes can be used to package data and methods together: End of explanation """ class SomeOtherClass (SomeClass): def __init__ (self, x, y): SomeClass.__init__ (self, x) self.y = y def doSomethingElse(self): print("my y value is {}".format(self.y)) other_obj = SomeOtherClass(5, 6) other_obj.doSomething() other_obj.doSomethingElse() """ Explanation: Inheritance Classes can be derived from others: End of explanation """ print('The type of obj is {}'.format(type(obj))) print('The type of other_obj is {}'.format(type(other_obj))) print('obj is instance of SomeClass? {}'.format(isinstance(obj, SomeClass))) print('obj is instance of SomeOtherClass? {}'.format(isinstance(obj, SomeOtherClass))) print('other_obj is instance of SomeClass? {}'.format(isinstance(obj, SomeClass))) print('other_obj is instance of SomeOtherClass? {}'.format( isinstance(obj, SomeOtherClass))) # scratch area """ Explanation: Polymorphism An instance of a derived class is automatically an instance of its base class: End of explanation """ # todo """ Explanation: Exercise todo End of explanation """
roebius/deeplearning_keras2
nbs2/babi-memnn.ipynb
apache-2.0
%matplotlib inline import importlib, utils2; importlib.reload(utils2) from utils2 import * np.set_printoptions(4) cfg = K.tf.ConfigProto(gpu_options={'allow_growth': True}) K.set_session(K.tf.Session(config=cfg)) """ Explanation: Babi End to End MemNN End of explanation """ def tokenize(sent): return [x.strip() for x in re.split('(\W+)?', sent) if x.strip()] """ Explanation: A memory network is a network that can retain information; it can be trained on a structured story and will learn how to answer questions about said story. This notebook contains an implementation of an end-to-end memory network trained on the Babi tasks dataset. Create datasets Code from this section is mainly taken from the babi-memnn example in the keras repo. Popular Science Slate The Babi dataset is a collection of tasks (or stories) that detail events in a particular format. At the end of each task is a question with a labelled answer. This section shows how to construct the dataset from the raw data. End of explanation """ def parse_stories(lines): data = [] story = [] for line in lines: line = line.decode('utf-8').strip() nid, line = line.split(' ', 1) if int(nid) == 1: story = [] if '\t' in line: q, a, supporting = line.split('\t') q = tokenize(q) substory = None substory = [[str(i)+":"]+x for i,x in enumerate(story) if x] data.append((substory, q, a)) story.append('') else: story.append(tokenize(line)) return data """ Explanation: This parser formats the story into a time-order labelled sequence of sentences, followed by the question and the labelled answer. End of explanation """ path = get_file('babi-tasks-v1-2.tar.gz', origin='https://s3.amazonaws.com/text-datasets/babi_tasks_1-20_v1-2.tar.gz') tar = tarfile.open(path) challenges = { # QA1 with 10,000 samples 'single_supporting_fact_10k': 'tasks_1-20_v1-2/en-10k/qa1_single-supporting-fact_{}.txt', # QA2 with 10,000 samples 'two_supporting_facts_10k': 'tasks_1-20_v1-2/en-10k/qa2_two-supporting-facts_{}.txt', 'two_supporting_facts_1k': 'tasks_1-20_v1-2/en/qa2_two-supporting-facts_{}.txt', } challenge_type = 'single_supporting_fact_10k' # challenge_type = 'two_supporting_facts_10k' challenge = challenges[challenge_type] def get_stories(f): data = parse_stories(f.readlines()) return [(story, q, answer) for story, q, answer in data] train_stories = get_stories(tar.extractfile(challenge.format('train'))) test_stories = get_stories(tar.extractfile(challenge.format('test'))) """ Explanation: Next we download and parse the data set. End of explanation """ stories = train_stories + test_stories story_maxlen = max((len(s) for x, _, _ in stories for s in x)) story_maxsents = max((len(x) for x, _, _ in stories)) query_maxlen = max(len(x) for _, x, _ in stories) def do_flatten(el): return isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)) def flatten(l): for el in l: if do_flatten(el): yield from flatten(el) else: yield el """ Explanation: Here we calculate upper bounds for things like words in sentence, sentences in a story, etc. for the corpus, which will be useful later. End of explanation """ vocab = sorted(set(flatten(stories))) vocab.insert(0, '<PAD>') vocab_size = len(vocab) story_maxsents, vocab_size, story_maxlen, query_maxlen, len(train_stories), len(test_stories) """ Explanation: Create vocabulary of corpus and find size, including a padding element. End of explanation """ test_stories[534] """ Explanation: Now the dataset is in the correct format. Each task in the dataset contains a list of tokenized sentences ordered in time, followed by a question about the story with a given answer. In the example below, we go can backward through the sentences to find the answer to the question "Where is Daniel?" as sentence 12, the last sentence to mention Daniel. This task structure is called a "one supporting fact" structure, which means that we only need to find one sentence in the story to answer our question. End of explanation """ word_idx = dict((c, i) for i, c in enumerate(vocab)) """ Explanation: Create an index mapping for the vocabulary. End of explanation """ def vectorize_stories(data, word_idx, story_maxlen, query_maxlen): X = []; Xq = []; Y = [] for story, query, answer in data: x = [[word_idx[w] for w in s] for s in story] xq = [word_idx[w] for w in query] y = [word_idx[answer]] X.append(x); Xq.append(xq); Y.append(y) return ([pad_sequences(x, maxlen=story_maxlen) for x in X], pad_sequences(Xq, maxlen=query_maxlen), np.array(Y)) inputs_train, queries_train, answers_train = vectorize_stories(train_stories, word_idx, story_maxlen, query_maxlen) inputs_test, queries_test, answers_test = vectorize_stories(test_stories, word_idx, story_maxlen, query_maxlen) def stack_inputs(inputs): for i,it in enumerate(inputs): inputs[i] = np.concatenate([it, np.zeros((story_maxsents-it.shape[0],story_maxlen), 'int')]) return np.stack(inputs) inputs_train = stack_inputs(inputs_train) inputs_test = stack_inputs(inputs_test) inputs_train.shape, inputs_test.shape """ Explanation: Next we vectorize our dataset by mapping words to their indices. We enforce consistent dimension by padding vectors up to the upper bounds we calculated earlier with our pad element. End of explanation """ inps = [inputs_train, queries_train] val_inps = [inputs_test, queries_test] """ Explanation: Our inputs for keras. End of explanation """ emb_dim = 20 parms = {'verbose': 2, 'callbacks': [TQDMNotebookCallback(leave_inner=False)]} """ Explanation: Model The approach to solving this task relies not only on word embeddings, but sentence embeddings. The authors of the Babi paper constructed sentence embeddings by simply adding up the word embeddings; this might seem naive, but given the relatively small length of these sentences we can expect the sum to capture relevant information. End of explanation """ def emb_sent_bow(inp): emb = TimeDistributed(Embedding(vocab_size, emb_dim))(inp) return Lambda(lambda x: K.sum(x, 2))(emb) """ Explanation: We use <tt>TimeDistributed</tt> here to apply the embedding to every element of the sequence, then the <tt>Lambda</tt> layer adds them up End of explanation """ inp_story = Input((story_maxsents, story_maxlen)) emb_story = emb_sent_bow(inp_story) inp_story.shape, emb_story.shape """ Explanation: The embedding works as desired; the raw input has 10 sentences of 8 words, and the output has 10 sentence embeddings of length 20. End of explanation """ inp_q = Input((query_maxlen,)) emb_q = Embedding(vocab_size, emb_dim)(inp_q) emb_q = Lambda(lambda x: K.sum(x, 1))(emb_q) emb_q = Reshape((1, emb_dim))(emb_q) inp_q.shape, emb_q.shape """ Explanation: We do the same for the queries, omitting the <tt>TimeDistributed</tt> since there is only one query. We use <tt>Reshape</tt> to match the rank of the input. End of explanation """ x = dot([emb_story, emb_q], 2) # Keras 2 x = Reshape((story_maxsents,))(x) x = Activation('softmax')(x) match = Reshape((story_maxsents,1))(x) match.shape """ Explanation: The actual memory network is incredibly simple. For each story, we take the dot product of every sentence embedding with that story's query embedding. This gives us a list of numbers proportional to how similar each sentence is with the query. We pass this vector of dot products through a softmax function to return a list of scalars that sum to one and tell us how similar the query is to each sentence. End of explanation """ emb_c = emb_sent_bow(inp_story) x = dot([match, emb_c], 1) # Keras 2 response = Reshape((emb_dim,))(x) res = Dense(vocab_size, activation='softmax')(response) answer = Model([inp_story, inp_q], res) answer.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy']) """ Explanation: Next, we construct a second, separate, embedding function for the sentences We then take the weighted average of these embeddings, using the softmax outputs as weights Finally, we pass this weighted average though a dense layer and classify it w/ a softmax into one of the words in the vocabulary End of explanation """ K.set_value(answer.optimizer.lr, 1e-2) hist=answer.fit(inps, answers_train, **parms, epochs=4, batch_size=32, validation_data=(val_inps, answers_test)) """ Explanation: And it works extremely well End of explanation """ f = Model([inp_story, inp_q], match) qnum=6 l_st = len(train_stories[qnum][0])+1 train_stories[qnum] """ Explanation: Test We can look inside our model to see how it's weighting the sentence embeddings. End of explanation """ np.squeeze(f.predict([inputs_train[qnum:qnum+1], queries_train[qnum:qnum+1]]))[:l_st] answers_train[qnum:qnum+10,0] np.argmax(answer.predict([inputs_train[qnum:qnum+10], queries_train[qnum:qnum+10]]), 1) answer.predict([inputs_train[qnum:qnum+1], queries_train[qnum:qnum+1]]) vocab[19] """ Explanation: Sure enough, for the question "Where is Sandra?", the largest weight is the last sentence with the name Sandra, sentence 1 with 0.98. The second highest is of course the first sentence, which also mentions Sandra. But the model has learned that the last occurring sentence is what is important; this is why we added the counter at the beginning of each sentence. End of explanation """ test_stories[534] """ Explanation: Multi hop Next, let's look at an example of a two-supporting fact story. End of explanation """ inputs_train.shape, inputs_test.shape """ Explanation: We can see that the question "Where is the milk?" requires to supporting facts to answer, "Daniel traveled to the hallway" and "Daniel left the milk there". End of explanation """ parms = {'verbose': 2, 'callbacks': [TQDMNotebookCallback(leave_inner=False)]} emb_dim = 30 def emb_sent_bow(inp): emb_op = TimeDistributed(Embedding(vocab_size, emb_dim)) emb = emb_op(inp) emb = Lambda(lambda x: K.sum(x, 2))(emb) # return Elemwise(0, False)(emb), emb_op return emb, emb_op inp_story = Input((story_maxsents, story_maxlen)) inp_q = Input((query_maxlen,)) emb_story, emb_story_op = emb_sent_bow(inp_story) emb_q = emb_story_op.layer(inp_q) emb_q = Lambda(lambda x: K.sum(x, 1))(emb_q) h = Dense(emb_dim) """ Explanation: The approach is basically the same; we add more embedding dimensions to account for the increased task complexity. End of explanation """ def one_hop(u, A): C, _ = emb_sent_bow(inp_story) x = Reshape((1, emb_dim))(u) x = dot([A, x], 2) # Keras 2 x = Reshape((story_maxsents,))(x) x = Activation('softmax')(x) match = Reshape((story_maxsents,1))(x) x = dot([match, C], 1) # Keras 2 x = Reshape((emb_dim,))(x) x = h(x) x = add([x, emb_q]) # Keras 2 return x, C """ Explanation: The main difference is that we are going to do the same process twice. Here we've defined a "hop" as the operation that returns the weighted average of the input sentence embeddings. End of explanation """ response, emb_story = one_hop(emb_q, emb_story) response, emb_story = one_hop(response, emb_story) # response, emb_story = one_hop(response, emb_story) res = Dense(vocab_size, activation='softmax')(response) answer = Model([inp_story, inp_q], res) answer.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy']) """ Explanation: We do one hop, and repeat the process using the resulting weighted sentence average as the new weights. This works because the first hop allows us to find the first fact relevant to the query, and then we can use that fact to find the next fact that answers the question. In our example, our model would first find the last sentence to mention "milk", and then use the information in that fact to know that it next has to find the last occurrence of "Daniel". This is facilitated by generating a new embedding function for the input story each time we hop. This means that the first embedding is learning things that help us find the first fact from the query, and the second is helping us find the second fact from the first. This approach can be extended to n-supporting factor problems by doing n hops. End of explanation """ K.set_value(answer.optimizer.lr, 5e-3) hist=answer.fit(inps, answers_train, **parms, epochs=8, batch_size=32, validation_data=(val_inps, answers_test)) np.array(hist.history['val_acc']) """ Explanation: Fitting this model can be tricky. End of explanation """ class Elemwise(Layer): def __init__(self, axis, is_mult, init='glorot_uniform', **kwargs): self.init = initializations.get(init) self.axis = axis self.is_mult = is_mult super(Elemwise, self).__init__(**kwargs) def build(self, input_shape): input_dims = input_shape[1:] dims = [1] * len(input_dims) dims[self.axis] = input_dims[self.axis] self.b = self.add_weight(dims, self.init, '{}_bo'.format(self.name)) self.built = True def call(self, x, mask=None): return x * self.b if self.is_mult else x + self.b def get_output_shape_for(self, input_shape): return input_shape def get_config(self): config = {'init': self.init.__name__, 'axis': self.axis} base_config = super(Dense, self).get_config() return dict(list(base_config.items()) + list(config.items())) """ Explanation: Custom bias layer End of explanation """
tarunchhabra26/fss16dst
code/8/WS4/dndesai_performance.ipynb
apache-2.0
%matplotlib inline # All the imports from __future__ import print_function, division import pom3_ga, sys import pickle # TODO 1: Enter your unity ID here __author__ = "dndesai" """ Explanation: Workshop 4 - Performance Metrics In this workshop we study 2 performance metrics(Spread and Inter-Generational Distance) on GA optimizing the POM3 model. End of explanation """ def normalize(problem, points): """ Normalize all the objectives in each point and return them """ meta = problem.objectives all_objs = [] for point in points: objs = [] for i, o in enumerate(problem.evaluate(point)): low, high = meta[i].low, meta[i].high # TODO 3: Normalize 'o' between 'low' and 'high'; Then add the normalized value to 'objs' if high == low: objs.append(0); continue; objs.append((o-low)/(high-low)) all_objs.append(objs) return all_objs """ Explanation: To compute most measures, data(i.e objectives) is normalized. Normalization is scaling the data between 0 and 1. Why do we normalize? TODO2 : To put on the same level playing field. That makes it easy to compare two data points even from different sets. End of explanation """ """ Performing experiments for [5, 10, 50] generations. """ problem = pom3_ga.POM3() pop_size = 10 repeats = 10 test_gens = [5, 10, 50] def save_data(file_name, data): """ Save 'data' to 'file_name.pkl' """ with open(file_name + ".pkl", 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) def load_data(file_name): """ Retrieve data from 'file_name.pkl' """ with open(file_name + ".pkl", 'rb') as f: return pickle.load(f) def build(problem, pop_size, repeats, test_gens): """ Repeat the experiment for 'repeats' number of repeats for each value in 'test_gens' """ tests = {t: [] for t in test_gens} tests[0] = [] # For Initial Population for _ in range(repeats): init_population = pom3_ga.populate(problem, pop_size) pom3_ga.say(".") for gens in test_gens: tests[gens].append(normalize(problem, pom3_ga.ga(problem, init_population, retain_size=pop_size, gens=gens)[1])) tests[0].append(normalize(problem, init_population)) print("\nCompleted") return tests """ Repeat Experiments """ # tests = build(problem, pop_size, repeats, test_gens) """ Save Experiment Data into a file """ # save_data("dump", tests) """ Load the experimented data from dump. """ tests = load_data("dump") print (tests.keys()) """ Explanation: Data Format For our experiments we store the data in the following format. data = { "expt1":[repeat1, repeat2, ...], "expt2":[repeat1, repeat2, ...], . . . } repeatx = [objs1, objs2, ....] // All of the final population objs1 = [norm_obj1, norm_obj2, ...] // Normalized objectives of each member of the final population. End of explanation """ def make_reference(problem, *fronts): """ Make a reference set comparing all the fronts. Here the comparison we use is bdom. It can be altered to use cdom as well """ retain_size = len(fronts[0]) reference = [] for front in fronts: reference+=front def bdom(one, two): """ Return True if 'one' dominates 'two' else return False :param one - [pt1_obj1, pt1_obj2, pt1_obj3, pt1_obj4] :param two - [pt2_obj1, pt2_obj2, pt2_obj3, pt2_obj4] """ dominates = False for i, obj in enumerate(problem.objectives): gt, lt = pom3_ga.gt, pom3_ga.lt better = lt if obj.do_minimize else gt # TODO 3: Use the varaibles declared above to check if one dominates two if better(one[i], two[i]): dominates = True elif one[i] != two[i]: return False return dominates def fitness(one, dom): return len([1 for another in reference if dom(one, another)]) fitnesses = [] for point in reference: fitnesses.append((fitness(point, bdom), point)) reference = [tup[1] for tup in sorted(fitnesses, reverse=True)] return reference[:retain_size] assert len(make_reference(problem, tests[5][0], tests[10][0], tests[50][0])) == len(tests[5][0]) ''' ### Spread Calculating spread: <img width=300 src="http://mechanicaldesign.asmedigitalcollection.asme.org/data/Journals/JMDEDB/27927/022006jmd3.jpeg"> - Consider the population of final gen(P) and the Pareto Frontier(R). - Find the distances between the first point of P and first point of R(_d<sub>f</sub>_) and last point of P and last point of R(_d<sub>l</sub>_) - Find the distance between all points and their nearest neighbor _d<sub>i</sub>_ and their nearest neighbor - Then: <img width=300 src="https://raw.githubusercontent.com/txt/ase16/master/img/spreadcalc.png"> - If all data is maximally spread, then all distances _d<sub>i</sub>_ are near mean d which would make _&Delta;=0_ ish. Note that _less_ the spread of each point to its neighbor, the _better_ since this means the optimiser is offering options across more of the frontier. ''' def eucledian(one, two): """ Compute Eucledian Distance between 2 vectors. We assume the input vectors are normalized. :param one: Vector 1 :param two: Vector 2 :return: """ # TODO 4: Code up the eucledian distance. https://en.wikipedia.org/wiki/Euclidean_distance return sum([(o-t)**2 for o,t in zip(one, two)])**0.5 def sort_solutions(solutions): """ Sort a list of list before computing spread """ def sorter(lst): m = len(lst) weights = reversed([10 ** i for i in xrange(m)]) return sum([element * weight for element, weight in zip(lst, weights)]) return sorted(solutions, key=sorter) def closest(one, many): min_dist = sys.maxint closest_point = None for this in many: dist = eucledian(this, one) if dist < min_dist: min_dist = dist closest_point = this return min_dist, closest_point def spread(obtained, ideals): """ Calculate the spread (a.k.a diversity) for a set of solutions """ s_obtained = sort_solutions(obtained) s_ideals = sort_solutions(ideals) d_f = closest(s_ideals[0], s_obtained)[0] d_l = closest(s_ideals[-1], s_obtained)[0] n = len(s_ideals) distances = [] for i in range(len(s_obtained)-1): distances.append(eucledian(s_obtained[i], s_obtained[i+1])) d_bar = sum(distances)/len(distances) # TODO 5: Compute the value of spread using the definition defined in the previous cell. d_sum = sum([abs(d_i - d_bar) for d_i in distances]) delta = (d_f + d_l + d_sum)/ (d_f + d_l + (n-1)*d_bar) return delta ref = make_reference(problem, tests[5][0], tests[10][0], tests[50][0]) print(spread(tests[5][0], ref)) print(spread(tests[10][0], ref)) print(spread(tests[50][0], ref)) """ Explanation: Reference Set Almost all the traditional measures you consider need a reference set for its computation. A theoritical reference set would be the ideal pareto frontier. This is fine for a) Mathematical Models: Where we can solve the problem to obtain the set. b) Low Runtime Models: Where we can do a one time exaustive run to obtain the model. But most real world problems are neither mathematical nor have a low runtime. So what do we do?. Compute an approximate reference set One possible way of constructing it is: 1. Take the final generation of all the treatments. 2. Select the best set of solutions from all the final generations End of explanation """ def igd(obtained, ideals): """ Compute the IGD for a set of solutions :param obtained: Obtained pareto front :param ideals: Ideal pareto front :return: """ # TODO 6: Compute the value of IGD using the definition defined in the previous cell. igd_val = sum([closest (ideal,obtained)[0] for ideal in ideals])/ len(ideals) return igd_val ref = make_reference(problem, tests[5][0], tests[10][0], tests[50][0]) print(igd(tests[5][0], ref)) print(igd(tests[10][0], ref)) print(igd(tests[50][0], ref)) import sk sk = reload(sk) def format_for_sk(problem, data, measure): """ Convert the experiment data into the format required for sk.py and computet the desired 'measure' for all the data. """ gens = data.keys() reps = len(data[gens[0]]) measured = {gen:["gens_%d"%gen] for gen in gens} for i in range(reps): ref_args = [data[gen][i] for gen in gens] ref = make_reference(problem, *ref_args) for gen in gens: measured[gen].append(measure(data[gen][i], ref)) return measured def report(problem, tests, measure): measured = format_for_sk(problem, tests, measure).values() sk.rdivDemo(measured) print("*** IGD ***") report(problem, tests, igd) print("\n*** Spread ***") report(problem, tests, spread) """ Explanation: IGD = inter-generational distance; i.e. how good are you compared to the best known? Find a reference set (the best possible solutions) For each optimizer For each item in its final Pareto frontier Find the nearest item in the reference set and compute the distance to it. Take the mean of all the distances. This is IGD for the optimizer Note that the less the mean IGD, the better the optimizer since this means its solutions are closest to the best of the best. End of explanation """
Kaggle/learntools
notebooks/machine_learning/raw/ex6.ipynb
apache-2.0
# Code you have previously used to load data import pandas as pd from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeRegressor # Path of the file to read iowa_file_path = '../input/home-data-for-ml-course/train.csv' home_data = pd.read_csv(iowa_file_path) # Create target object and call it y y = home_data.SalePrice # Create X features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd'] X = home_data[features] # Split into validation and training data train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1) # Specify Model iowa_model = DecisionTreeRegressor(random_state=1) # Fit Model iowa_model.fit(train_X, train_y) # Make validation predictions and calculate mean absolute error val_predictions = iowa_model.predict(val_X) val_mae = mean_absolute_error(val_predictions, val_y) print("Validation MAE when not specifying max_leaf_nodes: {:,.0f}".format(val_mae)) # Using best value for max_leaf_nodes iowa_model = DecisionTreeRegressor(max_leaf_nodes=100, random_state=1) iowa_model.fit(train_X, train_y) val_predictions = iowa_model.predict(val_X) val_mae = mean_absolute_error(val_predictions, val_y) print("Validation MAE for best value of max_leaf_nodes: {:,.0f}".format(val_mae)) # Set up code checking from learntools.core import binder binder.bind(globals()) from learntools.machine_learning.ex6 import * print("\nSetup complete") """ Explanation: Recap Here's the code you've written so far. End of explanation """ from sklearn.ensemble import RandomForestRegressor # Define the model. Set random_state to 1 rf_model = ____ # fit your model ____ # Calculate the mean absolute error of your Random Forest model on the validation data rf_val_mae = ____ print("Validation MAE for Random Forest Model: {}".format(rf_val_mae)) # Check your answer step_1.check() # The lines below will show you a hint or the solution. # step_1.hint() # step_1.solution() #%%RM_IF(PROD)%% from sklearn.ensemble import RandomForestRegressor # Define the model. Set random_state to 1 rf_model = RandomForestRegressor(random_state=1) # fit your model rf_model.fit(train_X, train_y) # Calculate the mean absolute error of your Random Forest model on the validation data rf_val_predictions = rf_model.predict(val_X) rf_val_mae = mean_absolute_error(rf_val_predictions, val_y) print("Validation MAE for Random Forest Model: {:,.0f}".format(rf_val_mae)) step_1.assert_check_passed() """ Explanation: Exercises Data science isn't always this easy. But replacing the decision tree with a Random Forest is going to be an easy win. Step 1: Use a Random Forest End of explanation """
tensorflow/docs-l10n
site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb
apache-2.0
#@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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2020 The TensorFlow Authors. End of explanation """ #@test {"skip": true} !pip install --quiet --upgrade tensorflow-federated !pip install --quiet --upgrade nest-asyncio import nest_asyncio nest_asyncio.apply() import tensorflow as tf import tensorflow_federated as tff """ Explanation: <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/federated/tutorials/building_your_own_federated_learning_algorithm"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org에서 보기</a></td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab에서 실행하기</a> </td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub에서 소스 보기</a></td> <td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">노트북 다운로드</a></td> </table> 시작하기 전에 시작하기 전에 다음을 실행하여 환경이 올바르게 설정되었는지 확인하세요. 인사말이 표시되지 않으면 설치 가이드에서 지침을 참조하세요. End of explanation """ emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() """ Explanation: 참고: 이 Colab은 <code>tensorflow_federated</code> pip 패키지의 <a>최신 릴리즈 버전</a>에서 동작하는 것으로 확인되었지만 Tensorflow Federated 프로젝트는 아직 시험판 개발 중이며 main에서 동작하지 않을 수 있습니다. 고유한 페더레이션 학습 알고리즘 구축하기 이미지 분류 및 텍스트 생성 튜토리얼에서는 페더레이션 학습(FL)을 위한 모델 및 데이터 파이프라인을 설정하는 방법을 배웠고 TFF의 tff.learning API 계층을 통해 페더레이션 학습을 수행했습니다. 이것은 FL 연구와 관련하여 빙산의 일각에 불과합니다. 이 튜토리얼에서는 tff.learning API를 따르지 않고 페더레이션 학습 알고리즘을 구현하는 방법을 논의합니다. 여기서는 다음을 목표로 합니다. 목표 페더레이션 학습 알고리즘의 일반적인 구조를 이해합니다. TFF의 페더레이션 코어를 탐색합니다. Federated Core를 사용하여 Federated Averaging을 직접 구현합니다. 이 튜토리얼은 자체적으로 진행할 수 있지만 먼저 이미지 분류 및 텍스트 생성 튜토리얼을 읽어보는 것이 좋습니다. 입력 데이터 준비하기 먼저 TFF에 포함된 EMNIST 데이터세트를 로드하고 전처리합니다. 자세한 내용은 이미지 분류 튜토리얼을 참조하세요. End of explanation """ NUM_CLIENTS = 10 BATCH_SIZE = 20 def preprocess(dataset): def batch_format_fn(element): """Flatten a batch of EMNIST data and return a (features, label) tuple.""" return (tf.reshape(element['pixels'], [-1, 784]), tf.reshape(element['label'], [-1, 1])) return dataset.batch(BATCH_SIZE).map(batch_format_fn) """ Explanation: 데이터세트를 모델에 제공하기 위해 데이터를 평면화하고 각 예제를 (flattened_image_vector, label) 형식의 튜플로 변환합니다. End of explanation """ client_ids = sorted(emnist_train.client_ids)[:NUM_CLIENTS] federated_train_data = [preprocess(emnist_train.create_tf_dataset_for_client(x)) for x in client_ids ] """ Explanation: 이제 소수의 클라이언트를 선택하고 위의 전처리를 데이터세트에 적용합니다. End of explanation """ def create_keras_model(): initializer = tf.keras.initializers.GlorotNormal(seed=0) return tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(784,)), tf.keras.layers.Dense(10, kernel_initializer=initializer), tf.keras.layers.Softmax(), ]) """ Explanation: 모델 준비하기 이미지 분류 튜토리얼에서와 동일한 모델을 사용합니다. 이 모델(tf.keras를 통해 구현됨)에는 하나의 숨겨진 레이어, 그리고 이어서 소프트맥스 레이어가 있습니다. End of explanation """ def model_fn(): keras_model = create_keras_model() return tff.learning.from_keras_model( keras_model, input_spec=federated_train_data[0].element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) """ Explanation: TFF에서 이 모델을 사용하기 위해 Keras 모델을 tff.learning.Model로 래핑합니다. 이를 통해 TFF 내에서 모델의 정방향 전달을 수행하고 모델 출력을 추출할 수 있습니다. 자세한 내용은 이미지 분류 튜토리얼을 참조하세요. End of explanation """ def initialize_fn(): model = model_fn() return model.trainable_variables """ Explanation: 여기서는 tf.keras를 사용하여 tff.learning.Model을 생성하지만 TFF는 훨씬 더 많은 일반 모델을 지원합니다. 이러한 모델에는 모델 가중치를 캡처하는 다음과 같은 관련 속성이 있습니다. trainable_variables: 학습 가능한 레이어에 해당하는 텐서의 이터러블입니다. non_trainable_variables: 학습할 수 없는 레이어에 해당하는 텐서의 이터러블입니다. 여기서는 목적상 trainable_variables만 사용합니다(우리 모델에는 이것만 있으므로!). 고유한 페더레이션 학습 알고리즘 구축하기 tff.learning API를 사용하면 Federated Averaging의 많은 변형을 생성할 수 있지만 이 프레임워크에 깔끔하게 맞지 않는 다른 페더레이션 알고리즘이 있습니다. 예를 들어 정규화, 클리핑 또는 페더레이션 GAN 학습과 같은 더 복잡한 알고리즘을 추가할 수도 있습니다. 아니면 페더레이션 분석에 관심이 있을 수도 있습니다. 이러한 고급 알고리즘의 경우 TFF를 사용하여 자체 사용자 지정 알고리즘을 작성해야 합니다. 많은 경우 페더레이션 알고리즘에는 4가지 주요 구성 요소가 있습니다. 서버-클라이언트 브로드캐스트 단계 로컬 클라이언트 업데이트 단계 클라이언트-서버 업로드 단계 서버 업데이트 단계 TFF에서는 일반적으로 페더레이션 알고리즘을 tff.templates.IterativeProcess(나머지 부분에서 IterativeProcess라고 함)로 나타냅니다. 이것은 initialize 및 next 함수를 포함하는 클래스입니다. 여기서 initialize는 서버를 초기화하는 데 사용되며 next는 페더레이션 알고리즘의 한 통신 라운드를 수행합니다. FedAvg에 대한 반복 프로세스가 어떤 모습인지 그 골격을 작성해 보겠습니다. 먼저 tff.learning.Model을 생성하고 학습 가능한 가중치를 반환하는 초기화 함수가 있습니다. End of explanation """ def next_fn(server_weights, federated_dataset): # Broadcast the server weights to the clients. server_weights_at_client = broadcast(server_weights) # Each client computes their updated weights. client_weights = client_update(federated_dataset, server_weights_at_client) # The server averages these updates. mean_client_weights = mean(client_weights) # The server updates its model. server_weights = server_update(mean_client_weights) return server_weights """ Explanation: 이 함수는 문제 없어 보이지만 "TFF 계산"이 되도록 약간 수정해야 합니다. 이 내용은 나중에 알아볼 것입니다. 또한, 우리는 next_fn를 스케치하려고 합니다. End of explanation """ @tf.function def client_update(model, dataset, server_weights, client_optimizer): """Performs training (using the server model weights) on the client's dataset.""" # Initialize the client model with the current server weights. client_weights = model.trainable_variables # Assign the server weights to the client model. tf.nest.map_structure(lambda x, y: x.assign(y), client_weights, server_weights) # Use the client_optimizer to update the local model. for batch in dataset: with tf.GradientTape() as tape: # Compute a forward pass on the batch of data outputs = model.forward_pass(batch) # Compute the corresponding gradient grads = tape.gradient(outputs.loss, client_weights) grads_and_vars = zip(grads, client_weights) # Apply the gradient using a client optimizer. client_optimizer.apply_gradients(grads_and_vars) return client_weights """ Explanation: 이 네 가지 구성 요소를 개별적으로 구현하는 데 중점을 둘 것입니다. 먼저 순수 TensorFlow에서 구현할 수 있는 부분, 즉 클라이언트 및 서버 업데이트 단계에 초점을 맞출 것입니다. TensorFlow 블록 클라이언트 업데이트 tff.learning.Model을 사용하여 기본적으로 TensorFlow 모델을 훈련하는 것과 동일한 방식으로 클라이언트 훈련을 수행합니다. 특히, 우리는 tf.GradientTape를 사용하여 데이터 배치에 대한 그레디언트를 계산한 다음 client_optimizer를 사용하여 이러한 그레디언트를 적용합니다. 우리는 훈련 가능한 가중치에만 초점을 맞춥니다. End of explanation """ @tf.function def server_update(model, mean_client_weights): """Updates the server model weights as the average of the client model weights.""" model_weights = model.trainable_variables # Assign the mean client weights to the server model. tf.nest.map_structure(lambda x, y: x.assign(y), model_weights, mean_client_weights) return model_weights """ Explanation: 서버 업데이트 FedAvg에 대한 서버 업데이트는 클라이언트 업데이트보다 간단합니다. 우리는 단순히 서버 모델 가중치를 클라이언트 모델 가중치의 평균으로 바꾸는 "바닐라" 페더레이션 평균화를 구현할 것입니다. 다시 말하지만, 우리는 훈련 가능한 가중치에만 초점을 맞춥니다. End of explanation """ federated_float_on_clients = tff.FederatedType(tf.float32, tff.CLIENTS) """ Explanation: 단순히 mean_client_weights를 반환하여 스니펫을 단순화할 수 있습니다. 그러나 Federated Averaging의 고급 구현에서는 모멘텀 또는 적응성과 같은 보다 정교한 기술과 함께 mean_client_weights를 사용합니다. 과제: model_weights 및 mean_client_weights의 중간점이 되도록 서버 가중치를 업데이트하는 server_update 버전을 구현합니다(참고: 이러한 종류의 "중간점" 접근 방식은 Lookahead 옵티마이저에 대한 최근의 작업과 유사합니다!). 지금까지 순수한 TensorFlow 코드만 작성했습니다. TFF를 사용하면 이미 익숙한 TensorFlow 코드를 많이 사용할 수 있으므로 이는 의도적으로 설계된 것입니다. 그러나 이제 <em>오케스트레이션 로직</em>, 즉 서버가 클라이언트에 브로드캐스트하는 내용과 클라이언트가 서버에 업로드하는 내용을 지정하는 로직을 지정해야 합니다. 이를 위해서는 TFF의 페더레이션 코어가 필요합니다. 페더레이션 코어 소개 페더레이션 코어(FC)는 tff.learning API의 기반 역할을 하는 하위 수준 인터페이스 집합입니다. 그러나 이러한 인터페이스는 학습에만 국한되지 않습니다. 실제로 분산 데이터에 대한 분석 및 기타 많은 계산에 사용할 수 있습니다. 상위 수준에서 페더레이션 코어는 간결하게 표현된 프로그램 로직을 사용하여 TensorFlow 코드를 분산 통신 연산자(예: 분산 합계 및 브로드캐스트)와 결합할 수 있는 개발 환경입니다. 목표는 시스템 구현 세부 사항(예: 지점 간 네트워크 메시지 교환 지정)을 요구하지 않고 연구자와 실무자에게 시스템의 분산 통신을 신속하게 제어할 수 있도록 하는 것입니다. 한 가지 요점은 TFF가 개인 정보 보호를 위해 설계되었다는 것입니다. 따라서 중앙 집중식 서버 위치에서 원치 않는 데이터 축적을 방지하기 위해 데이터가 있는 위치를 명시적으로 제어할 수 있습니다. 페더레이션 데이터 TFF의 핵심 개념은 "페더레이션 데이터"이며, 이는 분산 시스템의 장치 그룹(예: 클라이언트 데이터세트 또는 서버 모델 가중치)에 걸쳐 호스팅되는 데이터 항목의 집합을 나타냅니다. 우리는 모든 장치에서 데이터 항목의 전체 컬렉션을 단일 페더레이션 값으로 모델링합니다. 예를 들어, 센서의 온도를 나타내는 부동 소수점이 있는 클라이언트 장치가 있다고 가정합니다. 우리는 이것을 페더레이션 부동 소수점으로 표현할 수 있습니다. End of explanation """ str(federated_float_on_clients) """ Explanation: 페더레이션 유형은 해당 구성원 구성 요소(예: tf.float32)의 유형 T와 장치 그룹 G로 지정됩니다. G가 tff.CLIENTS 또는 tff.SERVER인 경우에 중점을 둘 것입니다. 이러한 페더레이션 유형은 아래와 같이 {T}@G로 표시됩니다. End of explanation """ @tff.federated_computation(tff.FederatedType(tf.float32, tff.CLIENTS)) def get_average_temperature(client_temperatures): return tff.federated_mean(client_temperatures) """ Explanation: 게재 위치에 관심이 많은 이유는 무엇입니까? TFF의 핵심 목표는 실제 분산 시스템에 배포할 수 있는 코드를 작성할 수 있도록 하는 것입니다. 즉, 장치의 하위 집합이 어떤 코드를 실행하고 다른 데이터 조각이 어디에 있는지 추론하는 것이 중요합니다. TFF는 데이터, 데이터가 배치되는 위치 및 데이터가 변환되는 방법의 세 가지에 중점을 둡니다. 처음 두 개는 페더레이션 유형으로 캡슐화되고 마지막 두 개는 페더레이션 계산에 캡슐화됩니다. 페더레이션 계산 TFF는 기본 단위가 페더레이션 계산인 강력한 형식의 함수형 프로그래밍 환경입니다. 이들은 페더레이션 값을 입력으로 받아들이고 페더레이션 값을 출력으로 반환하는 논리 조각입니다. 예를 들어 클라이언트 센서의 온도를 평균화하고 싶다고 가정합니다. 다음을 정의할 수 있습니다(페더레이션 부동 소수점 사용). End of explanation """ str(get_average_temperature.type_signature) """ Explanation: TensorFlow의 tf.function 데코레이터와 어떻게 다른지 물어볼 수 있습니다. 핵심적인 대답은 tff.federated_computation에 의해 생성된 코드가 TensorFlow도 아니고 Python 코드도 아니라는 것입니다. 내부 플랫폼 독립적인 글루 언어로 된 분산 시스템의 사양입니다. 복잡하게 들릴 수 있지만 TFF 계산은 잘 정의된 형식 서명이 있는 함수로 생각할 수 있습니다. 이러한 유형 서명은 직접 쿼리할 수 있습니다. End of explanation """ get_average_temperature([68.5, 70.3, 69.8]) """ Explanation: 이 tff.federated_computation은 페더레이션 유형 &lt;float&gt;@CLIENTS의 인수를 받아들이고 페더레이션 유형 &lt;float&gt;@SERVER의 값을 반환합니다. 페더레이션 계산은 서버에서 클라이언트로, 클라이언트에서 클라이언트로 또는 서버에서 서버로 이동할 수도 있습니다. 페더레이션 계산은 유형 서명이 일치하는 한 일반 함수처럼 구성할 수도 있습니다. 개발을 지원하기 위해 TFF를 사용하면 tff.federated_computation을 Python 함수로 호출할 수 있습니다. 예를 들어 다음을 호출할 수 있습니다. End of explanation """ @tff.tf_computation(tf.float32) def add_half(x): return tf.add(x, 0.5) """ Explanation: 비 즉시 실행 계산 및 TensorFlow 두 가지 주요 제한 사항을 알고 있어야 합니다. 첫째, Python 인터프리터가 tff.federated_computation 데코레이터를 만나면 함수가 한 번 추적되고 나중에 사용할 수 있도록 직렬화됩니다. 페더레이션 학습의 분산된 특성으로 인해 이러한 미래의 사용은 원격 실행 환경과 같은 다른 곳에서 발생할 수 있습니다. 따라서 TFF 계산은 기본적으로 비 즉시 실행입니다. 이 동작은 TensorFlow의 tf.function 데코레이터와 다소 유사합니다. 둘째, 페더레이션 계산은 페더레이션 연산자(예: tff.federated_mean)로만 구성될 수 있으며 TensorFlow 작업을 포함할 수 없습니다. TensorFlow 코드는 tff.tf_computation 데코레이션된 블록으로 제한되어야 합니다. 숫자를 취하고 여기에 0.5를 더하는 다음 함수와 같이 대부분의 일반적인 TensorFlow 코드는 직접 데코레이션할 수 있습니다. End of explanation """ str(add_half.type_signature) """ Explanation: 또한 유형 서명이 있지만 배치는 없습니다 . 예를 들어 다음을 호출할 수 있습니다. End of explanation """ @tff.federated_computation(tff.FederatedType(tf.float32, tff.CLIENTS)) def add_half_on_clients(x): return tff.federated_map(add_half, x) """ Explanation: 여기에서 tff.federated_computation과 tff.tf_computation의 중요한 차이점을 볼 수 있습니다. 전자는 명시적 배치가 있는 반면 후자는 그렇지 않습니다. 게재 위치를 지정하여 페더레이션 계산에서 tff.tf_computation 블록을 사용할 수 있습니다. 절반을 추가하지만 클라이언트에서 페더레이션 부동 소수점에만 추가하는 함수를 만들어 보겠습니다. 게재 위치를 유지하면서 지정된 tff.tf_computation을 적용하는 tff.federated_map을 사용하여 이를 수행할 수 있습니다. End of explanation """ str(add_half_on_clients.type_signature) """ Explanation: 이 함수는 tff.CLIENTS에 배치된 값만 허용하고 동일한 배치의 값을 반환한다는 점을 제외하면 add_half와 거의 동일합니다. 유형 서명에서 이를 확인할 수 있습니다. End of explanation """ @tff.tf_computation def server_init(): model = model_fn() return model.trainable_variables """ Explanation: 요약하자면: TFF는 페더레이션 값에서 작동합니다. 각 페더레이션 값에는 유형(예: tf.float32)과 배치(예: tff.CLIENTS)가 있는 페더레이션 유형{/em}이 있습니다. 페더레이션 값은 페더레이션 계산을 사용하여 변환될 수 있으며, tff.federated_computation 및 연합 유형 서명으로 데코레이션되어야 합니다. TensorFlow 코드는 tff.tf_computation 데코레이터가 있는 블록에 포함되어야 합니다. 그런 다음 이러한 블록을 페더레이션 계산에 통합할 수 있습니다. 고유한 페더레이션 학습 알고리즘 구축하기, 재검토 이제 페더레이션 코어를 살펴보았으므로 자체적인 페더레이션 학습 알고리즘을 구축할 수 있습니다. 위에서 알고리즘에 대해 initialize_fn 및 next_fn을 정의했음을 상기하세요. next_fn은 순수한 TensorFlow 코드를 사용하여 정의한 client_update 및 server_update를 사용합니다. 그러나 알고리즘을 페더레이션 계산으로 만들려면 next_fn과 initialize_fn이 각각 tff.federated_computation이 되어야 합니다. TensorFlow 페더레이션 블록 초기화 계산 만들기 initialize 함수는 매우 간단합니다. model_fn을 사용하여 모델을 생성합니다. 그러나 tff.tf_computation을 사용하여 TensorFlow 코드를 분리해야 합니다. End of explanation """ @tff.federated_computation def initialize_fn(): return tff.federated_value(server_init(), tff.SERVER) """ Explanation: 그런 다음 tff.federated_value를 사용하여 이를 페더레이션 계산에 직접 전달할 수 있습니다. End of explanation """ whimsy_model = model_fn() tf_dataset_type = tff.SequenceType(whimsy_model.input_spec) """ Explanation: next_fn 만들기 이제 클라이언트 및 서버 업데이트 코드를 사용하여 실제 알고리즘을 작성합니다. 먼저 client_update를 클라이언트 데이터세트와 서버 가중치를 받아들이고 업데이트된 클라이언트 가중치 텐서를 출력하는 tff.tf_computation으로 변환합니다. 함수를 적절하게 데코레이션하려면 해당 유형이 필요합니다. 다행히도 서버 가중치 유형은 모델에서 직접 추출할 수 있습니다. End of explanation """ str(tf_dataset_type) """ Explanation: 데이터세트 유형 서명을 살펴보겠습니다. 28 x 28 이미지(정수 레이블 포함)를 가져와 병합했다는 사실을 상기하세요. End of explanation """ model_weights_type = server_init.type_signature.result """ Explanation: 위의 server_init 함수를 사용하여 모델 가중치 유형을 추출할 수도 있습니다. End of explanation """ str(model_weights_type) """ Explanation: 형식 서명을 살펴보면 모델의 아키텍처를 볼 수 있습니다! End of explanation """ @tff.tf_computation(tf_dataset_type, model_weights_type) def client_update_fn(tf_dataset, server_weights): model = model_fn() client_optimizer = tf.keras.optimizers.SGD(learning_rate=0.01) return client_update(model, tf_dataset, server_weights, client_optimizer) """ Explanation: 이제 클라이언트 업데이트를 위한 tff.tf_computation을 생성할 수 있습니다. End of explanation """ @tff.tf_computation(model_weights_type) def server_update_fn(mean_client_weights): model = model_fn() return server_update(model, mean_client_weights) """ Explanation: 서버 업데이트의 tff.tf_computation 버전은 이미 추출한 유형을 사용하여 유사한 방식으로 정의할 수 있습니다. End of explanation """ federated_server_type = tff.FederatedType(model_weights_type, tff.SERVER) federated_dataset_type = tff.FederatedType(tf_dataset_type, tff.CLIENTS) """ Explanation: 마지막으로 이 모든 것을 통합하는 tff.federated_computation을 만들어야 합니다. 이 함수는 두 개의 페더레이션 값을 받아 들입니다. 하나는 서버 가중치(게재 위치 tff.SERVER)에 해당하고 다른 하나는 클라이언트 데이터세트(게재 위치 tff.CLIENTS)에 해당합니다. 이 두 유형은 모두 위에서 정의되었습니다! tff.FederatedType을 사용하여 적절한 배치를 제공하기만 하면 됩니다. End of explanation """ @tff.federated_computation(federated_server_type, federated_dataset_type) def next_fn(server_weights, federated_dataset): # Broadcast the server weights to the clients. server_weights_at_client = tff.federated_broadcast(server_weights) # Each client computes their updated weights. client_weights = tff.federated_map( client_update_fn, (federated_dataset, server_weights_at_client)) # The server averages these updates. mean_client_weights = tff.federated_mean(client_weights) # The server updates its model. server_weights = tff.federated_map(server_update_fn, mean_client_weights) return server_weights """ Explanation: FL 알고리즘의 4가지 요소를 기억하십니까? 서버-클라이언트 브로드캐스트 단계 로컬 클라이언트 업데이트 단계 클라이언트-서버 업로드 단계 서버 업데이트 단계 이제 위의 내용을 작성했으므로 각 부분을 한 줄의 TFF 코드로 간결하게 표현할 수 있습니다. 이 단순함 때문에 페더레이션 유형과 같은 것을 지정하기 위해 특별히 주의해야 했습니다! End of explanation """ federated_algorithm = tff.templates.IterativeProcess( initialize_fn=initialize_fn, next_fn=next_fn ) """ Explanation: 이제 알고리즘 초기화와 알고리즘의 한 단계를 실행하기 위한 tff.federated_computation이 있습니다. 알고리즘을 완료하기 위해 이를 tff.templates.IterativeProcess에 전달합니다. End of explanation """ str(federated_algorithm.initialize.type_signature) """ Explanation: 반복 프로세스의 <code>initialize</code> 및 next 함수의 <em>유형 서명</em>을 살펴보겠습니다. End of explanation """ str(federated_algorithm.next.type_signature) """ Explanation: 이는 federated_algorithm.initialize가 단일 레이어 모델(784x10 가중치 행렬 및 10개의 바이어스 단위 포함)을 반환하는 인수가 없는 함수라는 사실을 반영합니다. End of explanation """ central_emnist_test = emnist_test.create_tf_dataset_from_all_clients() central_emnist_test = preprocess(central_emnist_test) """ Explanation: 여기에서 federated_algorithm.next는 서버 모델과 클라이언트 데이터를 받아들이고 업데이트된 서버 모델을 반환합니다. 알고리즘 평가 몇 라운드를 실행하고 손실이 어떻게 변하는지 살펴보겠습니다. 먼저 두 번째 튜토리얼에서 논의한 중앙 집중식 접근 방식을 사용하여 평가 기능을 정의합니다. 먼저 중앙 집중식 평가 데이터세트를 만든 다음 훈련 데이터에 사용한 것과 동일한 전처리를 적용합니다. End of explanation """ def evaluate(server_state): keras_model = create_keras_model() keras_model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()] ) keras_model.set_weights(server_state) keras_model.evaluate(central_emnist_test) """ Explanation: 다음으로 서버 상태를 받아들이고 Keras를 사용하여 테스트 데이터세트를 평가하는 함수를 작성합니다. tf.Keras에 익숙하다면 모두 낯설지 않겠지만 set_weights의 사용에 주목하세요! End of explanation """ server_state = federated_algorithm.initialize() evaluate(server_state) """ Explanation: 이제 알고리즘을 초기화하고 테스트세트에서 평가해 보겠습니다. End of explanation """ for round in range(15): server_state = federated_algorithm.next(server_state, federated_train_data) evaluate(server_state) """ Explanation: 몇 라운드 동안 훈련하고 변경 사항이 있는지 살펴보겠습니다. End of explanation """
gldmt-duke/CokerAmitaiSGHMC
logistic_regression/logistic_regression_simulated.ipynb
mit
def logistic(x): ''' ''' return 1/(1+np.exp(-x)) def U_logistic(theta, Y, X, phi): ''' ''' return - (Y.T @ X @ theta - np.sum(np.log(1+np.exp(X @ theta))) - 0.5 * phi * np.sum(theta**2)) def gradU_logistic(theta, Y, X, phi): ''' ''' n = X.shape[0] Y_pred = logistic(X @ theta) epsilon = (Y[:,np.newaxis] - Y_pred[:,np.newaxis]) grad = X.T @ epsilon - phi * theta[:, np.newaxis] return -grad/n def hmc(Y, X, U, gradU, M, eps, m, theta0, phi): ''' ''' theta = theta0.copy() n, p = X.shape # Precompute Minv = np.linalg.inv(M) # Randomly sample momentum r = np.random.multivariate_normal(np.zeros(p),M)[:,np.newaxis] # Intial energy H0 = U(theta0, Y, X, phi) + 0.5 * np.asscalar(r.T @ Minv @ r) # Hamiltonian dynamics r -= (eps/2)*gradU(theta, Y, X, phi) for i in range(m): theta += (eps*Minv@r).ravel() r -= eps*gradU(theta, Y, X, phi) r -= (eps/2)*gradU(theta, Y, X, phi) # Final energy H1 = U(theta, Y, X, phi) + np.asscalar(0.5 * r.T @ Minv @ r) # MH step u = np.random.uniform() rho = np.exp(H0 - H1) # Acceptance probability if u < np.min((1, rho)): # accept accept = True H = H1 else: # reject theta = theta0 accept = False H = H0 return theta, accept, rho, H def run_hmc(Y, X, U, gradU, M, eps, m, theta, phi, nsample): n, p = X.shape # Allocate space samples = np.zeros((nsample, p)) accept = np.zeros(nsample) rho = np.zeros(nsample) H = np.zeros(nsample) # Run hmc for i in range(nsample): theta, accept[i], rho[i], H[i] = hmc(Y, X, U, gradU, M, eps, m, theta, phi) samples[i] = theta return samples, accept, rho, H def stogradU(theta, Y, X, nbatch, phi): '''A function that returns the stochastic gradient. Adapted from Eq. 5. Inputs are: theta, the parameters Y, the response X, the covariates nbatch, the number of samples to take from the full data ''' n, p = X.shape # Sample minibatch batch_id = np.random.choice(np.arange(n),nbatch,replace=False) Y_pred = logistic(X[batch_id,:] @ theta[:,np.newaxis]) epsilon = (Y[batch_id,np.newaxis] - Y_pred) grad = n/nbatch * X[batch_id,:].T @ epsilon - phi * theta[:, np.newaxis] #return -grad/n return -grad def sghmc(Y, X, U, gradU, M, Minv, eps, m, theta, B, D, phi): n, p = X.shape # Randomly sample momentum r = np.random.multivariate_normal(np.zeros(p),M)[:,np.newaxis] # Hamiltonian dynamics for i in range(m): theta += (eps*Minv@r).ravel() r -= eps*stogradU(theta, Y, X, nbatch,phi) - eps*C @ Minv @ r \ + np.random.multivariate_normal(np.zeros(p),D)[:,np.newaxis] # Record the energy H = U(theta, Y, X, phi) + np.asscalar(0.5 * r.T @ Minv @ r) return theta, H def run_sghmc(Y, X, U, gradU, M, eps, m, theta, C, V, phi, nsample): n, p = X.shape # Precompute Minv = np.linalg.inv(M) B = 0.5 * V * eps D = 2*(C-B)*eps # Allocate space samples = np.zeros((nsample, p)) H = np.zeros(nsample) # Run sghmc for i in range(nsample): theta, H[i] = sghmc(Y, X, U, gradU, M, Minv, eps, m, theta, B, D, phi) samples[i] = theta return samples, H def gd(Y, X, gradU, eps, m, theta, phi): ''' ''' samples = np.zeros((nsample, p)) for i in range(m): theta -= eps*gradU(theta, Y, X, phi).ravel() return theta """ Explanation: Here is the library of functions: End of explanation """ import numpy as np import matplotlib.pyplot as plt n = 500 p = 50 beta = np.random.normal(0, 1, p+1) Sigma = np.zeros((p, p)) Sigma_diags = np.array([25, 5, 0.2**2]) distribution = np.random.multinomial(p, pvals=[.05, .05, .9], size=1).tolist() np.fill_diagonal(Sigma, np.repeat(Sigma_diags, distribution[0], axis=0)) X = np.random.multivariate_normal(np.zeros(p), Sigma, n) X = np.hstack((np.ones((n, 1)), X)) p = np.exp(X @ beta)/np.exp(1 + np.exp(X @ beta)) Y = np.random.binomial(1, p, n) Xs = (X - np.mean(X, axis=0))/np.concatenate((np.ones(1),np.std(X[:,1:], axis=0))) Xs = Xs[:,1:] p = Xs.shape[1] """ Explanation: Everything after here is the script that runs the simulation: End of explanation """ from sklearn.linear_model import LogisticRegression # Unscaled mod_logis = LogisticRegression(fit_intercept=False, C=1e50) mod_logis.fit(X,Y) beta_true_unscale = mod_logis.coef_.ravel() beta_true_unscale # Scaled mod_logis = LogisticRegression(fit_intercept=False, C=1e50) mod_logis.fit(Xs,Y) beta_true_scale = mod_logis.coef_.ravel() beta_true_scale """ Explanation: Regression End of explanation """ # HMC - Scaled nsample = 1000 m = 20 eps = .0005 theta = np.zeros(p) #theta = beta_true_scale.copy() phi = 5 M = np.identity(p) samples, accept, rho, H = run_hmc(Y, Xs, U_logistic, gradU_logistic, M, eps, m, theta, phi, nsample) hmc_mean = np.mean(samples, axis=0) np.mean(samples, axis=0) - beta_true_scale plt.plot((samples - beta_true_scale)[:,3]) plt.show() plt.plot(H) plt.show() """ Explanation: HMC End of explanation """ # HMC - Scaled (no intercept) nsample = 1000 m = 20 eps = .01 theta = np.zeros(p) #theta = beta_true_scale.copy() phi = 5 nbatch = 500 C = 1 * np.identity(p) V = 0 * np.identity(p) M = np.identity(p) samples, H = run_sghmc(Y, Xs, U_logistic, gradU_logistic, M, eps, m, theta, C, V, phi, nsample) print(np.mean(samples, axis=0) - beta_true_scale) plt.plot((samples - beta_true_scale)[:,0]) plt.show() plt.plot(H) plt.show() """ Explanation: HMC - Unscaled nsample = 1000 m = 20 eps = .008 theta = np.zeros(p+1) theta = beta_true_unscale.copy() phi = 5 M = np.identity(p+1) samples, accept, rho, H = run_hmc(Y, X, U_logistic, gradU_logistic, M, eps, m, theta, phi, nsample) np.mean(samples, axis=0) - beta_true_unscale plt.plot((samples - beta_true_unscale)[:,3]) plt.show() plt.plot(H) plt.show() SGHMC End of explanation """ # Gradient descent - Scaled np.random.seed(2) phi = .1 res = gd(Y, Xs, gradU_logistic, .1, 20000, np.zeros(p), phi) res - beta_true_scale """ Explanation: HMC - Unscaled (no intercept) nsample = 1000 m = 20 eps = .00001 theta = np.zeros(p+1) theta = beta_true_scale.copy() phi = 5 nbatch = 500 C = 1 * np.identity(p+1) V = 0 * np.identity(p+1) M = np.identity(p+1) samples, H = run_sghmc(Y, X, U_logistic, gradU_logistic, M, eps, m, theta, C, V, phi, nsample) print(np.mean(samples, axis=0) - beta_true_unscale) plt.plot((samples - beta_true_unscale)[:,0]) plt.show() plt.plot(H) plt.show() Gradient Descent End of explanation """
epam/DLab
integration-tests/examples/test_templates/deeplearning/template_caffe2.ipynb
apache-2.0
# We'll also import a few standard python libraries from matplotlib import pyplot import numpy as np import time # These are the droids you are looking for. from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 # Let's show all plots inline. %matplotlib inline """ Explanation: Caffe2 Basic Concepts - Operators & Nets In this tutorial we will go through a set of Caffe2 basics: the basic concepts including how operators and nets are being written. First, let's import caffe2. core and workspace are usually the two that you need most. If you want to manipulate protocol buffers generated by caffe2, you probably also want to import caffe2_pb2 from caffe2.proto. End of explanation """ print("Current blobs in the workspace: {}".format(workspace.Blobs())) print("Workspace has blob 'X'? {}".format(workspace.HasBlob("X"))) """ Explanation: You might see a warning saying that caffe2 does not have GPU support. That means you are running a CPU-only build. Don't be alarmed - anything CPU is still runnable without problem. Workspaces Let's cover workspaces first, where all the data reside. If you are familiar with Matlab, workspace consists of blobs you create and store in memory. For now, consider a blob to be a N-dimensional Tensor similar to numpy's ndarray, but is contiguous. Down the road, we will show you that a blob is actually a typed pointer that can store any type of C++ objects, but Tensor is the most common type stored in a blob. Let's show what the interface looks like. Blobs() prints out all existing blobs in the workspace. HasBlob() queries if a blob exists in the workspace. For now, we don't have anything yet. End of explanation """ X = np.random.randn(2, 3).astype(np.float32) print("Generated X from numpy:\n{}".format(X)) workspace.FeedBlob("X", X) """ Explanation: We can feed blobs into the workspace using FeedBlob(). End of explanation """ print("Current blobs in the workspace: {}".format(workspace.Blobs())) print("Workspace has blob 'X'? {}".format(workspace.HasBlob("X"))) print("Fetched X:\n{}".format(workspace.FetchBlob("X"))) """ Explanation: Now, let's take a look what blobs there are in the workspace. End of explanation """ np.testing.assert_array_equal(X, workspace.FetchBlob("X")) """ Explanation: Let's verify that the arrays are equal. End of explanation """ try: workspace.FetchBlob("invincible_pink_unicorn") except RuntimeError as err: print(err) """ Explanation: Also, if you are trying to access a blob that does not exist, an error will be thrown: End of explanation """ print("Current workspace: {}".format(workspace.CurrentWorkspace())) print("Current blobs in the workspace: {}".format(workspace.Blobs())) # Switch the workspace. The second argument "True" means creating # the workspace if it is missing. workspace.SwitchWorkspace("gutentag", True) # Let's print the current workspace. Note that there is nothing in the # workspace yet. print("Current workspace: {}".format(workspace.CurrentWorkspace())) print("Current blobs in the workspace: {}".format(workspace.Blobs())) """ Explanation: One thing that you might not use immediately: you can have multiple workspaces in Python using different names, and switch between them. Blobs in different workspaces are separate from each other. You can query the current workspace using CurrentWorkspace. Let's try switching the workspace by name (gutentag) and creating a new one if it doesn't exist. End of explanation """ workspace.SwitchWorkspace("default") print("Current workspace: {}".format(workspace.CurrentWorkspace())) print("Current blobs in the workspace: {}".format(workspace.Blobs())) """ Explanation: Let's switch back to the default workspace. End of explanation """ workspace.ResetWorkspace() """ Explanation: Finally, ResetWorkspace() clears anything that is in the current workspace. End of explanation """ # Create an operator. op = core.CreateOperator( "Relu", # The type of operator that we want to run ["X"], # A list of input blobs by their names ["Y"], # A list of output blobs by their names ) # and we are done! """ Explanation: Operators Operators in Caffe2 are kind of like functions. From the C++ side, they all derive from a common interface, and are registered by type, so that we can call different operators during runtime. The interface of operators is defined in caffe2/proto/caffe2.proto. Basically, it takes in a bunch of inputs, and produces a bunch of outputs. Remember, when we say "create an operator" in Caffe2 Python, nothing gets run yet. All it does is to create the protocol buffere that specifies what the operator should be. At a later time it will be sent to the C++ backend for execution. If you are not familiar with protobuf, it is a json-like serialization tool for structured data. Find more about protocol buffers here. Let's see an actual example. End of explanation """ print("Type of the created op is: {}".format(type(op))) print("Content:\n") print(str(op)) """ Explanation: As we mentioned, the created op is actually a protobuf object. Let's show the content. End of explanation """ workspace.FeedBlob("X", np.random.randn(2, 3).astype(np.float32)) workspace.RunOperatorOnce(op) """ Explanation: OK, let's run the operator. We first feed in the input X to the workspace. Then the simplest way to run an operator is to do workspace.RunOperatorOnce(operator) End of explanation """ print("Current blobs in the workspace: {}\n".format(workspace.Blobs())) print("X:\n{}\n".format(workspace.FetchBlob("X"))) print("Y:\n{}\n".format(workspace.FetchBlob("Y"))) print("Expected:\n{}\n".format(np.maximum(workspace.FetchBlob("X"), 0))) """ Explanation: After execution, let's see if the operator is doing the right thing, which is our neural network's activation function (Relu) in this case. End of explanation """ op = core.CreateOperator( "GaussianFill", [], # GaussianFill does not need any parameters. ["Z"], shape=[100, 100], # shape argument as a list of ints. mean=1.0, # mean as a single float std=1.0, # std as a single float ) print("Content of op:\n") print(str(op)) """ Explanation: This is working if your Expected output matches your Y output in this example. Operators also take optional arguments if needed. They are specified as key-value pairs. Let's take a look at one simple example, which takes a tensor and fills it with Gaussian random variables. End of explanation """ workspace.RunOperatorOnce(op) temp = workspace.FetchBlob("Z") pyplot.hist(temp.flatten(), bins=50) pyplot.title("Distribution of Z") """ Explanation: Let's run it and see if things are as intended. End of explanation """ net = core.Net("my_first_net") print("Current network proto:\n\n{}".format(net.Proto())) """ Explanation: If you see a bell shaped curve then it worked! Nets Nets are essentially computation graphs. We keep the name Net for backward consistency (and also to pay tribute to neural nets). A Net is composed of multiple operators just like a program written as a sequence of commands. Let's take a look. When we talk about nets, we will also talk about BlobReference, which is an object that wraps around a string so we can do easy chaining of operators. Let's create a network that is essentially the equivalent of the following python math: X = np.random.randn(2, 3) W = np.random.randn(5, 3) b = np.ones(5) Y = X * W^T + b We'll show the progress step by step. Caffe2's core.Net is a wrapper class around a NetDef protocol buffer. When creating a network, its underlying protocol buffer is essentially empty other than the network name. Let's create the net and then show the proto content. End of explanation """ X = net.GaussianFill([], ["X"], mean=0.0, std=1.0, shape=[2, 3], run_once=0) print("New network proto:\n\n{}".format(net.Proto())) """ Explanation: Let's create a blob called X, and use GaussianFill to fill it with some random data. End of explanation """ print("Type of X is: {}".format(type(X))) print("The blob name is: {}".format(str(X))) """ Explanation: You might have observed a few differences from the earlier core.CreateOperator call. Basically, when we have a net, you can direct create an operator and add it to the net at the same time using Python tricks: essentially, if you call net.SomeOp where SomeOp is a registered type string of an operator, this essentially gets translated to op = core.CreateOperator("SomeOp", ...) net.Proto().op.append(op) Also, you might be wondering what X is. X is a BlobReference which basically records two things: - what its name is. You can access the name by str(X) - which net it gets created from. It is recorded by an internal variable _from_net, but most likely you won't need that. Let's verify it. Also, remember, we are not actually running anything yet, so X contains nothing but a symbol. Don't expect to get any numerical values out of it right now :) End of explanation """ W = net.GaussianFill([], ["W"], mean=0.0, std=1.0, shape=[5, 3], run_once=0) b = net.ConstantFill([], ["b"], shape=[5,], value=1.0, run_once=0) """ Explanation: Let's continue to create W and b. End of explanation """ Y = X.FC([W, b], ["Y"]) """ Explanation: Now, one simple code sugar: since the BlobReference objects know what net it is generated from, in addition to creating operators from net, you can also create operators from BlobReferences. Let's create the FC operator in this way. End of explanation """ print("Current network proto:\n\n{}".format(net.Proto())) """ Explanation: Under the hood, X.FC(...) simply delegates to net.FC by inserting X as the first input of the corresponding operator, so what we did above is equivalent to Y = net.FC([X, W, b], ["Y"]) Let's take a look at the current network. End of explanation """ from caffe2.python import net_drawer from IPython import display graph = net_drawer.GetPydotGraph(net, rankdir="LR") display.Image(graph.create_png(), width=800) """ Explanation: Too verbose huh? Let's try to visualize it as a graph. Caffe2 ships with a very minimal graph visualization tool for this purpose. Let's show that in ipython. End of explanation """ workspace.ResetWorkspace() print("Current blobs in the workspace: {}".format(workspace.Blobs())) workspace.RunNetOnce(net) print("Blobs in the workspace after execution: {}".format(workspace.Blobs())) # Let's dump the contents of the blobs for name in workspace.Blobs(): print("{}:\n{}".format(name, workspace.FetchBlob(name))) """ Explanation: So we have defined a Net, but nothing gets executed yet. Remember that the net above is essentially a protobuf that holds the definition of the network. When we actually want to run the network, what happens under the hood is: - Instantiate a C++ net object from the protobuf; - Call the instantiated net's Run() function. Before we do anything, we should clear any earlier workspace variables with ResetWorkspace(). Then there are two ways to run a net from Python. We will do the first option in the example below. Using workspace.RunNetOnce(), which instantiates, runs and immediately destructs the network. A little bit more complex and involves two steps: (a) call workspace.CreateNet() to create the C++ net object owned by the workspace, and (b) use workspace.RunNet() by passing the name of the network to it. End of explanation """ workspace.ResetWorkspace() print("Current blobs in the workspace: {}".format(workspace.Blobs())) workspace.CreateNet(net) workspace.RunNet(net.Proto().name) print("Blobs in the workspace after execution: {}".format(workspace.Blobs())) for name in workspace.Blobs(): print("{}:\n{}".format(name, workspace.FetchBlob(name))) """ Explanation: Now let's try the second way to create the net, and run it. First clear the variables with ResetWorkspace(), create the net with the workspace's net object you created earlier CreateNet(net_object), and then run the net by name with RunNet(net_name). End of explanation """ # It seems that %timeit magic does not work well with # C++ extensions so we'll basically do for loops start = time.time() for i in range(1000): workspace.RunNetOnce(net) end = time.time() print('Run time per RunNetOnce: {}'.format((end - start) / 1000)) start = time.time() for i in range(1000): workspace.RunNet(net.Proto().name) end = time.time() print('Run time per RunNet: {}'.format((end - start) / 1000)) """ Explanation: There are a few differences between RunNetOnce and RunNet, but probably the main difference is the computation time overhead. Since RunNetOnce involves serializing the protobuf to pass between Python and C and instantiating the network, it may take longer to run. Let's see in this case what the overhead is. End of explanation """
Abjad/intensive
day-3/4-command-classes.ipynb
mit
class IndicatorCommand: """ Indicator command. """ def __init__(self, indicator, selector): self.indicator = indicator self.selector = selector def __call__(self, music): for selection in self.selector(music): indicator = copy.copy(self.indicator) abjad.attach(indicator, selection) """ Explanation: Class collaboration: designing interactions between classes In the previous notebook we defined a music-maker class. In this notebook we'll define a command class. Then we'll extend our music-maker to handle these commands. This gives us the chance to study class collaboration. 1. Define the command class First we'll define an indicator command. The class will attach indicators to components picked out by a selector: End of explanation """ class MusicMaker: def __init__( self, counts, denominator, pitches, commands=None, ): self.counts = counts self.denominator = denominator self.pitches = pitches self.commands = commands or () def __call__(self, time_signatures): """ Calls music-maker on time signatures. """ time_signatures = [abjad.TimeSignature(_) for _ in time_signatures] staff = self._make_notes_and_rests( self.counts, self.denominator, time_signatures, ) self._impose_time_signatures(staff, time_signatures) self._pitch_notes(staff, self.pitches) self._call_commands(staff) return staff def _make_notes_and_rests(self, counts, denominator, time_signatures): """ Makes notes and rests. """ durations = [_.duration for _ in time_signatures] total_duration = sum(durations) talea = rmakers.Talea(counts, denominator) talea_index = 0 leaves = [] current_duration = abjad.Duration(0) while current_duration < total_duration: leaf_duration = talea[talea_index] if 0 < leaf_duration: pitch = abjad.NamedPitch("c'") else: pitch = None leaf_duration = abs(leaf_duration) if total_duration < (leaf_duration + current_duration): leaf_duration = total_duration - current_duration leaves_ = abjad.LeafMaker()([pitch], [leaf_duration]) leaves.extend(leaves_) current_duration += leaf_duration talea_index += 1 staff = abjad.Staff(leaves) return staff def _impose_time_signatures(self, staff, time_signatures): """ Imposes time signatures. """ selections = abjad.mutate.split(staff[:], time_signatures, cyclic=True) for time_signature, selection in zip(time_signatures, selections): abjad.attach(time_signature, selection[0]) measure_selections = abjad.select(staff).leaves().group_by_measure() for time_signature, measure_selection in zip(time_signatures, measure_selections): abjad.Meter.rewrite_meter(measure_selection, time_signature) def _pitch_notes(self, staff, pitches): """ Pitches notes. """ pitches = abjad.CyclicTuple(pitches) plts = abjad.select(staff).logical_ties(pitched=True) for i, plt in enumerate(plts): pitch = pitches[i] for note in plt: note.written_pitch = pitch def _call_commands(self, staff): """ Calls commands. """ for command in self.commands: command(staff) """ Explanation: 2. Extend our music-maker How can we extend our existing music-maker class to handle instances of our new indicator command? One way to do it is to pass a list of of commands to our music-maker at initialization time. The initializer of the revised music-maker implements a keyword argument to do this. Additionally, we've added a method to our music-maker to call these commands, one after the other in a stack. We've also made our music-maker callable. This means that we'll pass time signatures to our music-maker itself, rather than to any of the music-maker's public methods. And we've prefixed the music-maker's methods with underscores. This indicates that users doesn't need to know anything about these methods: users initialize a music-maker and then call it. Everything else happens behind the scenes: End of explanation """ start_beam_command = IndicatorCommand( indicator=abjad.StartBeam(), selector=abjad.select().runs().map(abjad.select().leaf(0)), ) stop_beam_command = IndicatorCommand( indicator=abjad.StopBeam(), selector=abjad.select().runs().map(abjad.select().leaf(-1)), ) start_slur_command = IndicatorCommand( indicator=abjad.StartSlur(), selector=abjad.select().runs().get([0], 2).map(abjad.select().leaf(0)), ) stop_slur_command = IndicatorCommand( indicator=abjad.StopSlur(), selector=abjad.select().runs().get([0], 2).map(abjad.select().leaf(-1)), ) accent_command = IndicatorCommand( indicator=abjad.Articulation("accent"), selector=abjad.select().runs().map(abjad.select().leaf(0)), ) staccato_command = IndicatorCommand( indicator=abjad.Articulation("staccato"), selector=abjad.select().runs().map(abjad.select().leaves()[1:]).flatten(), ) fast_music_maker = MusicMaker( counts=[1, 1, 1, 1, 1, -1], denominator=16, pitches="d' fs' a' d'' g' ef'".split(), commands=[ start_beam_command, stop_beam_command, start_slur_command, stop_slur_command, accent_command, staccato_command, ], ) staff = fast_music_maker(6 * [(3, 4), (5, 8), (4, 4)]) """ Explanation: 3. Initializing commands Now that we've extended our music-maker to handle indicator commands, we can use the two classes in conjunction. Let's try it out by making indicator commands and passing them to our music-maker: End of explanation """ score = abjad.Score([staff]) lilypond_file = abjad.LilyPondFile.new( music=score, includes=["stylesheet.ily"], ) abjad.show(lilypond_file) """ Explanation: 4. Making the score Then we enclose the staff in a score, and the score in a LilyPond file. The stylesheet is housed in the same directory as this notebook: End of explanation """
edwardd1/phys202-2015-work
assignments/assignment05/InteractEx01.ipynb
mit
%matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display """ Explanation: Interact Exercise 01 Import End of explanation """ def print_sum(a, b): """Print the sum of the arguments a and b.""" print(a+b) #raise NotImplementedError() """ Explanation: Interact basics Write a print_sum function that prints the sum of its arguments a and b. End of explanation """ interact(print_sum, a=(-10.,10.), b=(-8,8,2)); #raise NotImplementedError() assert True # leave this for grading the print_sum exercise """ Explanation: Use the interact function to interact with the print_sum function. a should be a floating point slider over the interval [-10., 10.] with step sizes of 0.1 b should be an integer slider the interval [-8, 8] with step sizes of 2. End of explanation """ def print_string(s, length=False): """Print the string s and optionally its length.""" print(s) if length == True: print (len(s)) #raise NotImplementedError() """ Explanation: Write a function named print_string that prints a string and additionally prints the length of that string if a boolean parameter is True. End of explanation """ interact(print_string, s='Hello World!', length=True) #raise NotImplementedError() assert True # leave this for grading the print_string exercise """ Explanation: Use the interact function to interact with the print_string function. s should be a textbox with the initial value "Hello World!". length should be a checkbox with an initial value of True. End of explanation """
Adamage/python-training
Lesson_01_variables_and_data_types.ipynb
apache-2.0
my_name = 'Adam' print my_name my_age = 92 your_age = 23 age_difference = my_age - your_age print age_difference """ Explanation: Python Training - Lesson 1 - Variables and Data Types Variables A variable refers to a certain value with specific type. For example, we may want to store a number, a fraction, or a name, date, maybe a list of numbers. All those need to be reachable using some name, some reference, which we create when we create a variable. After we create a variable with a value, we can peek at what's inside using "print" method. End of explanation """ a = 1 """ Explanation: How to assign values to variables? Single assignment End of explanation """ a, b, c = 1, 2, 3 print a, b, c a = b = c = d = "The same string" print a, b, c, d """ Explanation: Multiple assignment End of explanation """ type(my_age) """ Explanation: What is a reference? What is a value? You could ask: does Python use call-by-value, or call-by-reference? Neither of those, actually. Variables in Python are "names", that ALWAYS bind to some object, because mostly everything in Python is an object, a complex type. So assigning a variable means, binding this "name" to an object. Actually, each time you create a number, you are not using a classic approach, like for example in C++: int my_integer = 1; When we look at an integer in Python, it's actually an object of type 'int'. To check the type of an object, use the "type" method. End of explanation """ some_person = "Andrew" person_age = 22 print some_person, type(some_person), hex(id(some_person)) print person_age, type(person_age), hex(id(person_age)) """ Explanation: To be completely precise, let's look at creating two variables that store some names. To see where in memory does the object go, we can use method "id". To see the hex representation of this memory, as you will usually see, we can use the method "id". End of explanation """ some_person = "Jamie" person_age = 24 print some_person, type(some_person), hex(id(some_person)) print person_age, type(person_age), hex(id(person_age)) """ Explanation: Now, let's change this name to something else. End of explanation """ shared_list = [11,22] my_list = shared_list your_list = shared_list print shared_list, my_list, your_list """ Explanation: The important bit is that, even though we use the same variable "person_age", the memory address changed. The object holding integer '22' is still living somewhere on the process heap, but is no longer bound to any name, and probably will be deleted by the "Garbage Collector". The binding that exists now, if from name "person_age" to the int object "24". The same can be said about variable 'some_person'. Mutability and immutability The reason we need to talk about this, is that when you use variables in Python, you have to understand that such a "binding" can be shared! When you modify one, the other shared bindings will be modified as well! This is true for "mutable" objects. There are also "immutable" objects, that behave in a standard, standalone, not-changeable way. Immutable types: int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes Mutable types: list, dict, set, bytearray, user-defined classes End of explanation """ shared_list.append(33) print shared_list, my_list, your_list """ Explanation: Now, when we modify the binding of 'shared_list' variable, both of our variables will change also! End of explanation """ a = 111 print a, type(a) b = 111111111111111111111111111111111 print b, type(b) """ Explanation: This can be very confusing later on, if you do not grasp this right now. Feel free to play around :) Data types What is a data type? It is a way of telling our computer, that we want to store a specific kind of information in a particular variable. This allows us to access tools and mechanisms that are allowed for that type. We already mentioned that actually every time we create a variable, we create a complex type variable, or an object. This is called creating an object, or instantiating an object. Each object comes from a specific template, or how we call it in Object Oriented Programming, from a class. So when you assign a variable, you instantiate an object from a class. In Python, every data type is a class! Also, we will use some built-in tools for inspection - type() and isinstance() functions. The function type() will just say from which class does this object come from. THe function isinstance() will take an object reference, and then a class name, and will tell you if this is an instance of this class. Let's review data types used in Python (most of them). Numeric types These types allow you to store numbers. Easy. int Integers. If you create a really big integer, it will become a 'long integer', or 'long'. End of explanation """ c = 11.33333 d = 11111.33 print c, type(c) print d, type(d) """ Explanation: float Floating decimal point numbers. Used usually for everything that is not an 'int'. End of explanation """ c = 2 + 3j print c, type(c) """ Explanation: complex Complex numbers. Advanced sorceries of mathematicians. In simple terms, numbers that have two components. Historically, they were named 'real' component (regular numbers) and 'imaginary' component - marked in Python using the 'j' letter. End of explanation """ # Addition print(1+1) # Multiplication print(2*2) # Division print(4/2) # Remainder of division print(5%2) # Power print(2**4) """ Explanation: Numeric operations End of explanation """ a = "Something" b = 'Something else' print type(a), type(b) """ Explanation: Strings Represents text, or to be more specific, sequences of 'Unicode' characters. To let Python know we are using strings, put them in quotes, either single, or double. End of explanation """ name = 'Adam' print name + name print name * 3 """ Explanation: Even though strings are not numbers, you can do a lot of operations on them using the usual operators. End of explanation """ print 'Second character is: ' + name[1] """ Explanation: Actually, strings are 'lists' of characters. We will explore lists in just a moment, but I want you to become familiar with a new notation. It is based on the order of sequence. When I say, "Give me the second character of this string", I can write is as such: End of explanation """ print 'From second to fourth: ' + name[1:4] print 'The last character (or first counting from the end) is: ' + name[-1] print 'All characters, but skip every second: ' + name[0:4:2] """ Explanation: Since we are counting from 0, the second character has index = 1. Now, say I want characters from second, to fourth. End of explanation """ some_string = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAxxAAAAAAAAAAAAAAAAAAAA" substring = "xx" location = some_string.find(substring) print("Lets see what we found:") print(some_string[location:location+len(substring)]) """ Explanation: These operations are called 'slicing'. We can also find substrings in other substrings. THe result is the index, at which this substring occurs. End of explanation """ some_string = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAxxAAAAAAAAAAAAAAAAAAAA" substring = "xx" print(some_string.replace( substring , "___REPLACED___")) """ Explanation: We can also replace substrings in a bigger string. Very convenient. But more complex replacements or searches are done using regular expressions, which we will cover later End of explanation """ a = True b = False print("Is a equal to b ?") print(a==b) print("Logical AND") print(a and b) print("Logical OR") print(a or b) print("Logical value of True") print( bool(a) ) print("Logical value of an empty list") print( bool([]) ) print("Logical value of an empty string") print( bool("") ) print("Logical value of integer 0") print( bool(0) ) """ Explanation: Boolean It represents the True and False values. Variables of this type, can be only True or False. It is useful to know, that in Python we can check any variable to be True or False, even lists! We use the bool() function. End of explanation """ empty_list = [] list_from_something_else = list('I feel like Im going to explode') list_elements_defined_when_list_is_created = [1, 2, 3, 4] print empty_list print list_from_something_else print list_elements_defined_when_list_is_created """ Explanation: List Prepare to use this data type A LOT. Lists can store any objects, and have as many elements, as you like. The most important thing about lists, is that their elements are ordered. You can create a list by making an empty list, converting something else to a list, or defining elements of a list right there, when you declare it. Creating lists. End of explanation """ l = ["a", "b", "c", "d", "e"] print l[0] print l[-1] print l[1:3] """ Explanation: Selecting from lists End of explanation """ l = [] l.append(1) print l l[0] = 222 print l l.remove(1) print l l = [1,2,3,3,4,5,3,2,3,2] # Make a new list from a part of that list new = l[4:7] print new """ Explanation: Adding and removing from a list End of explanation """ # Do something for all of elements. for element in [1, 2, 3]: print element + 20 # Do something for numbers coming from a range of numbers. for number in range(0,3): print number + 20 # Do something for all of elements, but written in a short way. some_list = ['a', 'b', 'c'] print [element*2 for element in some_list] """ Explanation: Iterating over a list But lists are not only used to hold some sequences! You can iterate over a list. This means no more, no less, then doing something for each of the elements in a given range, or for all of them. We will cover the so-called 'for' loop in next lessons, but I guess you can easily imagine what this minimal example would do. End of explanation """ some_tuple = (1,3,4) print some_tuple print type(some_tuple) print len(some_tuple) print some_tuple[0] print some_tuple[-1] print some_tuple[1:2] other_tuple = 1, 2, 3 print other_tuple print type(other_tuple) # This will cause an error! You can not modify a tuple. some_tuple[1] = 22 """ Explanation: Even though the short notation is a more advanced topic, it is very elegant and 'pythonic'. This way of writing down the process of iteration is called 'list comprehensions'. Tuple A tuple is a simple data structure - it behaves pretty much like a list, except for one fact - you can not change elements of tuple after it is created! You create it the same as a list, but using normal brackets. End of explanation """ empty_dictionary = {} print empty_dictionary print type(empty_dictionary) dictionary_from_direct_definition = {"key1": 1, "key2": 33} print dictionary_from_direct_definition # Let's create a dictionary from a list of tuples dictionary_from_a_collection = dict([("a", 1), ("b", 2)]) print dictionary_from_a_collection # Let's create a dictionary from two lists some_list_with_strings = ["a", "b", "c"] some_list_with_numbers = [1,2,3] dictionary_from_two_lists = dict(zip(some_list_with_strings, some_list_with_numbers)) print dictionary_from_two_lists print type(dictionary_from_two_lists) # Let's create a dictionary from a dictionary comprehension dict_from_comprehension = {key:value for key, value in zip(some_list_with_strings, some_list_with_numbers)} print dict_from_comprehension """ Explanation: Dictionary This data structure is very useful. In essence, it stores pairs of values, first of which is always a "key", a unique identifier, and the "value", which is the connected object. A dictionary performs a mapping between keys and values. Because the key is always unique (has to be, we will find out in a minute), there is always exactly one key with specific content. A dictionary is also very efficient - finding a value in a dictionary takes only one operation, whereas searching through a list one by one could require going through the whole list. This means that for any situation, where you need to store lot's of values, that will be often used, it is much better to store them in a dictionary. Also, I recommend to read on Wikipedia on "hash maps". Creating dictionaries End of explanation """ d = {} d["a"] = 1 d["bs"] = 22 d["ddddd"] = 31 print d d.update({"b": 2, "c": 3}) print d """ Explanation: Using dictionaries Add key-value pairs End of explanation """ del d["b"] print d d.pop("c") print d """ Explanation: Remove items End of explanation """ # How many keys? print d.keys() print len(d) print len(d.keys()) # How many values? print d.values() print len(d.values()) """ Explanation: Inspect a dictionary End of explanation """ for key, value in d.items(): print key, value """ Explanation: Iterate over dictionary End of explanation """ l = ["r", "p", "s", "t"] d = {a: a for a in l} # Find "t" in list. for letter in l: if letter == "t": print "Found it!" else: print "Not yet!" # Find "t" in dictionary keys. print "In dictionary - found it! " + d["t"] """ Explanation: Example of looking for a specific thing in a list, and in a dictionary: End of explanation """ some_sequence = [1,1,1,1,2,2,2,3,3,3] some_set = set(some_sequence) print some_set some_string = "What's going ooooon?" another_set = set(some_string) print another_set some_dictionary = {"a": 2, "b": 2} print some_dictionary yet_another_set = set(some_dictionary) print yet_another_set print set(some_dictionary.values()) """ Explanation: Sets A set behaves pretty much like a mixture of a dictionary and a list. It has two features: - it only has unique values - it does not respect order of things - it has no order, like a dictionary End of explanation """
tensorflow/docs-l10n
site/ko/tutorials/images/data_augmentation.ipynb
apache-2.0
#@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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2020 The TensorFlow Authors. End of explanation """ !pip install tf-nightly import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow.keras import layers from tensorflow.keras.datasets import mnist """ Explanation: 데이터 증강 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/tutorials/images/data_augmentation"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org에서 보기</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/tutorials/images/data_augmentation.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab에서 실행</a></td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ko/tutorials/images/data_augmentation.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub에서 소스 보기</a></td> <td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ko/tutorials/images/data_augmentation.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">노트북 다운로드</a></td> </table> 개요 이 튜토리얼에서는 이미지 회전과 같은 무작위(그러나 사실적인) 변환을 적용하여 훈련 세트의 다양성을 증가시키는 기술인 데이터 증강의 예를 보여줍니다. 두 가지 방법으로 데이터 증강을 적용하는 방법을 배웁니다. 먼저, Keras 전처리 레이어를 사용하고, 그 다음으로 tf.image를 사용합니다. 설정 End of explanation """ (train_ds, val_ds, test_ds), metadata = tfds.load( 'tf_flowers', split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'], with_info=True, as_supervised=True, ) """ Explanation: 데이터세트 다운로드 이 튜토리얼에서는 tf_flowers 데이터세트를 사용합니다. 편의를 위해 TensorFlow Datasets를 사용하여 데이터세트를 다운로드합니다. 데이터를 가져오는 다른 방법을 알아보려면 이미지 로드 튜토리얼을 참조하세요. End of explanation """ num_classes = metadata.features['label'].num_classes print(num_classes) """ Explanation: 꽃 데이터세트에는 5개의 클래스가 있습니다. End of explanation """ get_label_name = metadata.features['label'].int2str image, label = next(iter(train_ds)) _ = plt.imshow(image) _ = plt.title(get_label_name(label)) """ Explanation: 데이터세트에서 이미지를 검색하고 이를 사용하여 데이터 증강을 수행하겠습니다. End of explanation """ IMG_SIZE = 180 resize_and_rescale = tf.keras.Sequential([ layers.experimental.preprocessing.Resizing(IMG_SIZE, IMG_SIZE), layers.experimental.preprocessing.Rescaling(1./255) ]) """ Explanation: Keras 전처리 레이어 사용하기 참고: 이 섹션에서 소개하는 Keras 전처리 레이어는 현재 실험적 단계입니다. 크기 및 배율 조정하기 전처리 레이어를 사용하여 이미지를 일관된 모양으로 크기 조정하고 픽셀 값의 배율을 조정할 수 있습니다. End of explanation """ result = resize_and_rescale(image) _ = plt.imshow(result) """ Explanation: 참고: 위의 배율 조정 레이어는 픽셀 값을 [0,1]로 표준화합니다. 그렇지 않고 [-1,1]을 원할 경우, Rescaling(1./127.5, offset=-1)을 작성하면 됩니다. 이러한 레이어를 이미지에 적용한 결과를 볼 수 있습니다. End of explanation """ print("Min and max pixel values:", result.numpy().min(), result.numpy().max()) """ Explanation: 픽셀이 [0-1]에 있는지 확인할 수 있습니다. End of explanation """ data_augmentation = tf.keras.Sequential([ layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"), layers.experimental.preprocessing.RandomRotation(0.2), ]) # Add the image to a batch image = tf.expand_dims(image, 0) plt.figure(figsize=(10, 10)) for i in range(9): augmented_image = data_augmentation(image) ax = plt.subplot(3, 3, i + 1) plt.imshow(augmented_image[0]) plt.axis("off") """ Explanation: 데이터 증강 데이터 증강에도 전처리 레이어를 사용할 수 있습니다. 몇 개의 전처리 레이어를 만들어 동일한 이미지에 반복적으로 적용 해 보겠습니다. End of explanation """ model = tf.keras.Sequential([ resize_and_rescale, data_augmentation, layers.Conv2D(16, 3, padding='same', activation='relu'), layers.MaxPooling2D(), # Rest of your model ]) """ Explanation: layers.RandomContrast, layers.RandomCrop, layers.RandomZoom 등 데이터 증강에 사용할 수 있는 다양한 전처리 레이어가 있습니다. 전처리 레이어를 사용하는 두 가지 옵션 중요한 절충을 통해 이러한 전처리 레이어를 사용할 수 있는 두 가지 방법이 있습니다. 옵션 1: 전처리 레이어를 모델의 일부로 만들기 End of explanation """ aug_ds = train_ds.map( lambda x, y: (resize_and_rescale(x, training=True), y)) """ Explanation: 이 경우 유의해야 할 두 가지 중요한 사항이 있습니다. 데이터 증강은 나머지 레이어와 동기적으로 기기에서 실행되며 GPU 가속을 이용합니다. model.save를 사용하여 모델을 내보낼 때 전처리 레이어가 모델의 나머지 부분과 함께 저장됩니다. 나중에 이 모델을 배포하면 레이어 구성에 따라 이미지가 자동으로 표준화됩니다. 이를 통해 서버측 논리를 다시 구현해야 하는 노력을 덜 수 있습니다. 참고: 데이터 증강은 테스트할 때 비활성화되므로 입력 이미지는 model.fit(model.evaluate 또는 model.predict가 아님) 호출 중에만 증강됩니다. 옵션 2: 데이터세트에 전처리 레이어 적용하기 End of explanation """ batch_size = 32 AUTOTUNE = tf.data.experimental.AUTOTUNE def prepare(ds, shuffle=False, augment=False): # Resize and rescale all datasets ds = ds.map(lambda x, y: (resize_and_rescale(x), y), num_parallel_calls=AUTOTUNE) if shuffle: ds = ds.shuffle(1000) # Batch all datasets ds = ds.batch(batch_size) # Use data augmentation only on the training set if augment: ds = ds.map(lambda x, y: (data_augmentation(x, training=True), y), num_parallel_calls=AUTOTUNE) # Use buffered prefecting on all datasets return ds.prefetch(buffer_size=AUTOTUNE) train_ds = prepare(train_ds, shuffle=True, augment=True) val_ds = prepare(val_ds) test_ds = prepare(test_ds) """ Explanation: 이 접근 방식에서는 Dataset.map을 사용하여 증강 이미지 배치를 생성하는 데이터세트를 만듭니다. 이 경우에는 다음과 같습니다. 데이터 증강은 CPU에서 비동기적으로 이루어지며 차단되지 않습니다. 아래와 같이 Dataset.prefetch를 사용하여 GPU에서 모델 훈련을 데이터 전처리와 중첩할 수 있습니다. 이 경우, 전처리 레이어는 model.save를 호출할 때 모델과 함께 내보내지지 않습니다. 저장하기 전에 이 레이어를 모델에 연결하거나 서버측에서 다시 구현해야 합니다. 훈련 후, 내보내기 전에 전처리 레이어를 연결할 수 있습니다. 이미지 분류 튜토리얼에서 첫 번째 옵션의 예를 볼 수 있습니다. 여기에서는 두 번째 옵션을 살펴보겠습니다. 데이터세트에 전처리 레이어 적용하기 위에서 생성한 전처리 레이어로 훈련, 검증 및 테스트 데이터세트를 구성합니다. 또한 병렬 읽기 및 버퍼링된 프리페치를 사용하여 I/O 차단 없이 디스크에서 배치를 생성하여 성능을 높이도록 데이터세트를 구성합니다. tf.data API로 성능 향상하기 가이드에서 데이터세트 성능에 대해 자세히 알아볼 수 있습니다. 참고: 데이터 증강은 훈련 세트에만 적용해야 합니다. End of explanation """ model = tf.keras.Sequential([ layers.Conv2D(16, 3, padding='same', activation='relu'), layers.MaxPooling2D(), layers.Conv2D(32, 3, padding='same', activation='relu'), layers.MaxPooling2D(), layers.Conv2D(64, 3, padding='same', activation='relu'), layers.MaxPooling2D(), layers.Flatten(), layers.Dense(128, activation='relu'), layers.Dense(num_classes) ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) epochs=5 history = model.fit( train_ds, validation_data=val_ds, epochs=epochs ) loss, acc = model.evaluate(test_ds) print("Accuracy", acc) """ Explanation: 모델 훈련하기 완성도를 높이기 위해 이제 이러한 데이터세트를 사용하여 모델을 훈련합니다. 이 모델은 정확성에 목표를 두고 조정되지 않았습니다(작동 방식을 시연하는 것이 목표임). End of explanation """ def random_invert_img(x, p=0.5): if tf.random.uniform([]) < p: x = (255-x) else: x return x def random_invert(factor=0.5): return layers.Lambda(lambda x: random_invert_img(x, factor)) random_invert = random_invert() plt.figure(figsize=(10, 10)) for i in range(9): augmented_image = random_invert(image) ax = plt.subplot(3, 3, i + 1) plt.imshow(augmented_image[0].numpy().astype("uint8")) plt.axis("off") """ Explanation: 사용자 정의 데이터 증강 사용자 정의 데이터 증강 레이어를 만들 수도 있습니다. 이 튜토리얼에서는 두 가지 방법을 소개합니다. 먼저, layers.Lambda 레이어를 생성합니다. 이것은 간결한 코드를 작성하는 좋은 방법입니다. 다음으로, 제어력을 높여주는 서브 클래스 생성을 통해 새 레이어를 작성합니다. 두 레이어는 확률에 따라 이미지의 색상을 무작위로 반전합니다. End of explanation """ class RandomInvert(layers.Layer): def __init__(self, factor=0.5, **kwargs): super().__init__(**kwargs) self.factor = factor def call(self, x): return random_invert_img(x) _ = plt.imshow(RandomInvert()(image)[0]) """ Explanation: 다음으로, 서브 클래스 생성을 통해 사용자 정의 레이어를 구현합니다. End of explanation """ (train_ds, val_ds, test_ds), metadata = tfds.load( 'tf_flowers', split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'], with_info=True, as_supervised=True, ) """ Explanation: 위의 옵션 1과 2의 설명에 따라 이 두 레이어를 모두 사용할 수 있습니다. tf.image 사용하기 위의 layers.preprocessing 유틸리티는 편리합니다. 보다 세밀한 제어를 위해서는 tf.data 및 tf.image를 사용하여 고유한 데이터 증강 파이프라인 또는 레이어를 작성할 수 있습니다. TensorFlow 애드온 이미지: 작업 및 TensorFlow I/O: 색 공간 변환도 확인해보세요. 꽃 데이터세트는 이전에 데이터 증강으로 구성되었으므로 다시 가져와서 새로 시작하겠습니다. End of explanation """ image, label = next(iter(train_ds)) _ = plt.imshow(image) _ = plt.title(get_label_name(label)) """ Explanation: 작업할 이미지를 검색합니다. End of explanation """ def visualize(original, augmented): fig = plt.figure() plt.subplot(1,2,1) plt.title('Original image') plt.imshow(original) plt.subplot(1,2,2) plt.title('Augmented image') plt.imshow(augmented) """ Explanation: 다음 함수를 사용하여 원본 이미지와 증강 이미지를 나란히 시각화하고 비교하겠습니다. End of explanation """ flipped = tf.image.flip_left_right(image) visualize(image, flipped) """ Explanation: 데이터 증강 이미지 뒤집기 이미지를 수직 또는 수평으로 뒤집습니다. End of explanation """ grayscaled = tf.image.rgb_to_grayscale(image) visualize(image, tf.squeeze(grayscaled)) _ = plt.colorbar() """ Explanation: 이미지를 회색조로 만들기 이미지를 회색조로 만듭니다. End of explanation """ saturated = tf.image.adjust_saturation(image, 3) visualize(image, saturated) """ Explanation: 이미지 포화시키기 채도 계수를 제공하여 이미지를 포화시킵니다. End of explanation """ bright = tf.image.adjust_brightness(image, 0.4) visualize(image, bright) """ Explanation: 이미지 밝기 변경하기 밝기 계수를 제공하여 이미지의 밝기를 변경합니다. End of explanation """ cropped = tf.image.central_crop(image, central_fraction=0.5) visualize(image,cropped) """ Explanation: 이미지 중앙 자르기 이미지를 중앙에서 원하는 이미지 부분까지 자릅니다. End of explanation """ rotated = tf.image.rot90(image) visualize(image, rotated) """ Explanation: 이미지 회전하기 이미지를 90도 회전합니다. End of explanation """ def resize_and_rescale(image, label): image = tf.cast(image, tf.float32) image = tf.image.resize(image, [IMG_SIZE, IMG_SIZE]) image = (image / 255.0) return image, label def augment(image,label): image, label = resize_and_rescale(image, label) # Add 6 pixels of padding image = tf.image.resize_with_crop_or_pad(image, IMG_SIZE + 6, IMG_SIZE + 6) # Random crop back to the original size image = tf.image.random_crop(image, size=[IMG_SIZE, IMG_SIZE, 3]) image = tf.image.random_brightness(image, max_delta=0.5) # Random brightness image = tf.clip_by_value(image, 0, 1) return image, label """ Explanation: 데이터세트에 증강 적용하기 이전과 마찬가지로 Dataset.map을 사용하여 데이터 증강을 데이터세트에 적용합니다. End of explanation """ train_ds = ( train_ds .shuffle(1000) .map(augment, num_parallel_calls=AUTOTUNE) .batch(batch_size) .prefetch(AUTOTUNE) ) val_ds = ( val_ds .map(resize_and_rescale, num_parallel_calls=AUTOTUNE) .batch(batch_size) .prefetch(AUTOTUNE) ) test_ds = ( test_ds .map(resize_and_rescale, num_parallel_calls=AUTOTUNE) .batch(batch_size) .prefetch(AUTOTUNE) ) """ Explanation: 데이터세트 구성하기 End of explanation """
h-mayorquin/time_series_basic
presentations/2015-11-10(Letter Frequency).ipynb
bsd-3-clause
import numpy as np import matplotlib.pyplot as plt from nltk.book import text7 as text import nltk import string print('Number of words', len(text)) text[0:10] """ Explanation: Studying Frequency on Corpus This is just to check what type of letters come in a determinate corpus and study the frequency distribution. This will serve as a template to study the structure of the text with more traditional methods before using the nexa machiner End of explanation """ print('Number of words', len(text)) concatenated_text = ' '.join(text) concatenated_text[0:50] # This is an ugly way to concatenate distribution = nltk.FreqDist(concatenated_text) # fig = plt.gcf() # fig.set_size_inches((32, 24)) distribution.plot() distribution.pprint() """ Explanation: As it can seen from the text above the text is only a list of words. Let's count the number of words and then concatenate to count the number of actual letters. End of explanation """ text_lowercase = [letter.lower() for letter in concatenated_text] distribution_low = nltk.FreqDist(text_lowercase) distribution_low.pprint() import seaborn as sns distribution_low.plot() distribution_low.keys() """ Explanation: We see that there are a lot of strange characters. We are going to transform to lowercase all the letters and then get the distribution again End of explanation """ bigrams = nltk.bigrams(text_lowercase) bigrams_freq = nltk.FreqDist(bigrams) """ Explanation: Bigrams. Now we will calculate the bigrams and their frequency for this text. End of explanation """ bigrams_freq.most_common(10) bigrams_freq.plot(20) """ Explanation: This however contains pairs with whitespaces as the most common frequency. End of explanation """ bigrams_dist_without_space = {key:value for key,value in bigrams_freq.items() if ' ' not in key} bigrams_dist_without_space """ Explanation: We can remove them by using a standar dictionary looping technique End of explanation """ bigrams = nltk.bigrams(text_lowercase) bigrams_without_space = [bigram for bigram in bigrams if ' ' not in bigram] bigrams_frequency = nltk.FreqDist(bigrams_without_space) bigrams_frequency.plot(10) """ Explanation: The problem with this approach is that we end up with a dictionary and not an nltk FreqDist object. Therefore we are deprived of handy methods like plot and most_common. Another approach is to first remove the ones with the white space from the bigrams and then construct a FreqDist that will already not count the spaces. End of explanation """
kubeflow/kfserving-lts
docs/samples/v1alpha2/custom/kfserving-custom-model/kfserving_sdk_custom_image.ipynb
apache-2.0
# Set this to be your dockerhub username # It will be used when building your image and when creating the InferenceService for your image DOCKER_HUB_USERNAME = "your_docker_username" %%bash -s "$DOCKER_HUB_USERNAME" docker build -t $1/kfserving-custom-model ./model-server %%bash -s "$DOCKER_HUB_USERNAME" docker push $1/kfserving-custom-model """ Explanation: Sample for KFServing SDK with a custom image This is a sample for KFServing SDK using a custom image. The notebook shows how to use KFServing SDK to create, get and delete InferenceService with a custom image. Setup Your ~/.kube/config should point to a cluster with KFServing installed. Your cluster's Istio Ingress gateway must be network accessible. Build the docker image we will be using. The goal of custom image support is to allow users to bring their own wrapped model inside a container and serve it with KFServing. Please note that you will need to ensure that your container is also running a web server e.g. Flask to expose your model endpoints. This example extends kfserving.KFModel which uses the tornado web server. To build and push with Docker Hub set the DOCKER_HUB_USERNAME variable below with your Docker Hub username End of explanation """ from kubernetes import client from kubernetes.client import V1Container from kfserving import KFServingClient from kfserving import constants from kfserving import utils from kfserving import V1alpha2EndpointSpec from kfserving import V1alpha2PredictorSpec from kfserving import V1alpha2InferenceServiceSpec from kfserving import V1alpha2InferenceService from kfserving import V1alpha2CustomSpec namespace = utils.get_default_target_namespace() print(namespace) """ Explanation: KFServing Client SDK We will use the KFServing client SDK to create the InferenceService and deploy our custom image. End of explanation """ api_version = constants.KFSERVING_GROUP + '/' + constants.KFSERVING_VERSION default_endpoint_spec = V1alpha2EndpointSpec( predictor=V1alpha2PredictorSpec( custom=V1alpha2CustomSpec( container=V1Container( name="kfserving-custom-model", image=f"{DOCKER_HUB_USERNAME}/kfserving-custom-model")))) isvc = V1alpha2InferenceService(api_version=api_version, kind=constants.KFSERVING_KIND, metadata=client.V1ObjectMeta( name='kfserving-custom-model', namespace=namespace), spec=V1alpha2InferenceServiceSpec(default=default_endpoint_spec)) """ Explanation: Define InferenceService Firstly define default endpoint spec, and then define the inferenceservice using the endpoint spec. To use a custom image we need to use V1alphaCustomSpec which takes a V1Container from the kuberenetes library End of explanation """ KFServing = KFServingClient() KFServing.create(isvc) """ Explanation: Create the InferenceService Call KFServingClient to create InferenceService. End of explanation """ KFServing.get('kfserving-custom-model', namespace=namespace, watch=True, timeout_seconds=120) """ Explanation: Check the InferenceService End of explanation """ MODEL_NAME = "kfserving-custom-model" %%bash --out CLUSTER_IP INGRESS_GATEWAY="istio-ingressgateway" echo "$(kubectl -n istio-system get service $INGRESS_GATEWAY -o jsonpath='{.status.loadBalancer.ingress[0].ip}')" %%bash -s "$MODEL_NAME" --out SERVICE_HOSTNAME echo "$(kubectl get inferenceservice $1 -o jsonpath='{.status.url}' | cut -d "/" -f 3)" import requests import json with open('input.json') as json_file: data = json.load(json_file) url = f"http://{CLUSTER_IP.strip()}/v1/models/{MODEL_NAME}:predict" headers = {"Host": SERVICE_HOSTNAME.strip()} result = requests.post(url, data=json.dumps(data), headers=headers) print(result.content) """ Explanation: Run a prediction End of explanation """ KFServing.delete(MODEL_NAME, namespace=namespace) """ Explanation: Delete the InferenceService End of explanation """
mne-tools/mne-tools.github.io
stable/_downloads/0602f866d20bff8af56294e10dd6854d/10_preprocessing_overview.ipynb
bsd-3-clause
import os import numpy as np import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) raw.crop(0, 60).load_data() # just use a fraction of data for speed here """ Explanation: Overview of artifact detection This tutorial covers the basics of artifact detection, and introduces the artifact detection tools available in MNE-Python. We begin as always by importing the necessary Python modules and loading some example data &lt;sample-dataset&gt;: End of explanation """ ssp_projectors = raw.info['projs'] raw.del_proj() """ Explanation: What are artifacts? Artifacts are parts of the recorded signal that arise from sources other than the source of interest (i.e., neuronal activity in the brain). As such, artifacts are a form of interference or noise relative to the signal of interest. There are many possible causes of such interference, for example: Environmental artifacts Persistent oscillations centered around the AC power line frequency_ (typically 50 or 60 Hz) Brief signal jumps due to building vibration (such as a door slamming) Electromagnetic field noise from nearby elevators, cell phones, the geomagnetic field, etc. Instrumentation artifacts Electromagnetic interference from stimulus presentation (such as EEG sensors picking up the field generated by unshielded headphones) Continuous oscillations at specific frequencies used by head position indicator (HPI) coils Random high-amplitude fluctuations (or alternatively, constant zero signal) in a single channel due to sensor malfunction (e.g., in surface electrodes, poor scalp contact) Biological artifacts Periodic QRS_-like signal patterns (especially in magnetometer channels) due to electrical activity of the heart Short step-like deflections (especially in frontal EEG channels) due to eye movements Large transient deflections (especially in frontal EEG channels) due to blinking Brief bursts of high frequency fluctuations across several channels due to the muscular activity during swallowing There are also some cases where signals from within the brain can be considered artifactual. For example, if a researcher is primarily interested in the sensory response to a stimulus, but the experimental paradigm involves a behavioral response (such as button press), the neural activity associated with the planning and executing the button press could be considered an artifact relative to signal of interest (i.e., the evoked sensory response). <div class="alert alert-info"><h4>Note</h4><p>Artifacts of the same genesis may appear different in recordings made by different EEG or MEG systems, due to differences in sensor design (e.g., passive vs. active EEG electrodes; axial vs. planar gradiometers, etc).</p></div> What to do about artifacts There are 3 basic options when faced with artifacts in your recordings: Ignore the artifact and carry on with analysis Exclude the corrupted portion of the data and analyze the remaining data Repair the artifact by suppressing artifactual part of the recording while (hopefully) leaving the signal of interest intact There are many different approaches to repairing artifacts, and MNE-Python includes a variety of tools for artifact repair, including digital filtering, independent components analysis (ICA), Maxwell filtering / signal-space separation (SSS), and signal-space projection (SSP). Separate tutorials demonstrate each of these techniques for artifact repair. Many of the artifact repair techniques work on both continuous (raw) data and on data that has already been epoched (though not necessarily equally well); some can be applied to memory-mapped_ data while others require the data to be copied into RAM. Of course, before you can choose any of these strategies you must first detect the artifacts, which is the topic of the next section. Artifact detection MNE-Python includes a few tools for automated detection of certain artifacts (such as heartbeats and blinks), but of course you can always visually inspect your data to identify and annotate artifacts as well. We saw in the introductory tutorial &lt;tut-overview&gt; that the example data includes :term:SSP projectors &lt;projector&gt;, so before we look at artifacts let's set aside the projectors in a separate variable and then remove them from the :class:~mne.io.Raw object using the :meth:~mne.io.Raw.del_proj method, so that we can inspect our data in it's original, raw state: End of explanation """ mag_channels = mne.pick_types(raw.info, meg='mag') raw.plot(duration=60, order=mag_channels, n_channels=len(mag_channels), remove_dc=False) """ Explanation: Low-frequency drifts Low-frequency drifts are most readily detected by visual inspection using the basic :meth:~mne.io.Raw.plot method, though it is helpful to plot a relatively long time span and to disable channel-wise DC shift correction. Here we plot 60 seconds and show all the magnetometer channels: End of explanation """ fig = raw.plot_psd(tmax=np.inf, fmax=250, average=True) # add some arrows at 60 Hz and its harmonics: for ax in fig.axes[1:]: freqs = ax.lines[-1].get_xdata() psds = ax.lines[-1].get_ydata() for freq in (60, 120, 180, 240): idx = np.searchsorted(freqs, freq) ax.arrow(x=freqs[idx], y=psds[idx] + 18, dx=0, dy=-12, color='red', width=0.1, head_width=3, length_includes_head=True) """ Explanation: Low-frequency drifts are readily removed by high-pass filtering at a fairly low cutoff frequency (the wavelength of the drifts seen above is probably around 20 seconds, so in this case a cutoff of 0.1 Hz would probably suppress most of the drift). Power line noise Power line artifacts are easiest to see on plots of the spectrum, so we'll use :meth:~mne.io.Raw.plot_psd to illustrate. End of explanation """ ecg_epochs = mne.preprocessing.create_ecg_epochs(raw) ecg_epochs.plot_image(combine='mean') """ Explanation: Here we see narrow frequency peaks at 60, 120, 180, and 240 Hz — the power line frequency of the USA (where the sample data was recorded) and its 2nd, 3rd, and 4th harmonics. Other peaks (around 25 to 30 Hz, and the second harmonic of those) are probably related to the heartbeat, which is more easily seen in the time domain using a dedicated heartbeat detection function as described in the next section. Heartbeat artifacts (ECG) MNE-Python includes a dedicated function :func:~mne.preprocessing.find_ecg_events in the :mod:mne.preprocessing submodule, for detecting heartbeat artifacts from either dedicated ECG channels or from magnetometers (if no ECG channel is present). Additionally, the function :func:~mne.preprocessing.create_ecg_epochs will call :func:~mne.preprocessing.find_ecg_events under the hood, and use the resulting events array to extract epochs centered around the detected heartbeat artifacts. Here we create those epochs, then show an image plot of the detected ECG artifacts along with the average ERF across artifacts. We'll show all three channel types, even though EEG channels are less strongly affected by heartbeat artifacts: End of explanation """ avg_ecg_epochs = ecg_epochs.average().apply_baseline((-0.5, -0.2)) """ Explanation: The horizontal streaks in the magnetometer image plot reflect the fact that the heartbeat artifacts are superimposed on low-frequency drifts like the one we saw in an earlier section; to avoid this you could pass baseline=(-0.5, -0.2) in the call to :func:~mne.preprocessing.create_ecg_epochs. You can also get a quick look at the ECG-related field pattern across sensors by averaging the ECG epochs together via the :meth:~mne.Epochs.average method, and then using the :meth:mne.Evoked.plot_topomap method: End of explanation """ avg_ecg_epochs.plot_topomap(times=np.linspace(-0.05, 0.05, 11)) """ Explanation: Here again we can visualize the spatial pattern of the associated field at various times relative to the peak of the EOG response: End of explanation """ avg_ecg_epochs.plot_joint(times=[-0.25, -0.025, 0, 0.025, 0.25]) """ Explanation: Or, we can get an ERP/F plot with :meth:~mne.Evoked.plot or a combined scalp field maps and ERP/F plot with :meth:~mne.Evoked.plot_joint. Here we've specified the times for scalp field maps manually, but if not provided they will be chosen automatically based on peaks in the signal: End of explanation """ eog_epochs = mne.preprocessing.create_eog_epochs(raw, baseline=(-0.5, -0.2)) eog_epochs.plot_image(combine='mean') eog_epochs.average().plot_joint() """ Explanation: Ocular artifacts (EOG) Similar to the ECG detection and epoching methods described above, MNE-Python also includes functions for detecting and extracting ocular artifacts: :func:~mne.preprocessing.find_eog_events and :func:~mne.preprocessing.create_eog_epochs. Once again we'll use the higher-level convenience function that automatically finds the artifacts and extracts them in to an :class:~mne.Epochs object in one step. Unlike the heartbeat artifacts seen above, ocular artifacts are usually most prominent in the EEG channels, but we'll still show all three channel types. We'll use the baseline parameter this time too; note that there are many fewer blinks than heartbeats, which makes the image plots appear somewhat blocky: End of explanation """
samuelsinayoko/kaggle-housing-prices
research/long_form_featureplots_seaborn.ipynb
mit
import string import pandas as pd import numpy as np import seaborn as sns """ Explanation: Distributions of multiple numerical features with Seaborn When given a set of numerical features, it is desirable to plot all of them using for example violinplots, to get a sense of their respective distributions. Seaborn can do this automatically using the violinplot function, but this doesn't work so well when the features have widely different ranges. End of explanation """ def get_random_numerical_data(size, *amplitudes): n = len(amplitudes) data = np.random.random((size, n)) * np.array(amplitudes).reshape(1, n) return pd.DataFrame(data=data, columns=pd.Series(list(string.ascii_uppercase[:n]), name="feature")) get_random_numerical_data(5, 1, 2) get_random_numerical_data(500, 1, 2, 3, 4).describe().loc[['count', 'std', 'max']] """ Explanation: Get some random data Create a function that returns a data frame where each feature is a random numerical variable where we can control the max amplitude. End of explanation """ df_small_range = get_random_numerical_data(500, 1, 2, 3, 4) sns.violinplot(df_small_range) df_big_range = get_random_numerical_data(500, 1, 10, 100, 1000) sns.violinplot(df_big_range) """ Explanation: Plotting all features directly with Seaborn Works well when the data range is small End of explanation """ df_big_range = get_random_numerical_data(500, 1, 10, 100, 1000) h = sns.violinplot(df_big_range) h.set_yscale('log') """ Explanation: Changing the y-scale to log doesn't help much End of explanation """ import matplotlib.pyplot as plt def featureplot(df, nrows=1, ncols=1, figsize=(12,8), plotfunc=sns.violinplot): """Plot the dataframe features""" width, height = figsize fig, axes = plt.subplots(nrows, ncols, figsize=(width, height * nrows)); i = 0 plots_per_figure = max(df.shape[1] // (nrows * ncols), 1) if nrows == 1 and ncols == 1: axes = [axes] if nrows > 1 and ncols > 1: axes = chain.from_iterable(axes) # flatten the nested list for j, ax in zip(range(plots_per_figure, df.shape[1] + 1, plots_per_figure), axes): plotfunc(df.iloc[:, i:j], ax=ax) i = j plt.tight_layout() featureplot(df_big_range, ncols=4) """ Explanation: Plotting distributions on separate figures using Matplotlib We could standardize all columns with Scikit Learn but then we use all sense of scale. Ideally, we want to plot each data on a separate plot. We can do this with a little matplotlib function. End of explanation """ df_big_range_lf = df_big_range.stack().reset_index(name="value").drop('level_0', axis=1)#.reset_index() # don't keep the index df_big_range_lf.head() # size is the height of each figure and aspect is the with/height aspect ratio of each figure. sns.FacetGrid(df_big_range_lf, col="feature", hue="feature", sharey=False, size=7, aspect=8/12.0/2.0).map(sns.violinplot, "value", orient="v") """ Explanation: Plotting on separate columns using Seaborn only However we can do this directly with Seaborn using a FacetGrid if we put the data in long form. End of explanation """ test = pd.DataFrame({'foo':["one"] * 3 + ["two"] * 3, 'bar': list("ABC")*2, 'baz': list(range(6))}) test test.pivot('foo', 'bar', 'baz') test.set_index(['foo','bar']).unstack()['baz'] """ Explanation: Appendix: stack vs pivot Pivot can be implemented by using set_index and unstack. End of explanation """
andersrmr/JupyterWorkflow
UnsupervisedAnalysis.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn') import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.mixture import GaussianMixture """ Explanation: Unsupervised Analysis of Days of Week Treating crossings each day of features to learn about the relationships between various days End of explanation """ from jupyterworkflow.data import get_fremont_data data = get_fremont_data() pivoted = data.pivot_table('Total', index=data.index.time, columns = data.index.date) pivoted.plot(legend=False,alpha=0.01) """ Explanation: Get Data End of explanation """ X = pivoted.fillna(0).T.values X.shape X2 =PCA(2, svd_solver='full').fit_transform(X) X2.shape import matplotlib.pyplot as plt plt.scatter(X2[:, 0], X2[:, 1]) """ Explanation: Principal Components Analysis End of explanation """ gmm = GaussianMixture(2).fit(X) labels = gmm.predict(X) np.unique(labels) plt.scatter(X2[:, 0], X2[:, 1], c=labels, cmap='rainbow') plt.colorbar() fig, ax = plt.subplots(1, 2, figsize=(14, 6)) pivoted.T[labels == 0].T.plot(legend=False, alpha=0.1, ax=ax[0]) pivoted.T[labels == 1].T.plot(legend=False, alpha=0.1, ax=ax[1]) ax[0].set_title('Purple Cluster') ax[1].set_title('Red Cluster') """ Explanation: Unsupervised Clustering End of explanation """ pd.DatetimeIndex(pivoted.columns).dayofweek dayofweek = pd.DatetimeIndex(pivoted.columns).dayofweek plt.scatter(X2[:, 0], X2[:, 1], c=dayofweek, cmap='rainbow') plt.colorbar() """ Explanation: Comparing with Day of Week End of explanation """ dates = pd.DatetimeIndex(pivoted.columns) dates[(labels==1) & (dayofweek<5)] """ Explanation: 0-4 weekdays 5, 6 weekend Analyzing Outliers The following points are weekdays with a holiday-like pattern End of explanation """
tensorflow/docs-l10n
site/ja/tfx/tutorials/data_validation/tfdv_basic.ipynb
apache-2.0
#@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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright &copy; 2020 The TensorFlow Authors. End of explanation """ try: import colab !pip install --upgrade pip except: pass """ Explanation: TensorFlow データ検証 TensorFlow Extended の主要コンポーネントの例 注意:この例は、Jupyter スタイルのノートブックで今すぐ実行できます。セットアップは必要ありません。「Google Colab で実行」をクリックするだけです。 <div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/tfx/tutorials/data_validation/tfdv_basic"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/tfx/tutorials/data_validation/tfdv_basic.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab で実行</a></td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/tfx/tutorials/data_validation/tfdv_basic.ipynb"> <img width="32px" src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub でソースを表示</a></td> </table></div> このサンプルの colab ノートブックは、TensorFlow Data Validation (TFDV) を使用してデータセットを調査および視覚化する方法を示しています。これには、記述統計の確認、スキーマの推測、異常のチェックと修正、データセットのドリフトとスキューのチェックが含まれています。実稼働環境のパイプラインでデータセットが時間の経過とともにどのように変化するかなど、データセットの特性を理解することが重要です。また、データの異常を探し、トレーニング、評価、およびサービングデータセットを比較して、それらが一貫していることを確認することも重要です。 シカゴ市からリリースされたタクシー乗車データセットのデータを使用します。 注意:このWeb サイトは、シカゴ市の公式 Web サイト www.cityofchicago.org で公開されたデータを変更して使用するアプリケーションを提供します。シカゴ市は、この Web サイトで提供されるデータの内容、正確性、適時性、または完全性について一切の表明を行いません。この Web サイトで提供されるデータは、随時変更される可能性があります。かかる Web サイトで提供されるデータはユーザーの自己責任で利用されるものとします。 データセットの詳細については、Google BigQuery を参照してください。BigQuery UI でデータセット全体をご確認ください。 キーポイント:モデラーおよび開発者の皆さんは、このデータがどのように使用されるか、モデルの予測が引き起こす可能性のある潜在的メリット・デメリットについて考えてください。このようなモデルは、社会的バイアスと格差を拡大する可能性があります。特徴は解決しようとする問題に関連していますか、それともバイアスを導入しますか? 詳細については、機械学習における公平性についてご一読ください。 データセットの列は次のとおりです。 <table> <tr> <td>pickup_community_area</td> <td>fare</td> <td>trip_start_month</td> </tr> <tr> <td>trip_start_hour</td> <td>trip_start_day</td> <td>trip_start_timestamp</td> </tr> <tr> <td>pickup_latitude</td> <td>pickup_longitude</td> <td>dropoff_latitude</td> </tr> <tr> <td>dropoff_longitude</td> <td>trip_miles</td> <td>pickup_census_tract</td> </tr> <tr> <td>dropoff_census_tract</td> <td>payment_type</td> <td>company</td> </tr> <tr> <td>trip_seconds</td> <td>dropoff_community_area</td> <td>tips</td> </tr> </table> Pip のアップグレード ローカルで実行する場合にシステム Pip をアップグレードしないようにするには、Colab で実行していることを確認してください。もちろん、ローカルシステムは個別にアップグレードできます。 End of explanation """ !pip install tensorflow==2.2.0 """ Explanation: TensorFlow のインストール 注意:Google Colab では、パッケージが更新されるため、このセルを初めて実行するときに、ランタイムを再起動([ランタイム] &gt; [ランタイムの再起動...])する必要があります。 End of explanation """ import sys # Confirm that we're using Python 3 assert sys.version_info.major is 3, 'Oops, not running Python 3. Use Runtime > Change runtime type' """ Explanation: Python バージョンのチェック End of explanation """ import tensorflow as tf print('Installing TensorFlow Data Validation') !pip install -q tensorflow_data_validation[visualization] """ Explanation: TFDV のインストール これにより、すべての依存関係が取得されます。これには1分かかります。互換性のない依存関係バージョンに関する警告またはエラーは無視します。 注意:Google Colab では、パッケージが更新されるため、このセルを初めて実行するときに、ランタイムを再起動([ランタイム] &gt; [ランタイムの再起動...])する必要があります。 End of explanation """ import os import tempfile, urllib, zipfile # Set up some globals for our file paths BASE_DIR = tempfile.mkdtemp() DATA_DIR = os.path.join(BASE_DIR, 'data') OUTPUT_DIR = os.path.join(BASE_DIR, 'chicago_taxi_output') TRAIN_DATA = os.path.join(DATA_DIR, 'train', 'data.csv') EVAL_DATA = os.path.join(DATA_DIR, 'eval', 'data.csv') SERVING_DATA = os.path.join(DATA_DIR, 'serving', 'data.csv') # Download the zip file from GCP and unzip it zip, headers = urllib.request.urlretrieve('https://storage.googleapis.com/artifacts.tfx-oss-public.appspot.com/datasets/chicago_data.zip') zipfile.ZipFile(zip).extractall(BASE_DIR) zipfile.ZipFile(zip).close() print("Here's what we downloaded:") !ls -R {os.path.join(BASE_DIR, 'data')} """ Explanation: ランタイムを再起動しましたか? Google Colab を使用している場合は、上記のセルを初めて実行するときにランタイムを再起動([ランタイム] &gt; [ランタイムの再起動...])する必要があります。これは、Colab がパッケージを読み込むために必要です。 ファイルを読み込む Google Cloud Storage からデータセットをダウンロードします。 End of explanation """ import tensorflow_data_validation as tfdv print('TFDV version: {}'.format(tfdv.version.__version__)) """ Explanation: バージョンのチェック End of explanation """ train_stats = tfdv.generate_statistics_from_csv(data_location=TRAIN_DATA) """ Explanation: 統計を計算し、視覚化する まず、tfdv.generate_statistics_from_csvを使用して、トレーニングデータの統計を計算します。(警告は無視します) TFDV は、記述統計を計算し、存在する特徴やそれらの値分布の形などを含むデータの概要を迅速に提供します。 内部的には、TFDV はApache Beamのデータ並列処理フレームワークを使用して、大規模なデータセットの統計計算をスケーリングします。アプリケーションを TFDV とより深く統合させるには(データ生成パイプラインの最後に統計生成をアタッチする場合など)、API は統計生成用の Beam PTransform も公開します。 End of explanation """ tfdv.visualize_statistics(train_stats) """ Explanation: 次に、tfdv.visualize_statisticsを使用します。これは、ファセットを使用して、トレーニングデータの簡潔な視覚化を作成します。 数値の特徴とカテゴリの特徴が別々に視覚化され、各特徴の分布を示すグラフが表示されます。 値が欠落しているかゼロの特徴は、それらの特徴の例に問題がある可能性があることを視覚的に示すために、パーセンテージが赤で表示されることに注意してください。パーセンテージは、その特徴の値が欠落しているかゼロである例のパーセンテージです。 pickup_census_tractの値を持つ例がないことに注意してください。これは次元削減の機会です。 グラフの上にある[展開]をクリックして、表示を変更してみてください グラフのバーにカーソルを合わせて、バケットの範囲とカウントを表示してみてください 対数目盛と線形目盛を切り替えてみてください。対数目盛がpayment_typeカテゴリカル特徴の詳細をどのように示しているかに注目してください。 [表示するグラフ]メニューから[分位数]を選択し、マーカーにカーソルを合わせて分位数のパーセンテージを表示してみてください End of explanation """ schema = tfdv.infer_schema(statistics=train_stats) tfdv.display_schema(schema=schema) """ Explanation: スキーマを推測する 次に、tfdv.infer_schemaを使用してデータのスキーマを作成しましょう。<br>スキーマは、機械学習に関連するデータの制約を定義します。制約の例には、各特徴のデータ型(数値、または、カテゴリ)、またはデータ内に存在する頻度が含まれます。カテゴリカル特徴の場合、スキーマはドメイン(許容値のリスト)も定義します。スキーマの作成は、特に多くの特徴を備えたデータセットの場合、手間のかかる作業になる可能性があるため、TFDV は、記述統計に基づいてスキーマの初期バージョンを生成する方法を提供します。 実稼働環境のパイプラインの残りの部分は、TFDV が生成するスキーマが正しいことに依存するため、スキーマを正しく作成することが重要です。スキーマはデータのドキュメントも提供するため、異なる開発者が同じデータで作業する場合に役立ちます。tfdv.display_schemaを使用して、推測されたスキーマを表示し、確認します。 End of explanation """ # Compute stats for evaluation data eval_stats = tfdv.generate_statistics_from_csv(data_location=EVAL_DATA) # Compare evaluation data with training data tfdv.visualize_statistics(lhs_statistics=eval_stats, rhs_statistics=train_stats, lhs_name='EVAL_DATASET', rhs_name='TRAIN_DATASET') """ Explanation: 評価データにエラーがないか確認します これまでは、トレーニングデータのみを見てきましたが、評価データがトレーニングデータと一致していること(同じスキーマを使用していることなど)を確認することが重要です。また、評価データに、トレーニングデータとほぼ同じ数値の範囲の特徴の例が含まれていることも重要です。カテゴリカル特徴でも同じです。そうでない場合、損失面の一部を評価しなかったため、評価中に特定されないトレーニングの問題が発生する可能性があります。 各特徴には、トレーニングデータセットと評価データセットの両方の統計が含まれていることに注意してください。 チャートにトレーニングデータセットと評価データセットの両方がオーバーレイされ、それらを簡単に比較できるようになっています。 チャートにはパーセンテージビューが含まれています。これは、ログまたはデフォルトの線形スケールと組み合わせることができます。 trip_milesの平均と中央値は、トレーニングデータセットと評価データセットで異なることに注意してください。これは問題を引き起こすでしょうか? 最大tipsは、トレーニングデータセットと評価データセットで大きく異なります。これは問題を引き起こすでしょうか? 数値特徴チャートの展開をクリックし、対数スケールを選択します。trip_seconds特徴を確認し、最大値の違いに注目してください。評価は損失面の一部を見逃すでしょうか? End of explanation """ # Check eval data for errors by validating the eval data stats using the previously inferred schema. anomalies = tfdv.validate_statistics(statistics=eval_stats, schema=schema) tfdv.display_anomalies(anomalies) """ Explanation: 評価の異常をチェックします 評価データセットは、トレーニングデータセットのスキーマと一致していますか?これは、許容値の範囲を特定するカテゴリカル特徴にとって特に重要です。 キーポイント:トレーニングデータセットにないカテゴリカル特徴値を持つデータを使用して評価しようとするとどうなるでしょうか?トレーニングデータセットの範囲外の数値特徴はどうなるでしょうか? End of explanation """ # Relax the minimum fraction of values that must come from the domain for feature company. company = tfdv.get_feature(schema, 'company') company.distribution_constraints.min_domain_mass = 0.9 # Add new value to the domain of feature payment_type. payment_type_domain = tfdv.get_domain(schema, 'payment_type') payment_type_domain.value.append('Prcard') # Validate eval stats after updating the schema updated_anomalies = tfdv.validate_statistics(eval_stats, schema) tfdv.display_anomalies(updated_anomalies) """ Explanation: スキーマの評価の異常を修正する 評価データにはcompanyの新しい値がいくつかありますが、トレーニングデータにはありません。また、payment_typeの新しい値もあります。これらは異常と見なす必要がありますが、それらに対して何をするかは、データに関するドメイン知識によって異なります。異常が本当にデータエラーを示している場合は、基になるデータを修正する必要があります。それ以外の場合は、スキーマを更新して、評価データセットに値を含めることができます。 キーポイント:これらの問題を修正しなかった場合、評価結果にどのような影響があるでしょうか? 評価データセットを変更しない限り、すべてを修正することはできませんが、受け入れやすいスキーマ内のものを修正することはできます。例えば、特定の特徴の異常とは何かという見方を見直したり、カテゴリカル特徴の欠落値を含めるようにスキーマを更新したりできます。TFDV を利用することにより、修正が必要なものを見つけることができます。 これらの修正を行ってから、もう一度確認します。 End of explanation """ serving_stats = tfdv.generate_statistics_from_csv(SERVING_DATA) serving_anomalies = tfdv.validate_statistics(serving_stats, schema) tfdv.display_anomalies(serving_anomalies) """ Explanation: TFDV を使用してトレーニング データと評価データが一致することを確認しました。 スキーマの環境変数 また、この例では「サービング」データセットを分割しているので、それも確認する必要があります。デフォルトでは、パイプライン内のすべてのデータセットは同じスキーマを使用する必要がありますが、多くの場合、例外があります。たとえば、教師あり学習では、データセットにラベルを含める必要がありますが、推論用のモデルを提供する場合、ラベルは含まれません。場合によっては、スキーマをわずかに変更する必要があります。 環境を使用して、このような要件を表すことができます。特に、スキーマの特徴は、default_environment、in_environment、および、not_in_environmentを使用して一連の環境に関連付けることができます。 たとえば、このデータセットでは、特徴Tipsがトレーニングのラベルとして含まれていますが、サービングデータにありません。環境を指定しないと、異常として表示されます。 End of explanation """ options = tfdv.StatsOptions(schema=schema, infer_type_from_schema=True) serving_stats = tfdv.generate_statistics_from_csv(SERVING_DATA, stats_options=options) serving_anomalies = tfdv.validate_statistics(serving_stats, schema) tfdv.display_anomalies(serving_anomalies) """ Explanation: 以下では特徴tipsについて説明します。また、スキーマは乗車期間(秒)として浮動小数点数型の値を期待していましたが整数型の値があります。TFDV は、その違いを見つけ、生成されるトレーニングテータとサービングデータの不整合を明らかにします。モデルのパフォーマンスが(時には破壊的に)低下するまで、このような問題に気付かないことがよくあります。これが重大な問題であってもなくても、調査する必要があります。 この場合、整数値を浮上小数点に安全に変換できます。以下のとおり、スキーマを使用して型を推測するように TFDV に指示します。 End of explanation """ # All features are by default in both TRAINING and SERVING environments. schema.default_environment.append('TRAINING') schema.default_environment.append('SERVING') # Specify that 'tips' feature is not in SERVING environment. tfdv.get_feature(schema, 'tips').not_in_environment.append('SERVING') serving_anomalies_with_env = tfdv.validate_statistics( serving_stats, schema, environment='SERVING') tfdv.display_anomalies(serving_anomalies_with_env) """ Explanation: これで、特徴tips(ラベル)が異常として表示されます(「列がドロップされました」)。サービングデータにラベルが含まれることは想定されていないため、TFDV にそれを無視するように指示します。 End of explanation """ # Add skew comparator for 'payment_type' feature. payment_type = tfdv.get_feature(schema, 'payment_type') payment_type.skew_comparator.infinity_norm.threshold = 0.01 # Add drift comparator for 'company' feature. company=tfdv.get_feature(schema, 'company') company.drift_comparator.infinity_norm.threshold = 0.001 skew_anomalies = tfdv.validate_statistics(train_stats, schema, previous_statistics=eval_stats, serving_statistics=serving_stats) tfdv.display_anomalies(skew_anomalies) """ Explanation: ドリフトとスキューのチェック TFDV は、データセットがスキーマで設定された期待値に準拠しているかどうかを確認する他、リフトとスキューを検出する機能も提供します。TFDV は、スキーマで指定されたドリフト/スキューコンパレータに基づいてさまざまなデータセットの統計を比較することにより、このチェックを実行します。 ドリフト ドリフト検知は、カテゴリカルな特徴量で、連続したスパン (言い換えるとスパン N とスパン N+1 ) のデータ、例えば異なる日付の訓練データについてサポートしています。ここで、ドリフトはL-無限大 距離に基いて表されます。また、ドリフトが許容可能でないほど高い値をとった場合に警告を受け取るように、距離のしきい値を設定できます。正しく距離を設定することは、典型的にはドメイン知識や試行錯誤が必要な反復的なプロセスになります。 歪度 TFDV は、データ内の3種類の歪度(スキーマ歪度、特徴歪度、および分布歪度)を検出します。 スキーマ歪度 スキーマ歪度は、トレーニングデータとサービングデータが同じスキーマに準拠していない場合に発生します。トレーニングデータとサービングデータの両方が同じスキーマに準拠することが期待されます。 これらの間に予想される偏差(ラベル機能はトレーニングデータにのみ存在し、サービングには存在しないなど)は、スキーマの環境フィールドで指定する必要があります。 特徴量の歪度 特徴量の歪度は、モデルがトレーニングする特徴値が、サービング時に表示される特徴値と異なる場合に発生します。たとえば、これは次の場合に発生する可能性があります。 特徴量を生成するデータソースがトレーニング時から実稼働環境に移行する間に修正される場合 トレーニング時と実稼働環境とで特徴量を生成するロジックが一貫していない場合。例えば、何らかの変換処理をどちらか一方のコードにしか追加していない場合。 分布歪度 分布の偏りは特徴量の分布が実稼働環境のデータの分布と著しく異なるときに生じます。分布の偏りが生じる主要な原因の1つは、トレーニングデータセットを生成するために異なるコードまたは異なるデータソースを使用することです。もう1つの理由は、サンプリングメカニズムの欠陥で、代表的でないサービングデータのサブサンプルがトレーニングされる場合です。 End of explanation """ from tensorflow.python.lib.io import file_io from google.protobuf import text_format file_io.recursive_create_dir(OUTPUT_DIR) schema_file = os.path.join(OUTPUT_DIR, 'schema.pbtxt') tfdv.write_schema_text(schema, schema_file) !cat {schema_file} """ Explanation: この例では、多少のドリフトが見られますが、設定したしきい値をはるかに下回っています。 スキーマの凍結 スキーマがレビューおよびキュレートされたので、「凍結」状態を反映するようにスキーマをファイルに保存します。 End of explanation """
zhenxinlei/SpringSecurity1
ex1/ex1.ipynb
epl-1.0
import csv import pandas as pd import numpy as np from numpy import genfromtxt data = pd.read_csv('./ex1data1.csv', delimiter=',', names=['population','profit']) data.head() %matplotlib inline ''' import matplotlib.pyplot as plt x= data['population'] y= data['profit'] plt.plot(x,y,'rx') plt.ylabel('profit in $10,000s') plt.xlabel('population in 10,000s') plt.show() ''' data.plot(x='population',y='profit',kind='scatter', figsize=(12,8)) """ Explanation: Read and plot data The file ex1data1.csv contains dataset first column is population in a city ; second column is the profit in that city End of explanation """ def computeCost(X,Y, theta ): inner= np.power(((X*theta.T)-Y),2) return np.sum(inner)/(2*len(X)) def h(theta, x ): return theta*x.T data.insert(0,'Ones',1) data.head() x=data.iloc[:,0:2] y=data.iloc[:,2:3] print("x=", x.head()," \n y=", y.head()) X= np.matrix(x.values) Y= np.matrix(y.values) theta = np.matrix(np.array([0,0])) theta.shape, X.shape, Y.shape computeCost(X,Y, theta ) """ Explanation: Object for linear regression is to minimize the cost function $$J(\theta)=\frac{1}{2m} \sum_{i=1}^m(h_{\theta}(x^{(i)})-y^{(i)})^2$$ where $h_{\theta}(x)$ is given by the linear model: $$ h_{\theta}(x) = \theta^T x = \theta_0+\theta_1 x_1$$ End of explanation """ alpha = 1e-2 iteration = 1000 error = 1e-8 def gradientDescent( X,Y, theta, alpha, iters): temp = np.matrix(np.zeros(theta.shape)) parameters = int(theta.ravel().shape[1]) cost = np.zeros(iters) for i in range(iters): error = (X * theta.T) - Y for j in range(parameters): term = np.multiply(error, X[:,j]) temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term)) theta = temp #print(theta) cost[i] = computeCost(X, Y, theta) return theta, cost g, cost = gradientDescent(X,Y, theta, alpha, iteration) g computeCost(X, Y, g) """ Explanation: Update $\theta$ with step $\alpha$ (learning rate ) to minimize $J(\theta)$ $$\theta_j := \theta_j - \alpha \frac{1}{m} \sum_{i=1}^m(h_{\theta}(x^{(i)})-y^{(i)}) x_j^{(i)} $$ End of explanation """ x = np.linspace(data.population.min(), data.population.max(),100) predict = g[0,0]+ g[0, 1]*x fig, ax = plt.subplots(figsize=(12,8)) ax.plot(x, predict, 'r', label='Prediction') ax.scatter(data.population, data.profit, label='Traning Data') ax.legend(loc=2) ax.set_xlabel('Population') ax.set_ylabel('Profit') ax.set_title('Predicted Profit vs. Population Size') """ Explanation: plot linear line with opimized $\theta$ End of explanation """ fig, ax = plt.subplots(figsize=(12,8)) ax.plot(np.arange(iteration), cost, 'r') ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title('Error vs. Training Epoch') """ Explanation: Visualizing $J(\theta)$ End of explanation """ data2 = pd.read_csv('./ex1data2.csv', delimiter=',', names=['size','bedroom','price']) data2.head() def featureNormalize(X, Y): row, col = X.shape #for i in range(col): # X.iloc[:,i]=(X.iloc[:,i]-X.iloc[:,i].mean())/X.iloc[:,i].std() X = (X-X.mean())/X.std() Y = (Y-Y.mean())/Y.std() #print(X) return X,Y x,y = featureNormalize(data2.iloc[:,0:2],data2.iloc[:,2:3]) x.insert(0,'ones',1) x = np.matrix(x.values) y = np.matrix(y.values) theta = np.matrix(np.array([0,0,0])) g, cost = gradientDescent(x,y ,theta, 0.01, iteration) computeCost(x,y,g),g fig, ax = plt.subplots(figsize=(12,8)) for i in [.1,0.01,0.001]: g, cost = gradientDescent(x,y ,theta, i, iteration) ax.plot(np.arange(iteration), cost) ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title('Error vs. Training Epoch') """ Explanation: Linear regression with multiple variables End of explanation """ g, cost = gradientDescent(x,y ,theta, 0.01, iteration) xtest = np.array([1650,3]) xtestscaled = (xtest- data2.iloc[:,0:2].mean())/data2.iloc[:,0:2].std() xtestscaled = np.matrix(xtestscaled.values) ones = np.ones((1,1)) xtestscaled = np.hstack((ones,xtestscaled)) #print( xtestscaled,g) pre_y= h(g, xtestscaled) #print(pre_y[0,0]) pre_y = pre_y [0,0]* data2.iloc[:,2:3].std()+ data2.iloc[:,2:3].mean() pre_y """ Explanation: predict price of house 1650 sqfeet and 3 bedrooms End of explanation """ from sklearn import linear_model x=data2.iloc[:,0:2].values.reshape(-1,2) y=data2.iloc[:,2:3] model = linear_model.LinearRegression() model.fit(x, y) pre_y = model.predict([[1650,3]]) print( " predicted y (price) ", pre_y[0,0]) """ Explanation: compare with sklearn Linear Regression model End of explanation """
karlstroetmann/Algorithms
Python/Chapter-06/Stack.ipynb
gpl-2.0
class Stack: pass S = Stack() S """ Explanation: Implementing a Stack Class First, we define an empty class Stack. End of explanation """ def stack(S): S.mStackElements = [] """ Explanation: Next we define a constructor for this class. The function stack(S) takes an uninitialized, empty object S and initializes its member variable mStackElements. This member variable is a list containing the data stored in the stack. End of explanation """ Stack.__init__ = stack del stack """ Explanation: We add this method to the class Stack. Since we add it under the name __init__, this method will be the constructor. Furthermore, to keep the environment tidy, we delete the function stack. End of explanation """ def push(S, e): S.mStackElements += [e] """ Explanation: Next, we add the method push to the class Stack. The method $\texttt{push}(S, e)$ pushes $e$ onto the stack $S$. End of explanation """ Stack.push = push del push """ Explanation: We add this method to the class Stack. End of explanation """ def pop(S): assert len(S.mStackElements) > 0, "popping empty stack" S.mStackElements = S.mStackElements[:-1] Stack.pop = pop del pop """ Explanation: The method pop removes the topmost element from a stack. It is an error to pop an empty stack. End of explanation """ def top(S): assert len(S.mStackElements) > 0, "top of empty stack" return S.mStackElements[-1] Stack.top = top del top """ Explanation: The method top returns the element that is on top of the stack. It is an error to call this method if the stack is empty. End of explanation """ def isEmpty(S): return S.mStackElements == [] Stack.isEmpty = isEmpty del isEmpty """ Explanation: The method S.isEmpty() checks whether the stack S is empty. End of explanation """ def copy(S): C = Stack() C.mStackElements = S.mStackElements[:] return C Stack.copy = copy del copy """ Explanation: The method S.copy() creates a shallow copy of the given stack, i.e. the copy contains the same objects as the stack S. End of explanation """ def toStr(S): C = S.copy() result = C._convert() dashes = "-" * len(result) return '\n'.join([dashes, result, dashes]) Stack.__str__ = toStr del toStr """ Explanation: The method S.toStr() converts a stack S into a string. Note that we assign it to the method __str__. This method is called automatically when an object of class Stack is cast into a string. End of explanation """ def convert(S): if S.isEmpty(): return '|' top = S.top() S.pop() return S._convert() + ' ' + str(top) + ' |' Stack._convert = convert del convert """ Explanation: The method convert converts a stack into a string. End of explanation """ def createStack(L): S = Stack() for x in L: S.push(x) print(S) return S S = createStack(range(10)) S """ Explanation: Testing The method createStack(L) takes a list L and pushes all of its elements on a newly created stack, which is then returned. End of explanation """ Stack.__repr__ = Stack.__str__ S for i in range(10): print(S.top()) S.pop() print(S) """ Explanation: By defining the function S.__repr__() for stack objects, we can print stacks in Jupyter notebooks without calling the function print. End of explanation """
natashabatalha/PandExo
notebooks/JWST_Running_Pandexo_w_ExoMAST.ipynb
gpl-3.0
import warnings warnings.filterwarnings('ignore') import pandexo.engine.justdoit as jdi import numpy as np import os """ Explanation: Getting Started Before starting here, all the instructions on the installation page should be completed! Here you will learn how to: set planet and star properties using exomast run default instrument modes adjust instrument modes run pandexo End of explanation """ exo_dict = jdi.load_exo_dict('HD 189733 b') """ Explanation: Load Exo Dict for Specific Planet To start, load in a blank exoplanet dictionary with empty keys. You will fill these out for yourself in the next step. End of explanation """ exo_dict['observation']['sat_level'] = 80 #saturation level in percent of full well exo_dict['observation']['sat_unit'] = '%' exo_dict['observation']['noccultations'] = 2 #number of transits exo_dict['observation']['R'] = None #fixed binning. I usually suggest ZERO binning.. you can always bin later #without having to redo the calcualtion exo_dict['observation']['baseline_unit'] = 'total' #Defines how you specify out of transit observing time #'frac' : fraction of time in transit versus out = in/out #'total' : total observing time (seconds) exo_dict['observation']['baseline'] = 4.0*60.0*60.0 #in accordance with what was specified above (total observing time) exo_dict['observation']['noise_floor'] = 0 #this can be a fixed level or it can be a filepath #to a wavelength dependent noise floor solution (units are ppm) """ Explanation: Edit exoplanet observation inputs Editting each keys are annoying. But, do this carefully or it could result in nonsense runs End of explanation """ exo_dict['planet']['type'] ='user' #tells pandexo you are uploading your own spectrum exo_dict['planet']['exopath'] = 'wasp12b.txt' exo_dict['planet']['w_unit'] = 'cm' #other options include "um","nm" ,"Angs", "sec" (for phase curves) exo_dict['planet']['f_unit'] = 'rp^2/r*^2' #other options are 'fp/f*' """ Explanation: Edit exoplanet inputs using one of three options 1) user specified 2) constant value 3) select from grid 1) Edit exoplanet planet inputs if using your own model End of explanation """ exo_dict['planet']['type'] = 'constant' #tells pandexo you want a fixed transit depth exo_dict['planet']['f_unit'] = 'rp^2/r*^2' #this is what you would do for primary transit #ORRRRR.... #if you wanted to instead to secondary transit at constant temperature exo_dict['planet']['f_unit'] = 'fp/f*' exo_dict['planet']['temp'] = 1000 """ Explanation: 2) Users can also add in a constant temperature or a constant transit depth End of explanation """ exo_dict['planet']['type'] = 'grid' #tells pandexo you want to pull from the grid exo_dict['planet']['temp'] = 1000 #grid: 500, 750, 1000, 1250, 1500, 1750, 2000, 2250, 2500 exo_dict['planet']['chem'] = 'noTiO' #options: 'noTiO' and 'eqchem', noTiO is chemical eq. without TiO exo_dict['planet']['cloud'] = 'ray10' #options: nothing: '0', """ Explanation: 3) Select from grid NOTE: Currently only the fortney grid for hot Jupiters from Fortney+2010 is supported. Holler though, if you want another grid supported End of explanation """ #jdi.print_instruments() result = jdi.run_pandexo(exo_dict,['NIRCam F322W2']) inst_dict = jdi.load_mode_dict('NIRSpec G140H') #loading in instrument dictionaries allow you to personalize some of #the fields that are predefined in the templates. The templates have #the subbarays with the lowest frame times and the readmodes with 1 frame per group. #if that is not what you want. change these fields #Try printing this out to get a feel for how it is structured: print(inst_dict['configuration']) #Another way to display this is to print out the keys inst_dict.keys() """ Explanation: Load in instrument dictionary (OPTIONAL) Step 2 is optional because PandExo has the functionality to automatically load in instrument dictionaries. Skip this if you plan on observing with one of the following and want to use the subarray with the smallest frame time and the readout mode with 1 frame/1 group (standard): - NIRCam F444W - NIRSpec Prism - NIRSpec G395M - NIRSpec G395H - NIRSpec G235H - NIRSpec G235M - NIRCam F322W - NIRSpec G140M - NIRSpec G140H - MIRI LRS - NIRISS SOSS End of explanation """ print("SUBARRAYS") print(jdi.subarrays('nirspec')) print("FILTERS") print(jdi.filters('nircam')) print("DISPERSERS") print(jdi.dispersers('nirspec')) #you can try personalizing some of these fields inst_dict["configuration"]["detector"]["ngroup"] = 'optimize' #running "optimize" will select the maximum #possible groups before saturation. #You can also write in any integer between 2-65536 inst_dict["configuration"]["detector"]["subarray"] = 'substrip256' #change the subbaray """ Explanation: Don't know what instrument options there are? End of explanation """ inst_dict['background'] = 'ecliptic' inst_dict['background_level'] = 'high' """ Explanation: Adjusting the Background Level You may want to think about adjusting the background level of your observation, based on the position of your target. PandExo two options and three levels for the position: ecliptic or minzodi low, medium, high End of explanation """ inst_dict = jdi.load_mode_dict('NIRISS SOSS') inst_dict['strategy']['order'] = 2 inst_dict['configuration']['detector']['subarray'] = 'substrip256' ngroup_from_order1_run = 2 inst_dict["configuration"]["detector"]["ngroup"] = ngroup_from_order1_run """ Explanation: Running NIRISS SOSS Order 2 PandExo only will extract a single order at a time. By default, it is set to extract Order 1. Below you can see how to extract the second order. NOTE! Users should be careful with this calculation. Saturation will be limited by the first order. Therefore, I suggest running one calculation with ngroup='optmize' for Order 1. This will give you an idea of a good number of groups to use. Then, you can use that in this order 2 calculation. End of explanation """ jdi.print_instruments() result = jdi.run_pandexo(exo_dict,['NIRCam F322W2']) """ Explanation: Running PandExo You have four options for running PandExo. All of them are accessed through attribute jdi.run_pandexo. See examples below. jdi.run_pandexo(exo, inst, param_space = 0, param_range = 0,save_file = True, output_path=os.getcwd(), output_file = '') Option 1- Run single instrument mode, single planet If you forget which instruments are available run jdi.print_isntruments() and pick one End of explanation """ inst_dict = jdi.load_mode_dict('NIRSpec G395M') #personalize subarray inst_dict["configuration"]["detector"]["subarray"] = 'sub2048' result = jdi.run_pandexo(exo_dict, inst_dict) np.mea(result['FinalSpectrum']['spectrum_w_rand']) """ Explanation: Option 2- Run single instrument mode (with user dict), single planet This is the same thing as option 1 but instead of feeding it a list of keys, you can feed it a instrument dictionary (this is for users who wanted to simulate something NOT pre defined within pandexo) End of explanation """ #choose select result = jdi.run_pandexo(exo_dict,['NIRSpec G140M','NIRSpec G235M','NIRSpec G395M'], output_file='three_nirspec_modes.p') #run all #result = jdi.run_pandexo(exo_dict, ['RUN ALL'], save_file = False) """ Explanation: Option 3- Run several modes, single planet Use several modes from print_isntruments() options. End of explanation """ #looping over different exoplanet models jdi.run_pandexo(exo_dict, ['NIRCam F444W'], param_space = 'planet+exopath', param_range = os.listdir('/path/to/location/of/models'), output_path = '/path/to/output/simulations') #looping over different stellar temperatures jdi.run_pandexo(exo_dict, ['NIRCam F444W'], param_space = 'star+temp', param_range = np.linspace(5000,8000,2), output_path = '/path/to/output/simulations') #looping over different saturation levels jdi.run_pandexo(exo_dict, ['NIRCam F444W'], param_space = 'observation+sat_level', param_range = np.linspace(.5,1,5), output_path = '/path/to/output/simulations') """ Explanation: Option 4- Run single mode, several planet cases Use a single modes from print_isntruments() options. But explore parameter space with respect to any parameter in the exo dict. The example below shows how to loop over several planet models You can loop through anything in the exoplanet dictionary. It will be planet, star or observation followed by whatever you want to loop through in that set. i.e. planet+exopath, star+temp, star+metal, star+logg, observation+sat_level.. etc End of explanation """
rusucosmin/courses
ml/ex01/solution/taskB.ipynb
mit
np.random.seed(10) p, q = (np.random.rand(i, 2) for i in (4, 5)) p_big, q_big = (np.random.rand(i, 80) for i in (100, 120)) print(p, "\n\n", q) """ Explanation: Data Generation End of explanation """ def naive(p, q): result = np.zeros((p.shape[0], q.shape[0])) for i in range(p.shape[0]): for j in range(q.shape[0]): tmp = 0 for k in range(p.shape[1]): tmp += (p[i,k]-q[j,k])**2 result[i,j] = tmp return np.sqrt(result) def naive_2(p, q): result = np.zeros((p.shape[0], q.shape[0])) for i in range(p.shape[0]): for j in range(q.shape[0]): result[i,j] = np.sum((p[i]-q[j])**2) return np.sqrt(result) """ Explanation: Solution End of explanation """ rows, cols = np.indices((p.shape[0], q.shape[0])) print(rows, end='\n\n') print(cols) print(p[rows.ravel()], end='\n\n') print(q[cols.ravel()]) def with_indices(p, q): rows, cols = np.indices((p.shape[0], q.shape[0])) distances = np.sqrt(np.sum((p[rows.ravel(), :] - q[cols.ravel(), :])**2, axis=1)) return distances.reshape((p.shape[0], q.shape[0])) def with_indices_2(p, q): rows, cols = np.indices((p.shape[0], q.shape[0])) distances = np.sqrt(np.sum((p[rows, :] - q[cols, :])**2, axis=2)) return distances """ Explanation: Use matching indices Instead of iterating through indices, one can use them directly to parallelize the operations with Numpy. End of explanation """ from scipy.spatial.distance import cdist def scipy_version(p, q): return cdist(p, q) """ Explanation: Use a library scipy is the equivalent of matlab toolboxes and have a lot to offer. Actually the pairwise computation is part of the library through the spatial module. End of explanation """ def tensor_broadcasting(p, q): return np.sqrt(np.sum((p[:,np.newaxis,:]-q[np.newaxis,:,:])**2, axis=2)) """ Explanation: Numpy Magic End of explanation """ methods = [naive, naive_2, with_indices, with_indices_2, scipy_version, tensor_broadcasting] timers = [] for f in methods: r = %timeit -o f(p_big, q_big) timers.append(r) plt.figure(figsize=(10,6)) plt.bar(np.arange(len(methods)), [r.best*1000 for r in timers], log=False) # Set log to True for logarithmic scale plt.xticks(np.arange(len(methods))+0.2, [f.__name__ for f in methods], rotation=30) plt.xlabel('Method') plt.ylabel('Time (ms)') plt.show() """ Explanation: Compare methods End of explanation """
cni/psych204a
mrImaging.ipynb
gpl-2.0
%pylab inline import matplotlib as mpl mpl.rcParams["figure.figsize"] = (8, 6) mpl.rcParams["axes.grid"] = True from IPython.display import display, clear_output from time import sleep """ Explanation: MR Imaging Class: Psych 204a Tutorial: MR Imaging Author: Wandell Date: 03.15.04 Duration: 90 minutes Copyright: Stanford University, Brian A. Wandell Checked: Oct 2007: Rory Sayres Sep 2009: Jon Winawer Translated to Python by Michael Waskom, 10/2012 This tutorial covers two related topics. First, pulse sequence methods for measuring T1 or T2 are illustrated. These are introduced by explaining two types of pulse sequences (inversion recovery and spin echo) that selectively emphasize the T1 or T2 tissue properties. Then, the tutorial continues with a very simple example of how one can form images of the relaxation constants (T1 or T2) at different positions You should complete the tutorial "mrTutMR" prior to this one. First we set up the pylab environment and import a few display-relevant functions. End of explanation """ def cart2pol(x, y): theta = arctan2(y, x) r = sqrt(x ** 2 + y ** 2) return theta, r def pol2cart(theta, r): x = r * cos(theta) y = r * sin(theta) return x, y """ Explanation: Next we define two small functions to convert between coordinate systems. End of explanation """ def inversion_recovery(T1, f=None, ax=None): """Graphical illustration of the Inversion Recovery idea.""" if not all([f, ax]): f, ax = subplots(1, 1) ax.set_aspect("equal") ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) # Original net magnetization m = [0, 10] p0, r0 = cart2pol(*m) arr = Arrow(0, 0, *m) ax.add_patch(arr) ax.set_title("Initial magnetization") display(f) sleep(1.5) # Flip the magnetization with a 180 pulse ax.set_title("$180^o$ RF pulse") p, r = cart2pol(*m) p = p0 - pi m = pol2cart(p, r) arr.remove() arr = Arrow(0, 0, *m) ax.add_patch(arr) clear_output(True) display(f) sleep(.5) # Let the T1 value decay for a while at the T1 rate. ax.set_title("Recovery") for t in arange(0, 0.8, 0.15): # Time in seconds arr.remove() r = r0 - 2 * r0 *exp(-t / T1) p = p0 if r > 0 else p m = pol2cart(p, abs(r)) arr = Arrow(0, 0, *m) ax.add_patch(arr) clear_output(True) display(f) sleep(.2) # Rotate the magnetization using a 90 deg pulse to measure it ax.set_title("$90^o$ RF pulse") for i in range(5): p, r = cart2pol(*m) p = p - (pi / 2) / 5 m = pol2cart(p, r) arr.remove() arr = Arrow(0, 0, *m) ax.add_patch(arr) clear_output(True) display(f) sleep(.2) ax.set_title("Measure RF now") clear_output(True) display(f) plt.close() def spin_echo(TE=16, f=None, ax=None): """Graphical illustration of the Spin Echo dephasing and echo formation.""" if not all(f, ax): f, ax = subplots(1, 1) ax.set_aspect("equal") ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) ax.set_xlabel("X axis") ax.set_ylabel("Y axis") # Original net magnetization ma = [10, 0] p0, r0 = cart2pol(*ma) arr_a = Arrow(0, 0, *ma, color="blue") ax.add_patch(arr_a) mb = ma arr_b = arrow(0, 0, *mb, color="green") ax.set_title("$90^o$ pulse and dephasing") display(f) sleep(1.2) for i in range(TE): arr_a.remove() arr_b.remove() pa, ra = cart2pol(*ma) pa = pa - pi / 8 ma = pol2cart(pa, ra) arr_a = Arrow(0, 0, *ma, color="blue") ax.add_patch(arr_a) pb, rb = cart2pol(*mb) pb = pb - pi / 10 mb = pol2cart(pb, rb) arr_b = Arrow(0, 0, *mb, color="green") ax.add_patch(arr_b) clear_output(True) display(f) sleep(.2) # Apply a 180 deg pulse that rotates the spins around the x-axis sleep(.8) ax.set_title("Inverting ($180^o$ pulse)") clear_output(True) display(f) sleep(.5) arr_a.remove() arr_b.remove() pa, ra = cart2pol(*ma) pa = -pa ma = pol2cart(pa, ra) arr_a = Arrow(0, 0, *ma, color="blue") ax.add_patch(arr_a) pb, rb = cart2pol(*mb) pb = -pb mb = pol2cart(pb, rb) arr_b = Arrow(0, 0, *mb, color="green") ax.add_patch(arr_b) clear_output(True) display(f) # Now keep going ax.set_title("Catching up") clear_output(True) display(f) sleep(.5) for i in range(TE): arr_a.remove() arr_b.remove() pa, ra = cart2pol(*ma) pa = pa - pi / 8 ma = pol2cart(pa, ra) arr_a = Arrow(0, 0, *ma, color="blue") ax.add_patch(arr_a) pb, rb = cart2pol(*mb) pb = pb - pi / 10 mb = pol2cart(pb, rb) arr_b = Arrow(0, 0, *mb, color="green") ax.add_patch(arr_b) clear_output(True) display(f) sleep(.2) ax.set_title("The echo arrives") clear_output(True) display(f) plt.close() def phase_encode(rate, spin_dir, n_steps=15): """Visualization of the phase-encoding.""" f, axes = subplots(2, 2, figsize=(8, 8)) axes = axes.ravel() for ax in axes: ax.set_aspect("equal") ax.set_xlabel("X axis") ax.set_ylabel("Y axis") ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) a = empty(4, object) for i in range(n_steps): sleep(.2) pa = zeros(4) ra = zeros(4) for j, ax in enumerate(axes): pa[j], ra[j] = cart2pol(spin_dir[j, 0], spin_dir[j, 1]) pa[j] = pa[j] - rate[j] spin_dir[j, 0], spin_dir[j, 1] = pol2cart(pa[j], ra[j]) if i: a[j].remove() a[j] = Arrow(0, 0, *spin_dir[j, :]) ax.add_patch(a[j]) clear_output(True) display(f) plt.close() """ Explanation: Now we will define several functions that will be employed in the tutorial to illustrate concepts. The narrative tutorial begins below the function definitions. If you are curious about how to draw the plots, or to dig deeper into the code demonstrating the principles, feel free to read these. However, they are mostly for manipulating plots, so don't feel the need to concern yourself with the details. End of explanation """ inversion_recovery(T1=2.8) """ Explanation: Pulse Sequences for measuring T1 and T2 signals T1 Signals (used for anatomical images) Inversion-Recovery (IR) Inversion-Recovery pulse sequences are a method for measuring T1 relaxation (spin-lattice). As the sequence name suggests, the pulse sequence first inverts the net magnetization ($180^o$ pulse). Then, the sequence simply pauses for a time, TI, to let the longitudinal magnetization recover towards steady state across the tissue. Then, a $90^o$ pulse is delivered that places the net magnetization in the transverse plane. The transverse magnetization is measured right away, before significant dephasing, in order to estimate the T1 properties. To help you visualize the events, run this code a few times. The first plot shows the 180-TI-90 sequence for a relatively slow T1 value. End of explanation """ inversion_recovery(T1=0.6) """ Explanation: Now suppose the tissue has a faster T1 relaxation End of explanation """ spin_echo(TE=16) """ Explanation: Question 1: If we apply a 90-degree pulse at the time when exactly half the signal has recovered, what do you expect the transverse magnetization to be? (Extra credit: is this the same as applying a pulse at T1? Why or why not?) Comparing the two plots, you can see that the amplitude of the net transverse magnetization depends on the value of T1. The final $90^o$ flip let us measure the size of the longitudinal magnetization. Because the measurement takes place immediately after this flip, there is not much time for spin-spin dephasing and we measure mainly properties of T1. That is why such sequences are called 'T1-weighted'. T2 Signals (used for BOLD images) Spin Echo (Hahn) In principle, to make a T2 measurement we need only to flip the net magnetization $90^o$ and then measure the signal decay as the spins dephase. Because the T2 reduction is very fast compared to the T1 reduction, the decay we see will be nearly all due to T2. The spin-spin dephasing occurs so quickly that it is almost impossible to obtain a T2 measurement soon enough after the 90 deg flip. The Hahn Spin Echo, and its partner the Gradient Echo, make it possible to separate the time between the pulse and the measurement. The next visualizataion shows two spins within a single voxel. These spins are experiencing slightly differeent local magnetic fields. Consequently, one precesses around the origin slightly faster than the other. After a little time the signals are well out of phase. Then, a 180 deg inverting pulse is introduced. This pulse rotates the spins around the horizontal axis (x-axis). Seen within the plane, this causes the two spins to reverse positions so that the leader becomes the follower. The leader is still in a higher local field, and so after a while it catches up. At this moment the spin phasese come together to create an echo of the signal after the first 90 deg pulse. This echo happens at a point in time that is well separated from the inverting pulse. The time until the inverse pulse determines when the echo will occur End of explanation """ Mo = 1 # Net magnetization larmor_freq = [12, 18] # Larmor frequency in MHz/10 T1 = [1.5, 3] t = arange(0, 1, .005) * (3 * max(T1)) # Time samples in secs def rf_signal(tau=1, net_mag=1, t_samples=None, larmor_freq=12, ph=0): """Estimate an rf signal based on the various parameters.""" if t_samples is None: t_samples = arange(0, 1, 0.005) * (4 * tau) signal = exp_decay(tau, net_mag, t_samples) * cos(t_samples * larmor_freq + ph) return signal def exp_decay(tau, Mo, t): """Create an exponential decay that will be used for either longitudinal or transverse decay modeling.""" return Mo * exp(-t / tau) """ Explanation: MR Image Formation We now ask: How can we distinguish signals from different locations? This is the key step in learning how to form an image of the MR time constant's properties. Consider a simple situation in which we have two beakers sitting next to one another on a table. Both contain water. To start, suppose the magnetic field is uniform, and suppose that we measure T1. We are going to need these variables to develop the story End of explanation """ def rf_plot(time, signal, title): f, ax = subplots(1, 1, figsize=(6, 6)) ax.plot(time, signal) ax.set_xlabel('Time (s)') ax.set_ylabel('RF signal') ax.set_title(title) def rf_kspace_plot(time, signal, titles): f, (ax1, ax2) = subplots(1, 2, figsize=(14, 6)) ax1.plot(t, signal) ax1.set_xlabel("Time (s)") ax1.set_ylabel("RF signal") ax1.set_title(titles[0]) ax2.psd(signal) ax2.set_title(titles[1]) signal = rf_signal(T1[0], Mo, t, larmor_freq[1]) rf_kspace_plot(t, signal, ["Beaker Signal", "Slice Selection"]) """ Explanation: The function rf_signal produces the RF signal that we will measure given a particular time constant and Larmor frequency. The RF signal is periodic. We can summarize the amplitude and frequency of this signal by plotting the Fourier Transform amplitude spectrum. This plot measures the amplitude of each harmonic (temporal frequency) in the signal. We're going to be making quite a few plots with an RF signal over time and its spectral density. Let's write a general function so that we avoid typing the same thing over and over again. As a general rule of thumb for progamming, any time you find yourself using "copy" and "paste", it's time to write a function. End of explanation """ t_constant = [1, 2, 4] f, axes = subplots(1, 3, figsize=(14, 5), sharey=True) for i, ax in enumerate(axes): signal = rf_signal(t_constant[i], Mo, t, larmor_freq[0]) ax.set_ylim(-1, 1) ax.plot(t, signal) """ Explanation: Next, consider the signal as the relaxation constant (t_constant) increases. Notice that over the same period of time, the rf_signal has a larger amplitude (there is less decay). End of explanation """ t_constant = [1, 2, 4] f, axes = subplots(1, 3, figsize=(14, 5), sharey=True) for i, ax in enumerate(axes): signal = rf_signal(t_constant[i], Mo, t, larmor_freq[1]) ax.psd(signal) """ Explanation: Question 2: If you were to plot the Fourier Transform for each of the three subplots, how do you expect they would differ? End of explanation """ larmor_freqs = [6, 124] f, axes = subplots(1, 2, figsize=figsize(13, 7), sharey=True) for i, freq in enumerate(larmor_freqs): signal = rf_signal(T1[0], Mo, t, freq); axes[i].plot(t, signal) axes[i].set_title("Frequency: %d Hz" % freq) """ Explanation: Changing magnetic field strength Now, suppose that we change the magnetic field strength. Remember that the Larmor frequency is proportional to the magnetic field. Consequently, the frequency of the RF signal will increase. We can compare the signals at two different frequencies as follows End of explanation """ f, axes = subplots(1, 2, figsize=figsize(13, 7), sharey=True) for i, freq in enumerate(larmor_freqs): ax = axes[i] signal = rf_signal(T1[0], Mo, t, freq) ax.psd(signal) ax.set_title('Fourier Spectrum for %d Hz Signal' % freq) """ Explanation: It is easiest to see the change in frequency if we compute the Fourier transform of the two signals. End of explanation """ signal = rf_signal(T1[0], Mo, t, larmor_freqs[0]) + rf_signal(T1[0], Mo, t, larmor_freqs[1]) rf_plot(t, signal, "Two Beakers in Gradient") """ Explanation: This figure is important. It shows that the frequency of the response from each beaker depends on the local magnetic field. We have already seen that the amplitude at the response frequency depends on the time constant. We can take advantage of these two observations by introducing a gradient into the magnetic field. By inserting a gradient, the two beakers experience slightly different magnetic fields and thus the signals have two different Larmor frequencies. The combined RF signal from the two beakers will be the sum of the signals from the two beakers. End of explanation """ rf_kspace_plot(t, signal, ["Two beakers in gradient", "Fourier Space"]) """ Explanation: We can see the amplitude of the signals from each of the beakers by plotting the Fourier Transform spectrum End of explanation """ signal = rf_signal(T1[0], Mo, t, larmor_freqs[0]) + rf_signal(T1[1], Mo, t, larmor_freqs[1]) rf_plot(t, signal, "Two beakers in gradient") """ Explanation: Finally, if the two beakers represent substances with different time constants, we will be able to measure this by estimating the amplitudes of the two peaks in the spectrum. Here, we create a signal in which the two beakers are in a gradient and the substances have slightly different time constants. End of explanation """ rf_kspace_plot(t, signal, ["Two Beakers in Gradient", "Fourier Space"]) """ Explanation: You can see that the amplitude of peaks in the signal change, reflecting the different time constants. We can distinguish which amplitude is associated with which beaker because their responses are at different frequencies. End of explanation """ n_time = 256. t = arange(n_time) / n_time - 0.5 rf_pulse = zeros(int(n_time)) pulse_duration = round(n_time / 2) pulse_start = n_time / 2 - pulse_duration / 2 pulse_stop = pulse_start + pulse_duration - 1 idx = slice(int(pulse_start), int(pulse_stop)) pulse_t = t[idx] """ Explanation: Question 3: When computing the RF signal in the last example, which variable(s) represented the magnetic field gradient? From answering Question 2, and understanding this simple case, you should understand how the gradient associates different RF signal frequencies with different spatial locations. This is why determining the frequency amplitude of the signal, using the Fourier Transform, is so important: RF signal frequency is associated with spatial position. The amplitude at that frequency can be interpreted as the decay rate. This simple example provides you with the basic principles of an important MR imaging term: k-space. Specifically, in this example the frequency axis of the Fourier Transform is analogous to k-space. There are important limitations to the method we have developed up this point. Mainly, this method works if we only need to make images of an array of beakers along a line. To make estimates of beakers spread across a table top (2D) or filling up a box (3D) we need to do more. These methods will be explained below. The main difference between this example and general imaging is dimensionality. In MR imaging the stimuli don't fall along one dimension, so we can't simply use a one-dimensional frequency axis to assign position. In general the position in k-space corresponds to a position in a two-dimensional plane that represents various spatial frequencies. (By the way, there are historical reasons why they call it k-space. I forget these reasons. If someone can remind me, I will give them a firm handshake and a warm smile.) We will start to extend the ideas on imaging in this first section to slightly more complex cases in the next section. Slice Selection In nearly all fMRI imaging, the data are acquired using a series of measurements from different planar sections (slices) of the tissue. The measurements are made by selectively exciting the spins, one planar section at a time. If only one plane is excited, then we can be confident that the signal we measure must arise from a voxel in that plane. In the next part of this tutorial, we will reivew how we can excite the spins in one planar section. Following that we will review how we can distinguish different positions within the excited plane. The principles used to understand slice selection are the same as the principles used to distinguish signals from beakers at two positions. The main difference is that in the previous example we used gradients to distinguish received signals. In slice selection we use gradients to selectively deliver an excitation. The idea is this. We introduce a magnetic field gradient across the sample changing the Larmor frequency across the sample. When we deliver an RF pulse at a particular frequency, then, only the spins in one portion of the gradient field will be excited. What would such a pulse look like? Let's create some examples. Let's perform some example calculations. We initialize the rf_pulse to zero, and then we initialize some parameters. End of explanation """ pulse_freq = 25 """ Explanation: We choose a pulse frequency. This frequency will excite the planar section of the tissue that is at the Larmor frequency we wish to excite. End of explanation """ rf_pulse[idx] = sin(2 * pi * pulse_freq * pulse_t) rf_plot(t, rf_pulse, "RF pulse") """ Explanation: Now, create a sinusoid RF pulse at that frequency: End of explanation """ rf_kspace_plot(t, rf_pulse, ["RF Pulse", "Slice Selection"]) """ Explanation: Here is the Fourier Transform spectrum of the RF pulse. The frequency content of the pulse determines which plane we excite. End of explanation """ pulse_freq = 50 rf_pulse[idx] = sin(2 * pi * pulse_freq * pulse_t) rf_kspace_plot(t, rf_pulse, ["RF Pulse", "Slice Selection"]) """ Explanation: We can control the position that is excited by adjusting the frequency. End of explanation """ sinc_freq = 20 # Try 10, 20 and 40. pulse_freq = 50 # Try 25, 50 and 75. rf_pulse[idx] = sin(2 * pi * pulse_freq * pulse_t) rf_pulse[idx] = rf_pulse[idx] * sinc(sinc_freq * pulse_t) rf_kspace_plot(t, rf_pulse, ["RF Pulse", "Slice Selection"]) """ Explanation: A second parameter we would like to control is the slice width. There are two ways we can adjust the slice width. One way, as described in the book, is to change the gradient. A second way, illustrated here, is to change the timing of the RF pulse. In this example, we create an RF pulse that is the product of the sinusoid and a sinc function. (Type sinc? to read about this important function). Each sinc function has its own frequency, too. End of explanation """ T1 = array([(1, 2), (3, 4)], float) / 2 larmor_freq = [15., 50.] ph = [0, pi] t = arange(0, 5, .02) Mo = 1 rate = [0., 0., 0., 0.] spin_dir = array([(10, 0), (10, 0), (10, 0), (10, 0)], float) """ Explanation: Question 4: Run the above code a few times, varying the pulse and sinc frequency values. What effect does each parameter have on slice position and slice width? Image Formation using Frequency Encoding and Phase Encoding The Hornak MRI book has a very good discussion of imaging, including frequency and phase encoding. Please read Chapters 6 and 7 for a useful discussion of the principles further described here. Also, the Huettel et al. book is very clear and useful in describing pulse sequences (Chapters 4 and 5). Earlier, we reviewed how to use a gradient field to associate different positions along a line with different RF signal frequencies. That method is often called frequency encoding. In this section, we describe how to measure along the second spatial dimension. This measurement is sometimes called the phase-encoding dimension. Taken together, the methods described in this section are sometimes called Fourier Transform imaging. Consider the problem of identifying signals from 4 beakers placed at the corners of a square. These four beakers are in the planar section and the spins were set in motion using the methods described in the previous section. First, we set up the basic parameters for the four beakers. End of explanation """ phase_encode(rate, spin_dir, 1) """ Explanation: Plot the starting positions in the transverse plane: End of explanation """ def plot_rf_2d(fs, ps, t, T1, Mo=1): f, axes = subplots(2, 2, figsize=(8, 8)) signal = zeros((2, 2, len(t))) freq_text = ["F1", "F2"] fs = reshape(fs, (2, 2)).T ps = reshape(ps, (2, 2)).T for i in range(2): for j in range(2): signal[i, j, :] = rf_signal(T1[i, j], Mo, t, fs[i, j], ps[i, j]) axes[i, j].plot(t, signal[i, j, :]) axes[i, j].set_title(freq_text[j]) return signal """ Explanation: Now define a new plotting function to save some typing. End of explanation """ freqs = [larmor_freq[0]] * 2 + [larmor_freq[1]] * 2 phases = [ph[0]] * 4 signal = plot_rf_2d(freqs, phases, t, T1, Mo) """ Explanation: Suppose we apply a gradient across the x-axis. In the presence of this gradient, the signals from the two beakers on the left will differ from the RF signals emitted by the two beakers on the right. When we measure with only the x-gradient (Gx), we obtain the sum of the two beakers on the left in one frequency band and the sum of the two beakers on the right in a second frequency band. End of explanation """ s = (signal[0] + signal[1]).sum(axis=0) rf_kspace_plot(t, s, ["Total RF", "Total RF Signal"]) """ Explanation: Here is the total signal: End of explanation """ rate = [pi / 8, pi / 8, pi / 16, pi / 16] spin_dir = array([(10, 0), (10, 0), (10, 0), (10, 0)], float) phase_encode(rate, spin_dir, 15) """ Explanation: Now, suppose that we turn off the Gx gradient and introduce a gradient in the y-dimension (Gy). This changes the Larmor frequency of the beakers at the top and bottom of the square. Suppose the frequency for the bottom beakers is a little lower. Then the spins in the bottom beakers rotate more slowly and they end up pointing in a different direction from the spins at the top. After applying Gy for a certain amount of time, the spins at the top and bottom will point in opposite directions. End of explanation """ ps = [ph[0], ph[1]] * 2 signal = plot_rf_2d(freqs, ps, t, T1, Mo) """ Explanation: Next, we switch off Gy and turn on Gx. As before we will measure the combination of the spins on the left at one frequency and the combination of the spins at the right at a different frequency. Because the spins of the top and bottom beaker oppose one another, however, the total RF signal we obtain now is the difference between the top and bottom. End of explanation """ s = (signal[0] + signal[1]).sum(axis=0) rf_kspace_plot(t, s, ["Total RF", "Total RF Signal"]) """ Explanation: Total signal: End of explanation """
brian-rose/env-415-site
notes/Introducing_CESM.ipynb
mit
from IPython.display import YouTubeVideo YouTubeVideo('As85L34fKYQ') """ Explanation: ENV / ATM 415: Climate Laboratory Introducing the Community Earth System Model About the model We are using a version of the Community Earth System Model (CESM) which is developed and maintained at the National Center for Atmospheric Research in Boulder, CO. See the CESM website here: http://www2.cesm.ucar.edu Our experiments will use CESM in the so-called "Slab Ocean Model" mode, in which the ocean is represented by a static layer of water with some heat capacity but no motion. This greatly simplifies the necessary calculations, particularly the time required for the model to reach equilibrium. The net effect heat transport by ocean currents is prescribed through a so-called "q-flux", which really just means we prescribed sources and sinks of heat at different locations. For (lots of) details, see http://www2.cesm.ucar.edu/working-groups/pwg/documentation/cesm1-paleo-toolkit/ocean/som Atmosphere Horizontal resolution about 2º lat/lon AGCM solves the fundamental equations: Conservation of momentum, mass, energy, water, equation of state Model also solves equations of radiative transfer. This takes account of composition of the atmosphere absorption properties of different gases radiative effects of clouds. At 2º we resolve the synoptic-scale dynamics storm tracks and cyclones. We do NOT resolve the mesoscale and smaller thunderstorms, individual convective events, clouds These all must be parameterized. Sea ice Resolution of 1º. Thermodynamics (conservation of energy, water and salt) determines freezing and melting Dynamics (momentum equations) determine ice motion and deformation. Complex! Sea ice is sort of a mixture of a fluid and a solid. Land surface model Same resolution as atmosphere. Determines surface fluxes of heat, water, momentum (friction) based on prescribed vegetation types. Ocean Same grid as sea ice, 1º. Sea surface temperature evolves based on: heat exchange with atmosphere prescribed “q-flux”. Experimental setup Model is given realistic atmospheric composition, realistic solar radiation, etc. We perform a control run to get a baseline simulation, and take averages of several years (because the model has internal variability – every year is a little bit different) We then change something, e.g. $2\times CO_2$! And allow the model to adjust to a new equilibrium, just as we've done with our various simple models. Once it has gotten close to its new equilibrium, we run it for several more years again to get the new climatology. Then we can look at the differences in the climatologies before and after the perturbation. The model runs on one of our local compute clusters here at U. Albany. We can simulate about 5 years per day by running the model on 32 cores. Equilibration time for the slab ocean model is roughly 20 years. Thus it takes a few days to run any particularly scenario out to equilibrium. The atmospheric GCM uses about half of the cpu time, the sea ice uses about one quarter, and the rest goes to the land model, the coupler, and various other bits and pieces. We will begin with a "control run", i.e. we will set up the model with (approximately) realistic conditions and run it out to equilibrium. We can then measure how well our simulated climate agrees with observations. What can we resolve with a 2º atmosphere? The following animation shows contours of sea level pressure in the control simulation. It is based on 6-hourly output from the numerical model. The atmosphere is simulated with a 2º finite volume dynamical core. End of explanation """ %matplotlib inline import numpy as np import matplotlib.pyplot as plt import netCDF4 as nc """ Explanation: Discussion point: How well does this represent the true general circulation of the atmosphere? Description of input First, let's take a look at some of the ingredients that go into the control run. All of the necessary data will be served up by a special data server sitting in the department, so you should be able to run this code to interact with the data on any computer that is connected to the internet. You need to be connected to the internet to run the code in this notebook You can browse the available data through a web interface here: http://ramadda.atmos.albany.edu:8080/repository/entry/show/Top/Users/Brian+Rose/CESM+runs Within this folder called CESM runs, you will find another folder called som_input which contains all the input files. The data are all stored in NetCDF files. Python has some nice interfaces for working with NetCDF data files, including accessing files remotely over the internet. To begin, we need to import the Python package netCDF4 to read the data files. We also set the notebook to inline graphics mode to display figures right here in the notebook. End of explanation """ datapath = "http://ramadda.atmos.albany.edu:8080/repository/opendap/latest/Top/Users/Brian+Rose/CESM+runs/" endstr = "/entry.das" # Notice that in Python we can easily concatenate strings together just by `adding` them fullURL = datapath + 'som_input/USGS-gtopo30_1.9x2.5_remap_c050602.nc' + endstr print fullURL # Now we actually open the file topo = nc.Dataset( fullURL ) print topo """ Explanation: You are encouraged to experiment and tinker with all the code below. Boundary conditions: continents and topography Here we are going to load the input topography file and take a look at what's inside. We use the Dataset object from the netCDF4 module as our basic container for any netCDF data. Dataset() requires at least one argument telling it what file to open. This can either be a file on your local disk or a URL. In this case we are passing it a URL to our online dataserver. We'll put the URL in a string variable called datapath to simplify things later on. End of explanation """ for v in topo.variables: print(v) """ Explanation: The Dataset object has several important attributes. Much of this should look familiar if you have worked with netCDF data before. This Python interface to netCDF stores most of the data in dictionaries. For example, the actual variables contained in this dataset are: End of explanation """ print topo.variables['PHIS'] """ Explanation: The output of our little for loop is a list of variable names contained in the file we just opened -- actually the keys to the dictionary called variables. Each variables contains some data along with a bunch of descriptive information about the data. Here's an example: End of explanation """ lat = topo.variables['lat'][:] lon = topo.variables['lon'][:] print lat.shape, lon.shape """ Explanation: Getting the actual data This shows the syntax for reading a particular variable, which in this code is the surface geopotential (from which we can get surface elevation). It will be handy to store the grid information (latitude and longitude) in some local arrays. The example below shows that by adding [:] at the end of the expression, we reference just the data itself (which is stored as a numpy array) and not the accompanying decription. In the Python world this is called slicing. You can get subsets of the data by taking a smaller slice, using array indexing. End of explanation """ height = topo.variables['PHIS'][:] / 9.8 / 1000 # in kilometers # This makes use of the `masked array`, part of the numpy module # essentially a numpy array with a mask of the same size height_masked = np.ma.MaskedArray(height, topo.variables['LANDFRAC'][:] == 0. ) fig1 = plt.figure(figsize=(10,5)) ax1 = fig1.add_subplot(1, 1, 1) cax1 = ax1.pcolormesh( lon, lat, height_masked ) ax1.set_title('Topography (km) and land-sea mask in CESM') ax1.axis([0, 360, -90, 90]) ax1.set_xlabel('Longitude'); ax1.set_ylabel('Latitude'); cbar1 = plt.colorbar(cax1); """ Explanation: Now we have made local copies of these two arrays that contain coordinate information for the actual data in the file. The .shape command used above (which works for any numpy array) gives us information about the dimensions of the arrays, in this case, 96 latitude points and 144 longitude points. If you like can also try just typing print lat or print lon and see the coordinates themselves. Plotting the topography We will now read the geopotential and make a plot of the topography of the Earth's surface as represented on the 2º grid. The code below makes a colorful plot of the topography. We also use the land-sea mask in order to plot nothing at grid points that are entirely ocean-covered. Execute this code exactly as written first, and then play around with it to see how you might customize the graph. Note that the function pcolormesh does most of the work here. It's a function that makes color 2D plots of an array. End of explanation """ ocean_mask = np.ma.MaskedArray( topo.variables['LANDFRAC'][:], topo.variables['LANDFRAC'][:] == 1. ) fig2 = plt.figure(figsize=(10,5)) ax2 = fig2.add_subplot(1, 1, 1) cax2 = ax2.pcolormesh( lon, lat, ocean_mask ) ax2.set_title('Ocean mask in CESM') ax2.axis([0, 360, -90, 90]) ax2.set_xlabel('Longitude'); ax2.set_ylabel('Latitude') cbar2 = plt.colorbar(cax2); """ Explanation: Note that at 2º resolution we can see many smaller features (e.g. Pacific islands). The model is given a fractional land cover for each grid point. Here let's plot the land-sea mask itself so we can see where there is at least "some" water: End of explanation """ som_input = nc.Dataset( datapath + 'som_input/pop_frc.1x1d.090130.nc' + endstr ) for v in som_input.variables: print v """ Explanation: Making nicer maps Notice that to make these plots we've just plotted the lat-lon array without using any map projection. There are nice tools available to make better maps. If you're keen to learn about this, check out: http://matplotlib.org/basemap/ and http://scitools.org.uk/cartopy/ Ocean boundary conditions Another important input file contains information about the slab ocean. You can see this file in the data catalog here: http://ramadda.atmos.albany.edu:8080/repository/entry/show/Top/Users/Brian+Rose/CESM+runs/som_input/pop_frc.1x1d.090130.nc Let's load it and take a look. End of explanation """ lon_som = som_input.variables['xc'][:] lat_som = som_input.variables['yc'][:] print lon_som.shape, lat_som.shape """ Explanation: The ocean / sea ice models exist on different grids than the atmosphere (1º instead of 2º resolution). Let's store the new coordinate information just like we did for the atmosphere grid. End of explanation """ np.shape(som_input.variables['qdp'][:]) """ Explanation: Now we are going to look at the annual mean heat flux out of the ocean, which is the prescribed 'q-flux' that we give to the slab ocean model. It is stored in the field qdp in the input file. The sign convention in CESM is that qdp &gt; 0 where heat is going IN to the ocean. We will change the sign to plot heat going OUT of the ocean INTO the atmosphere (a more atmosphere-centric viewpoint). First, let's just look at the size of the data array: End of explanation """ qdp_an = np.mean( som_input.variables['qdp'][:], axis=0 ) # Note that we have to tell numpy which axis to average over # By default it will average over all axes simultaneously print qdp_an.shape """ Explanation: This means that there are 12 x 180 x 360 data points. One 180 x 360 grid for each calendar month! Now we are going to take the average over the year at each point. We will use a very convenient array function np.mean(), which just computes the mean point-by-point. This leaves us with a single grid on 180 latitude points by 360 longitude points: End of explanation """ # We can always set a non-standard size for our figure window fig3 = plt.figure(figsize=(10, 6)) ax3 = fig3.add_subplot(111) cax3 = ax3.pcolormesh( lon_som, lat_som, -qdp_an, cmap=plt.cm.seismic, vmin=-700., vmax=700. ) cbar3 = plt.colorbar(cax3) ax3.set_title( 'CESM: Prescribed heat flux out of ocean (W m$^{-2}$), annual mean', fontsize=14 ) ax3.axis([0, 360, -90, 90], fontsize=12) ax3.set_xlabel('Longitude', fontsize=14) ax3.set_ylabel('Latitude', fontsize=14) ax3.contour( lon, lat, topo.variables['LANDFRAC'][:], [0.5], colors='k'); ax3.text(65, 50, 'Annual', fontsize=16 ); """ Explanation: Now make a nice plot of the annual mean q-flux. This code also overlays a contour of the land-sea mask for reference. End of explanation """ qdp_jan = som_input.variables['qdp'][0,:,:] qdp_jan.shape """ Explanation: Notice all the spatial structure here: Lots of heat is going in to the oceans at the equator, particularly in the eastern Pacific Ocean. The red hot spots show where lots of heat is coming out of the ocean. Hot spots include the mid-latitudes off the eastern coasts of Asia and North America And also the northern North Atlantic. All this structure is determined by ocean circulation, which we are not modeling here. Instead, we are prescribing these heat flux patterns as an input to the atmosphere. This pattern changes throughout the year. Recall that we just averaged over all months to make this plot. We might want to look at just one month: End of explanation """ fig4 = plt.figure(); ax4 = fig4.add_subplot(111) cax4 = ax4.pcolormesh( lon_som, lat_som, -qdp_jan, cmap=plt.cm.seismic, vmin=-700., vmax=700. ) cbar4 = plt.colorbar(cax3) ax4.set_title( 'CESM: Prescribed heat flux out of ocean (W m$^{-2}$)' ) ax4.axis([0, 360, -90, 90]) ax4.set_xlabel('Longitude') ax4.set_ylabel('Latitude') ax4.contour( lon, lat, topo.variables['LANDFRAC'][:], [0.5], colors='k'); ax4.text(65, 50, 'January', fontsize=12 ); """ Explanation: Here we got just the first month (January) by specifying [0,:,:] after the variable name. This is called slicing or indexing an array. We are saying "give me everything for month number 1". Now make the plot: End of explanation """ # The variable we want to plot qdp = som_input.variables['qdp'][:] # A function that makes a plot for a given month (which we pass as an argument) # note... imshow is an alternate way to generate an image from a data array # Faster than pcolormesh (which is why I use it here) # but not as flexible def sh(month): plt.imshow(np.flipud(-qdp[month,:,:]), cmap=plt.cm.seismic, vmin=-700., vmax=700. ) plt.colorbar() """ Explanation: Just for fun: some interactive plotting IPython provides some really neat and easy-to-use tools to set up interactive graphics in your notebook. Here we're going to create a figure with a slider that lets of step through each month of the q-flux data. End of explanation """ from ipywidgets import interact interact(sh, month=(0,11,1)); """ Explanation: When you execute the next cell, you should get a figure with a slider above it. Go ahead and play with it. End of explanation """ atm_control = nc.Dataset( datapath + 'som_1850_f19/som_1850_f19.cam.h0.clim.nc' + endstr ) """ Explanation: The "pre-industrial" control run Our control run is set up to simulate the climate of the "pre-industrial era", meaning before significant human-induced changes to the composition of the atmosphere, nominally the year 1850. Output from the control run is available on the same data server as above. Look in the folder called som_1850_f19 (Here som stands for "slab ocean model", 1850 indicated pre-industrial conditions, and f19 is a code for the horizontal grid resolution). There are climatology files for each active model component: atmosphere, sea ice land surface I created these files by averaging over the last 10 years of the simulation. Let's take a look at the atmosphere file. The file is called som_1850_f19.cam.h0.clim.nc (the file extension .nc is used to indicate NetCDF format). Output from the control run is available on the same data server as above. Look in the folder called som_control. There are climatology files for the atmosphere, sea ice, and land surface. I created these files by averaging over the last 10 years of the simulation. Let's take a look at the atmosphere file. You can look up the necessary URL by following the procedure outlined above. The file is called som_control.cam.h0.clim.nc (the file extension .nc is used to indicate NetCDF format). Or just copy the following: End of explanation """ for v in atm_control.variables: print v """ Explanation: Now we would like to see what's in this file, same as before: End of explanation """ print atm_control.variables['SOLIN'] """ Explanation: Lots of different stuff! These are all the different quantities that are calculated as part of the model simulation. Every quantity represents a long-term average for a particular month. Want to get more information about a particular variable? End of explanation """ np.shape( atm_control.variables['T'] ) """ Explanation: Apparently this is the incoming solar radiation or insolation, with shape (12,96,144) meaning it's got 12 months, 96 latitude points and 144 longitude points. Your task, for now.... Is just to play with the data in this file. Try to figure out what some of the different fields are. Get familiar with the data and with making plots. Some fields you might want to look at: surface temperature, 'TS' Outgoing longwave radiation, 'FLNT' Net absorbed shortwave, 'FSNT' These are all 12 x 96 x 144 -- i.e. a two-dimensional grid for every calendar month. Many other fields are three-dimensional. For example, here is the shape of the array that hold the air temperature at every point and every month: End of explanation """ plt.plot( atm_control.variables['T'][1,:,70,115], atm_control.variables['lev'] ) plt.gca().invert_yaxis() plt.ylabel('Pressure (hPa)') plt.xlabel('Temperature (K)') """ Explanation: And here is some code to plot the average sounding (temperature as function of pressure) at a particular point in the month of January. End of explanation """ lat[70], lon[115] """ Explanation: What was the location we just used for that plot? Let's check by indexing the latitude and longitude arrays we previously stored: End of explanation """
choyichen/omics
examples/biomaRt.ipynb
mit
import pandas as pd %load_ext rpy2.ipython %%R library(biomaRt) %load_ext version_information %version_information pandas, rpy2 """ Explanation: Access Ensembl BioMart using biomart module We use rpy2 and R magics in IPython Notebook to utilize the powerful biomaRt package in R. Usage: Run Setup Select a mart & dataset Demo All genes on Y chromosome Annotate a gene list Ref: Blog post: Some basics of biomaRt Table of Assemblies: http://www.ensembl.org/info/website/archives/assembly.html Setup End of explanation """ %%R marts = listMarts() head(marts) """ Explanation: Tutorial What marts are available? Current build (currently not working...): End of explanation """ %%R marts.v74 = listMarts(host="dec2013.archive.ensembl.org") head(marts.v74) """ Explanation: Sometimes you need to specify a particular genome build (e.g., GTEx v6 used GENCODE v19, which was based on GRCh37.p13 = Ensembl 74): End of explanation """ %%R datasets = listDatasets(useMart("ensembl")) head(datasets) """ Explanation: What datasets are available? End of explanation """ %%R mart.hsa = useMart("ensembl", "hsapiens_gene_ensembl") """ Explanation: Select a mart & dataset End of explanation """ %%R mart74.hsa = useMart("ENSEMBL_MART_ENSEMBL", "hsapiens_gene_ensembl", host="dec2013.archive.ensembl.org") """ Explanation: For an old archive, you can even specify the archive version when calling useMart, e.g., End of explanation """ %%R mart.hsa = mart74.hsa """ Explanation: We will use mart build v74 as our example End of explanation """ %%R attributes <- listAttributes(mart.hsa) head(attributes) %%R filters <- listFilters(mart.hsa) head(filters) """ Explanation: What attributes and filters can I use? Attributes are the identifiers that you want to retrieve. For example HGNC gene ID, chromosome name, Ensembl transcript ID. Filters are the identifiers that you supply in a query. Some but not all of the filter names may be the same as the attribute names. Values are the filter identifiers themselves. For example the values of the filter “HGNC symbol” could be 3 genes “TP53”, “SRY” and “KIAA1199”. End of explanation """ %%R head(attributes[grep("affy", attributes$name),]) """ Explanation: You can search for specific attributes by running grep() on the name. For example, if you’re looking for Affymetrix microarray probeset IDs: End of explanation """ %%R -o df df = getBM(attributes=c("ensembl_gene_id", "hgnc_symbol", "chromosome_name"), filters="chromosome_name", values="Y", mart=mart.hsa) head(df) """ Explanation: Demo All genes on Y chromosome Query in R: End of explanation """ df.head() """ Explanation: Accessible in Python: End of explanation """ genes = ["ENSG00000135245", "ENSG00000240758", "ENSG00000225490"] %%R -i genes -o df df = getBM(attributes=c("ensembl_gene_id", "hgnc_symbol", "external_gene_id", "chromosome_name", "gene_biotype", "description"), filters="ensembl_gene_id", values=genes, mart=mart.hsa) df df """ Explanation: Annotate a gene list End of explanation """