code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # In this notebook we investigate the effect of normalization on the fitting procedure. # + # General imports import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from deepmod_l1.diff_library import theta_analytical #Plotting imports import matplotlib.pyplot as plt import seaborn as sns sns.set() # Remainder imports from os import listdir, path, getcwd # Setting cuda if torch.cuda.is_available(): torch.set_default_tensor_type('torch.cuda.FloatTensor') # Settings for reproducibility np.random.seed(42) torch.manual_seed(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # Defining output folder output_folder = getcwd() # %load_ext autoreload # %autoreload 2 # - # # Making library # + D = 0.5 a = 0.25 x = np.linspace(-5, 5, 500, dtype=np.float32) t = np.linspace(0, 5, 100, dtype=np.float32) x_grid, t_grid = np.meshgrid(x, t, indexing='ij') # Analytical time_deriv, theta = theta_analytical(x_grid, t_grid, D, a) # - # And performing lst-sq we get: xi_base = np.linalg.lstsq(theta, time_deriv, rcond=None)[0].squeeze() xi_base # # No normalization X_train = torch.tensor(theta, dtype=torch.float32) y_train = torch.tensor(time_deriv, dtype=torch.float32) model = nn.Sequential(*[nn.Linear(X_train.shape[1], 1, bias=False)]) optimizer = torch.optim.Adam(model.parameters()) iterations = 10000 for it in np.arange(iterations): prediction = model(X_train) loss = torch.mean((prediction - y_train)**2) optimizer.zero_grad() loss.backward() optimizer.step() if it % 1000 == 0: print(loss.item()) xi = model[0].weight.detach().numpy().squeeze() xi np.mean((xi_base - xi)**2) # Which looks okay; now on to standardizing: # # Standardization # + a = np.mean(theta, axis=0) b = np.std(theta, axis=0) a[0] = 0.0 # for the ones. b[0] = 1.0 theta_standard = (theta - a)/b # - X_train = torch.tensor(theta_standard, dtype=torch.float32) y_train = torch.tensor(time_deriv, dtype=torch.float32) model = nn.Sequential(*[nn.Linear(X_train.shape[1], 1, bias=False)]) optimizer = torch.optim.Adam(model.parameters()) iterations = 10000 for it in np.arange(iterations): prediction = model(X_train) loss = torch.mean((prediction - y_train)**2) optimizer.zero_grad() loss.backward() optimizer.step() if it % 1000 == 0: print(loss.item()) # Loss is definitely lower, let's see about the weights: weights = model[0].weight.detach().numpy().squeeze() weights # Let's transform them back: weights[0] = weights[0] - np.sum(weights[1:] * a[1:]) weights[1:] = weights[1:] / b[1:] xi_standard = weights xi_standard np.mean((xi_base-xi_standard)**2) # So basically same level as the other one; although the MSE is smaller :-) # # Norm # Now let's do the norm over theta b = np.linalg.norm(theta, axis=0) b[0] = 1.0 theta_norm = theta / b X_train = torch.tensor(theta_norm, dtype=torch.float32) y_train = torch.tensor(time_deriv, dtype=torch.float32) model = nn.Sequential(*[nn.Linear(X_train.shape[1], 1, bias=False)]) optimizer = torch.optim.Adam(model.parameters(), lr=0.1) iterations = 10000 for it in np.arange(iterations): prediction = model(X_train) loss = torch.mean((prediction - y_train)**2) optimizer.zero_grad() loss.backward() optimizer.step() if it % 1000 == 0: print(loss.item()) weights = model[0].weight.detach().numpy().squeeze() weights xi_norm = weights / b xi_norm b np.std(theta, axis=0) np.mean((xi_base-xi_norm)**2) # So xi_norm sucks, but that's probably because the scaling is too high? Update: training another round with high lr fixes it, but good to keep in mind it doesn't converge quickly. # # Min - max # + a = np.min(theta, axis=0) b = np.max(theta, axis=0) - np.min(theta, axis=0) a[0] = 0.0 # for the ones. b[0] = 1.0 theta_minmax = (theta - a)/b # - X_train = torch.tensor(theta_minmax, dtype=torch.float32) y_train = torch.tensor(time_deriv, dtype=torch.float32) model = nn.Sequential(*[nn.Linear(X_train.shape[1], 1, bias=False)]) optimizer = torch.optim.Adam(model.parameters(), lr=0.1) iterations = 10000 for it in np.arange(iterations): prediction = model(X_train) loss = torch.mean((prediction - y_train)**2) optimizer.zero_grad() loss.backward() optimizer.step() if it % 1000 == 0: print(loss.item()) weights = model[0].weight.detach().numpy().squeeze() weights weights[0] = weights[0] - np.sum(weights[1:] * a[1:]) weights[1:] = weights[1:] / b[1:] xi_minmax = weights xi_minmax np.mean((xi_base-xi_minmax)**2) # Which is baddd...... No idea why though... np.linalg.lstsq(theta_minmax, time_deriv, rcond=None)[0].squeeze()[1:] / b[1:] np.linalg.lstsq(theta_minmax, time_deriv, rcond=None)[0].squeeze()[0] - np.sum(np.linalg.lstsq(theta_minmax, time_deriv, rcond=None)[0].squeeze()[1:] * a[1:]) # it's def not related to our implementation though.... Seems to be numerical errors? # # Conclusion # For fitting there doesn't seem to be much difference; we seems to get same results for standardized and nothing. In future might be important to compare coeffs. Norming doesn't seem great way because the number if too big # # **Conclusion**: Standardize theta.
notebooks/Normalization.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # Making models with GPflow # -- # # *<NAME> November 2015, January 2016* # # GPflow is a Gaussian process framework in python which build on tensorflow. One of the key ingredients in GPflow is the model class, which allows the user to carefully control parameters. This notebook shows how some of these parameter control features work, and how to build your own model with GPflow. First we'll look at # # - how to view models and parameters # - how to set parameter values # - how to constrain parameters (e.g. variance > 0) # - how to fix model parameters # - how to apply priors to parameters # - how to optimize models # # Then we'll show how to build a simple logistic regression model, demonstrating the ease of the parameter framework. For a more complicated example, have a look at the fully_nonstationary_gp notebook (todo). # # GPy users should feel right at home, but there are some small differences. # # First, let's deal with the usual notebook boilerplate and make a simple GP regression model. See the Regression notebook for specifics of the model: we just want some parameters to play with. import GPflow import numpy as np #build a very simple GPR model X = np.random.rand(20,1) Y = np.sin(12*X) + 0.66*np.cos(25*X) + np.random.randn(20,1)*0.01 m = GPflow.gpr.GPR(X, Y, kern=GPflow.kernels.Matern32(1) + GPflow.kernels.Linear(1)) # ### Viewing and setting parameters # You can display the state of the model in a terminal with `print m` (or `print(m)`), and by simply returning it in a notebook m # This model has four parameters. The kernel is made of the sum of two parts: the RBF kernel has a variance parameter and a lengthscale parameter, the linear kernel only has a variance parameter. There is also a parmaeter controlling the variance of the noise, as part of the likelihood. # # All of the model variables have been initialized at one. Individual parameters can be accessed in the same way as they are displayed in the table: to see all the parameters that are part of the likelihood, do m.likelihood # This gets more useful with more complex models! # To set the value of a parameter, just assign. m.kern.matern32.lengthscales = 0.5 m.likelihood.variance = 0.01 m # ### Constraints and fixes # # GPflow helpfully creates a 'free' vector, containing an unconstrained representation of all the variables. Above, all the variables are constrained positive (see right hand table column), the unconstrained representation is given by $\alpha = \log(\exp(\theta)-1)$. You can get at this vector with `m.get_free_state()`. print m.get_free_state() # Constraints are handled by the `Transform` classes. You might prefer the constrain $\alpha = \log(\theta)$: this is easily done by changing setting the transform attribute on a parameter: m.kern.matern32.lengthscales.transform = GPflow.transforms.Exp() print m.get_free_state() # The second free parameter, representing unconstrained lengthscale has changed (though the lengthscale itself remains the same). Another helpful feature is the ability to fix parameters. This is done by simply setting the fixed boolean to True: a 'fixed' notice appears in the representation and the corresponding variable is removed from the free state. m.kern.linear.variance.fixed = True m print m.get_free_state() # To unfix a parameter, just flip the boolean back. The transformation (+ve) reappears. m.kern.linear.variance.fixed = False m # ### Priors # # Priors are set just like transforms and fixes, using members of the `GPflow.priors.` module. Let's set a Gamma prior on the RBF-variance. m.kern.matern32.variance.prior = GPflow.priors.Gamma(2,3) m # ### Optimization # # Optimization is done by calling `m.optimize()` which has optional arguments that are passed through to `scipy.optimize.minimize` (we minimize the negative log-likelihood). Variables that have priors are MAP-estimated, others are ML, i.e. we add the log prior to the log likelihood. m.optimize() m # # Building new models # # To build new models, you'll need to inherrit from `GPflow.model.Model`. Parameters are instantiated with `GPflow.param.Param`. You may also be interested in `GPflow.param.Parameterized` which acts as a 'container' of `Param`s (e.g. kernels are Parameterized). # # In this very simple demo, we'll implement linear multiclass classification. There will be two parameters: a weight matrix and a 'bias' (offset). The key thing to implement is the `build_likelihood` method, which should return a tensorflow scalar representing the (log) likelihood. Param objects can be used inside `build_likelihood`: they will appear as appropriate (unconstrained) tensors. import tensorflow as tf class LinearMulticlass(GPflow.model.Model): def __init__(self, X, Y): GPflow.model.Model.__init__(self) # always call the parent constructor self.X = X.copy() # X is a numpy array of inputs self.Y = Y.copy() # Y is a 1-of-k representation of the labels self.num_data, self.input_dim = X.shape _, self.num_classes = Y.shape #make some parameters self.W = GPflow.param.Param(np.random.randn(self.input_dim, self.num_classes)) self.b = GPflow.param.Param(np.random.randn(self.num_classes)) # ^^ You must make the parameters attributes of the class for # them to be picked up by the model. i.e. this won't work: # # W = GPflow.param.Param(... <-- must be self.W def build_likelihood(self): # takes no arguments p = tf.nn.softmax(tf.matmul(self.X, self.W) + self.b) # Param variables are used as tensorflow arrays. return tf.reduce_sum(tf.log(p) * self.Y) # be sure to return a scalar # ...and that's it. let's build a really simple demo to show that it works. # + X = np.vstack([np.random.randn(10,2) + [2,2], np.random.randn(10,2) + [-2,2], np.random.randn(10,2) + [2,-2]]) Y = np.repeat(np.eye(3), 10, 0) from matplotlib import pyplot as plt # %matplotlib inline import matplotlib matplotlib.rcParams['figure.figsize'] = (12,6) matplotlib.style.use('ggplot') plt.scatter(X[:,0], X[:,1], 100, np.argmax(Y, 1), lw=2, cmap=plt.cm.viridis) # - m = LinearMulticlass(X, Y) m m.optimize() m xx, yy = np.mgrid[-4:4:200j, -4:4:200j] X_test = np.vstack([xx.flatten(), yy.flatten()]).T f_test = np.dot(X_test, m.W._array) + m.b._array p_test = np.exp(f_test) p_test /= p_test.sum(1)[:,None] for i in range(3): plt.contour(xx, yy, p_test[:,i].reshape(200,200), [0.5], colors='k', linewidths=1) plt.scatter(X[:,0], X[:,1], 100, np.argmax(Y, 1), lw=2, cmap=plt.cm.viridis) # That concludes the new model example and this notebook. You might want to convince yourself that the `LinearMulticlass` model and its parameters have all the functionality demonstrated above. You could also add some priors and run Hamiltonian Monte Carlo using `m.sample`. See the sparse_MCMC notebook for details of running the sampler.
notebooks/models.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python (python37) # language: python # name: python37 # --- # + import numpy as np import pandas as pd from matplotlib import pyplot as plt from GIR_model_simple import * # - # # Defining the parameter set # # First thing to do is define the default parameter set for a run with FaIRv2.0. # # For this we need carbon cycle parameters (such as a, $\tau$, r, PI_conc, emis2conc), and parameters controlling the forcing and thermal properties of the model (f, d and q). # # FaIRv2.0 is designed to run an emissions timeseries, or concentration timeseries, and produce the globally averaged climate response. In order to do this it uses a 4 pool impulse response carbon cycle, and a two box thermal response model. FaIRv2.0 is designed to run more than just CO2 emissions, with the code built to run in parallel across any number of input gases, with different physical response behaviours characterised by the parameter choices. As such the parameter sets are defined in a specific dimensionality, in order to process an arbitrary number of gases. # # To help with simple, single timeseries runs, a function has been built to check the input format of the parameter sets. To use this, type: make_param_dimensions() giving the parameter values and expected dimensions as input. Output is the parameter sets of the correct dimensions. # # An equivalent function has been made for input dimensionality: make_input_dimensions(). # + # define gas parameters a = np.array([[0.2173,0.2240,0.2824,0.2763]]) tau = np.array([[1000000,394.4,36.54,4.304]]) r = np.array([[28.627296,0.019773,4.334433,0.0]]) PI_conc = np.array([278.0]) emis2conc = np.array([0.468952]) # define forcing parameters f = np.array([[5.754389,0.001215,-0.069598]]) # define thermal parameters d = np.array([283.0,9.88,0.85]) q = np.array([0.311333,0.165417,0.242]) # define dimensionality of FaIRv2.0 run dim_scens = 1 dim_thermal_param_sets = 1 dim_gas_param_sets = 1 dim_gases = 1 num_therm_boxes = 3 n_year = 2501-1765 # check the parameter sets are of the correct dimensionality a, tau, r, PI_conc, emis2conc, f, d, q = make_param_dimensions(a, tau, r, PI_conc, emis2conc, f, d, q, dim_scens, dim_gas_param_sets, dim_thermal_param_sets, dim_gases, num_therm_boxes) # make an emissions input emissions = np.zeros((dim_gases,n_year)) # emissions rise quadrativally from 0 in 1765 to 10 GtC/yr in 2020 emissions[0,:2021-1765] = 0.00016*np.arange(0,2021-1765)**2 # emissions then fall in a straight line to zero in 2050 emissions[0,2020-1765:2051-1765] = np.arange(10,-0.01,-10/(2050-2020)) # check input is of correct shape emissions = make_input_dimensions_test(emissions, dim_scens, dim_gas_param_sets, dim_thermal_param_sets, dim_gases, n_year) # plot emissions input years = np.arange(1765,2501) plt.plot(years, emissions[0,0,0,0,:], color='black') plt.xlabel('Year') plt.ylabel('Annual emissions (GtC/yr)') plt.xlim(1765,2100) # - # # Running through FaIRv2.0 # # Next, lets run this through FaIRv2.0 to get a concentrations, RF and temperature repsonse timeseries... # # The first line is the model call. We inpout the emissions timeseries defined above, with the relevant parameters also from the code box above. # # Below this we plot the output... # + E_out, C_out, RF_out, T_out, alpha_out = GIR_model(emissions=emissions, a=a, tau=tau, r=r, PI_conc=PI_conc, emis2conc=emis2conc, f=f, d=d, q=q, dim_scens=dim_scens, dim_gas_param_sets=dim_gas_param_sets, dim_thermal_param_sets=dim_thermal_param_sets, dim_gases=dim_gases) # + fig, ax = plt.subplots(2,2,figsize=(10,10)) # set up and beautify plot ax[0,0].set_xlim(1765,2101) ax[0,1].set_xlim(1765,2101) ax[1,0].set_xlim(1765,2101) ax[1,1].set_xlim(1765,2101) ax[0,0].set_xlabel('Year') ax[0,0].set_ylabel('Annual emissions (GtC/yr)') ax[0,1].set_xlabel('Year') ax[0,1].set_ylabel('CO$_2$ concentration (ppmv)') ax[1,0].set_xlabel('Year') ax[1,0].set_ylabel('Radiative forcing (W/m$^2$)') ax[1,1].set_xlabel('Year') ax[1,1].set_ylabel('Temperature anomaly ($^{\circ}$C rel. to 1850-1900)') ax[0,0].plot(years, E_out[0,0,0,0,:], color='black') ax[0,1].plot(years, C_out[0,0,0,0,:], color='black') ax[1,0].plot(years, RF_out[0,0,0,0,:], color='black') ax[1,1].plot(years, T_out[0,0,0,:] - np.mean(T_out[0,0,0,1850-1765:1901-1765]), color='black') # - # # Plotting an alternative pathway # + # make a different emissions input emissions_again = np.copy(emissions) emissions_again[0,0,0,0,2020-1765:2051-1765] -= 0.1*np.arange(0,2051-2020) emissions_again[0,0,0,0,2051-1765:] = -3.0 # then run them both throguh FaIRv2.0: E_out, C_out, RF_out, T_out, alpha_out = GIR_model(emissions=emissions, a=a, tau=tau, r=r, PI_conc=PI_conc, emis2conc=emis2conc, f=f, d=d, q=q, dim_scens=dim_scens, dim_gas_param_sets=dim_gas_param_sets, dim_thermal_param_sets=dim_thermal_param_sets, dim_gases=dim_gases) E_out_again, C_out_again, RF_out_again, T_out_again, alpha_out_again = GIR_model(emissions=emissions_again, a=a, tau=tau, r=r, PI_conc=PI_conc, emis2conc=emis2conc, f=f, d=d, q=q, dim_scens=dim_scens, dim_gas_param_sets=dim_gas_param_sets, dim_thermal_param_sets=dim_thermal_param_sets, dim_gases=dim_gases) fig, ax = plt.subplots(2,2,figsize=(10,10)) # set up and beautify plot ax[0,0].set_xlim(1765,2101) ax[0,1].set_xlim(1765,2101) ax[1,0].set_xlim(1765,2101) ax[1,1].set_xlim(1765,2101) ax[0,0].set_xlabel('Year') ax[0,0].set_ylabel('Annual emissions (GtC/yr)') ax[0,1].set_xlabel('Year') ax[0,1].set_ylabel('CO$_2$ concentration (ppmv)') ax[1,0].set_xlabel('Year') ax[1,0].set_ylabel('Radiative forcing (W/m$^2$)') ax[1,1].set_xlabel('Year') ax[1,1].set_ylabel('Temperature anomaly ($^{\circ}$C rel. to 1850-1900)') # plot original emissions output ax[0,0].plot(years, E_out[0,0,0,0,:], color='black') ax[0,1].plot(years, C_out[0,0,0,0,:], color='black') ax[1,0].plot(years, RF_out[0,0,0,0,:], color='black') ax[1,1].plot(years, T_out[0,0,0,:] - np.mean(T_out[0,0,0,1850-1765:1901-1765]), color='black') # plot alternative emissions output ax[0,0].plot(years, E_out_again[0,0,0,0,:], color='red') ax[0,1].plot(years, C_out_again[0,0,0,0,:], color='red') ax[1,0].plot(years, RF_out_again[0,0,0,0,:], color='red') ax[1,1].plot(years, T_out_again[0,0,0,:] - np.mean(T_out_again[0,0,0,1850-1765:1901-1765]), color='red') # - # # Finally, what about adding a forcing timeseries aswell # # We can run through an emissions and forcing timeseries together using the argument 'forcing' when calling the FaIRv2.0 model... # + # make a different emissions input emissions_again = np.copy(emissions) emissions_again[0,0,0,0,2020-1765:2051-1765] -= 0.1*np.arange(0,2051-2020) emissions_again[0,0,0,0,2051-1765:] = -3.0 # design the forcing timeseries to be a quadratic stabilising in 2050 at 0.67 W/m2 forcing_in = np.zeros_like(emissions) l1 = np.arange(-255,1) l2 = np.arange(0,31) y0 = 0.6 y1 = 0.67 x0 = 255 x1 = 30 f1 = (y0/x0**2) * l1**2 + l1 * 2*y0/x0 + y0 f2 = l2**2 * (y1-y0-2*y0*x1/x0)/x1**2 + l2 * 2*y0/x0 + y0 forcing_in[0,0,0,0,:2021-1765] = f1 forcing_in[0,0,0,0,2020-1765:2051-1765] = f2 forcing_in[0,0,0,0,2050-1765:] = f2[-1] # then run them both throguh FaIRv2.0: E_out, C_out, RF_out, T_out, alpha_out = GIR_model(emissions=emissions, forcing=forcing_in, a=a, tau=tau, r=r, PI_conc=PI_conc, emis2conc=emis2conc, f=f, d=d, q=q, dim_scens=dim_scens, dim_gas_param_sets=dim_gas_param_sets, dim_thermal_param_sets=dim_thermal_param_sets, dim_gases=dim_gases) E_out_again, C_out_again, RF_out_again, T_out_again, alpha_out_again = GIR_model(emissions=emissions_again, forcing=forcing_in, a=a, tau=tau, r=r, PI_conc=PI_conc, emis2conc=emis2conc, f=f, d=d, q=q, dim_scens=dim_scens, dim_gas_param_sets=dim_gas_param_sets, dim_thermal_param_sets=dim_thermal_param_sets, dim_gases=dim_gases) fig, ax = plt.subplots(2,2,figsize=(10,10)) # set up and beautify plot ax[0,0].set_xlim(1765,2101) ax[0,1].set_xlim(1765,2101) ax[1,0].set_xlim(1765,2101) ax[1,1].set_xlim(1765,2101) ax[0,0].set_xlabel('Year') ax[0,0].set_ylabel('Annual emissions (GtC/yr)') ax[0,1].set_xlabel('Year') ax[0,1].set_ylabel('CO$_2$ concentration (ppmv)') ax[1,0].set_xlabel('Year') ax[1,0].set_ylabel('Radiative forcing (W/m$^2$)') ax[1,1].set_xlabel('Year') ax[1,1].set_ylabel('Temperature anomaly ($^{\circ}$C rel. to 1850-1900)') # plot original emissions output ax[0,0].plot(years, E_out[0,0,0,0,:], color='black') ax[0,1].plot(years, C_out[0,0,0,0,:], color='black') ax[1,0].plot(years, RF_out[0,0,0,2,:], color='black') ax[1,0].plot(years, RF_out[0,0,0,1,:], color='blue') # non_co2 RF profile ax[1,1].plot(years, T_out[0,0,0,:] - np.mean(T_out[0,0,0,1850-1765:1901-1765]), color='black') # plot alternative emissions output ax[0,0].plot(years, E_out_again[0,0,0,0,:], color='red') ax[0,1].plot(years, C_out_again[0,0,0,0,:], color='red') ax[1,0].plot(years, RF_out_again[0,0,0,2,:], color='red') ax[1,1].plot(years, T_out_again[0,0,0,:] - np.mean(T_out_again[0,0,0,1850-1765:1901-1765]), color='red') # -
GIR/GIR_model_simple/testing GIR_model_simple.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + pycharm={} from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.feature_extraction import DictVectorizer from sklearn.model_selection import GridSearchCV from sklearn.tree import export_graphviz import pandas as pd # + pycharm={} df = pd.read_csv(r"../titanic.txt") # + pycharm={} data = df[["pclass", "age", "sex"]] target = df["survived"] # + pycharm={} """ 方法                                     说明 count                      非NA值的数量 describe                  针对Series或各DataFrame列计算汇总统计 min,max                 计算最小值和最大值 argmin,argmax        计算能够获取到最小值和最大值的索引位置(整数) idxmin,idxmax         计算能够获取到最小值和最大值的索引值 quantile                   计算样本的分位数(0到 1) sum                        值的总和 mean                      值的平均数, a.mean() 默认对每一列的数据求平均值;若加上参数a.mean(1)则对每一行求平均值 media                      值的算术中位数(50%分位数) mad                         根据平均值计算平均绝对离差 var                          样本值的方差 std                        样本值的标准差 skew                     样本值的偏度(三阶矩) kurt                       样本值的峰度(四阶矩) cumsum                 样本值的累计和 cummin,cummax    样本值的累计最大值和累计最小 cumprod                样本值的累计积 diff                        计算一阶差分(对时间序列很有用) pct_change            计算百分数变化 """ # + pycharm={} data["age"].fillna(data["age"].mean(), inplace=True) # + pycharm={} data_dict = data.to_dict(orient="records") # + pycharm={} dv = DictVectorizer() # + pycharm={} dv_data = dv.fit_transform(data_dict) # + pycharm={} data_train, data_test, target_train, target_test = train_test_split(dv_data, target, random_state=22) # + pycharm={} dtree_param_dict = {"max_depth": [1, 3, 5, 7, 11, 13, 15]} # + pycharm={} dt = DecisionTreeClassifier(criterion="entropy") # + pycharm={} gs = GridSearchCV(dt, param_grid=dtree_param_dict, cv=30) # + pycharm={} gs.fit(data_train, target_train) # + pycharm={} target_predict = gs.predict(data_test) print(target_predict == target_test) print(gs.score(data_test, target_test)) # + pycharm={} print("最佳参数") print(gs.best_params_) print("最佳结果") print(gs.best_score_) print("最佳预估器") print(gs.best_estimator_) print("交叉验证结果") print(gs.cv_results_) # + pycharm={} dt2 = DecisionTreeClassifier(criterion="entropy", max_depth=3) dt2.fit(data_train, target_train) target_predict2 = dt2.predict(data_test) print(target_predict2 == target_test) print(dt2.score(data_test, target_test)) # + pycharm={"metadata": false, "name": "#%%\n"} export_graphviz(dt2, out_file=r"./titanic_tree.dot", feature_names=dv.get_feature_names()) print("graphviz finished!")
simple-sklearn-demo/test8/jn/Untitled.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import numpy as np from sklearn.cluster import KMeans from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors.nearest_centroid import NearestCentroid from pyproj import Geod from sklearn import preprocessing import matplotlib.pyplot as plt # %matplotlib inline # + # Input data kitchen = pd.read_csv("input/kitchen.csv", error_bad_lines=False, engine="python", encoding = "ISO-8859-1") customer = pd.read_csv("input/customer.csv", error_bad_lines=False, engine="python", encoding = "ISO-8859-1") customer1 = pd.read_csv("input/customer.csv", error_bad_lines=False, engine="python", encoding = "ISO-8859-1") kitchen1 = pd.read_csv("input/kitchen.csv", error_bad_lines=False, engine="python", encoding = "ISO-8859-1") # + import bokeh.plotting as bk from bokeh.plotting import figure, show, output_file bk.output_notebook() def mscatter(p, x, y, marker): p.scatter(x, y, marker=marker, size=10, line_color="black", fill_color="red", alpha=0.5) p = figure(title="Persebaran Customer dan Kitchen") p.grid.grid_line_color = None p.background_fill_color = "#eeeeee" #p.axis.visible = False mscatter(p, customer['long'], customer['lat'], "circle") mscatter(p, kitchen['long'], kitchen['lat'], "x") show(p) # + # Preprocessing for grouping kitchen.drop(['minCapacity'], axis=1, inplace=True) kitchen.drop(['maxCapacity'], axis=1, inplace=True) kitchen.drop(['tolerance'], axis=1, inplace=True) customer.drop(['customersName'], axis=1, inplace=True) customer.drop(['qtyOrdered'], axis=1, inplace=True) lef = preprocessing.LabelEncoder() #Create a new column with transformed values. kitchen['kitchenName'] = lef.fit_transform(kitchen['kitchenName']) print(kitchen) # - # # Overview # Kunci utama dari Efisiensi pengiriman adalah customer harus terassign ke kitchen yang terdekat dulu. # Kami melakukannya dengan menSort customer dari jarak yang paling jauh dari titik pusat customer (sum/total lat long). # Solusi tersebut belum optimal,tapi mendekati. # Solusi optimal = Sort dari Outermost customer. # Customer kemudian di assign ke kitchen terdekatnya, apabila sudah full maka diassign ke kitchen kedua terdekat, dst. # Sehingga bisa didapat group berupa customer yang terassign ke suatu kitchen. # # Driver kemudian di assign per group berdasarkan degree dan jarak. # Di assign tidak hanya berdasarkan jarak untuk mengoptimalkan waktu pengiriman selama 1 jam. # # Grouping customer to the best kitchen # Find center point of customer, buat nyari # long long_centroid = sum(customer['long'])/len(customer) # lat lat_centroid = sum(customer['lat'])/len(customer) # + import bokeh.plotting as bk from bokeh.plotting import figure, show, output_file bk.output_notebook() def mscatter(p, x, y, marker,color): p.scatter(x, y, marker=marker, size=10, line_color="black", fill_color=color, alpha=0.5) p = figure(title="Persebaran Customer dan Kitchen") p.grid.grid_line_color = None p.background_fill_color = "#eeeeee" #p.axis.visible = False mscatter(p, customer['long'], customer['lat'], "circle", "red") mscatter(p, long_centroid, lat_centroid, "square", "blue") show(p) # + wgs84_geod = Geod(ellps='WGS84') #Distance will be measured on this ellipsoid - more accurate than a spherical method katanya #Get distance between pairs of lat-lon points def Distance(lat1,lon1,lat2,lon2): az12,az21,dist = wgs84_geod.inv(lon1,lat1,lon2,lat2) return dist #Add/update a column to the data frame with the distances (in metres) customer1['dist0'] = Distance(customer1['lat'].tolist(),customer1['long'].tolist(),[kitchen['lat'].iloc[0]]*len(customer),[kitchen['long'].iloc[0]]*len(customer)) customer1['dist1'] = Distance(customer1['lat'].tolist(),customer1['long'].tolist(),[kitchen['lat'].iloc[1]]*len(customer),[kitchen['long'].iloc[1]]*len(customer)) customer1['dist2'] = Distance(customer1['lat'].tolist(),customer1['long'].tolist(),[kitchen['lat'].iloc[2]]*len(customer),[kitchen['long'].iloc[2]]*len(customer)) customer1['dist3'] = Distance(customer1['lat'].tolist(),customer1['long'].tolist(),[kitchen['lat'].iloc[3]]*len(customer),[kitchen['long'].iloc[3]]*len(customer)) customer1['dist4'] = Distance(customer1['lat'].tolist(),customer1['long'].tolist(),[kitchen['lat'].iloc[4]]*len(customer),[kitchen['long'].iloc[4]]*len(customer)) customer1['dist5'] = Distance(customer1['lat'].tolist(),customer1['long'].tolist(),[kitchen['lat'].iloc[5]]*len(customer),[kitchen['long'].iloc[5]]*len(customer)) customer1['dist6'] = Distance(customer1['lat'].tolist(),customer1['long'].tolist(),[kitchen['lat'].iloc[6]]*len(customer),[kitchen['long'].iloc[6]]*len(customer)) # Minimum distance #customer1['Minimum'] = customer1.loc[:, ['dist0', 'dist1', 'dist2', 'dist3', 'dist4', 'dist5', 'dist6']].min(axis=1) a = pd.DataFrame(np.sort(customer1[['dist0','dist1','dist2','dist3','dist4','dist5','dist6']].values)[:,:3], columns=['nearest','2nearest', '3nearest']) customer1 = customer1.join(a) customer1.head() # - print(kitchen1) # + # Find distance from customer point to central customer point customer1['distSort'] = Distance(customer1['lat'].tolist(),customer1['long'].tolist(),[lat_centroid]*len(customer),[lat_centroid]*len(customer)) #np.sqrt( (customer.long-long_centroid)**2 + (customer.lat-lat_centroid)**2) # Sort by longest distance customer1 = customer1.sort_values(['distSort'], ascending=False) # - customer1.reset_index(drop=True, inplace=True) customer1.head() # + # Data already sorted from outermost customer # For each row in the column,assign customer to the the nearest kitchen, # if the kitchen already full, assign customer to the second nearest kitchen and so on. # BELUM SELESAI YANG INI clusters = [] #masih manual cap0 = 0 cap1 = 0 cap2 = 0 cap3 = 0 cap4 = 0 cap5 = 0 cap6 = 0 cluster=8 #hanya init scndCluster=8 #hanya init for i in customer1.index: if customer1['nearest'].loc[i]==customer1['dist0'].loc[i]: cluster=0 elif customer1['nearest'].loc[i]==customer1['dist1'].loc[i]: cluster=1 elif customer1['nearest'].loc[i]==customer1['dist2'].loc[i]: cluster=2 elif customer1['nearest'].loc[i]==customer1['dist3'].loc[i]: cluster=3 elif customer1['nearest'].loc[i]==customer1['dist4'].loc[i]: cluster=4 elif customer1['nearest'].loc[i]==customer1['dist5'].loc[i]: cluster=5 # if customer1['nearest'].loc[i]==customer1['dist6'].loc[i]: # cluster=6 if customer1['2nearest'].loc[i]==customer1['dist0'].loc[i]: scndCluster=0 elif customer1['2nearest'].loc[i]==customer1['dist1'].loc[i]: scndCluster=1 elif customer1['2nearest'].loc[i]==customer1['dist2'].loc[i]: scndCluster=2 elif customer1['2nearest'].loc[i]==customer1['dist3'].loc[i]: scndCluster=3 elif customer1['2nearest'].loc[i]==customer1['dist4'].loc[i]: scndCluster=4 elif customer1['2nearest'].loc[i]==customer1['dist5'].loc[i]: scndCluster=5 # if customer1['2nearest'].loc[i]==customer1['dist6'].loc[i]: # scndCluster=6 if customer1['3nearest'].loc[i]==customer1['dist0'].loc[i]: trdCluster=0 elif customer1['3nearest'].loc[i]==customer1['dist1'].loc[i]: trdCluster=1 elif customer1['3nearest'].loc[i]==customer1['dist2'].loc[i]: trdCluster=2 elif customer1['3nearest'].loc[i]==customer1['dist3'].loc[i]: trdCluster=3 elif customer1['3nearest'].loc[i]==customer1['dist4'].loc[i]: trdCluster=4 elif customer1['3nearest'].loc[i]==customer1['dist5'].loc[i]: trdCluster=5 # if customer1['3nearest'].loc[i]==customer1['dist6'].loc[i]: # trdCluster=6 # Assign to nearest kitchen if not yet full if (cluster==0) and (cap0<100): cap0=cap0+customer1['qtyOrdered'].loc[i] elif (cluster==1) and (cap1<40): cap1=cap1+customer1['qtyOrdered'].loc[i] elif (cluster==2) and (cap2<60): cap2=cap2+customer1['qtyOrdered'].loc[i] elif (cluster==3) and (cap3<70): cap3=cap3+customer1['qtyOrdered'].loc[i] elif (cluster==4) and (cap4<80): cap4=cap4+customer1['qtyOrdered'].loc[i] elif (cluster==5) and (cap5<50): cap5=cap5+customer1['qtyOrdered'].loc[i] elif (cluster==6) and (cap6<50): cap6=cap6+customer1['qtyOrdered'].loc[i] # if full assign to 2nd nearest kitchen if (cluster==0) and (cap0>100): cluster=scndCluster scndCluster=10 elif (cluster==1) and (cap1>40): cluster=scndCluster scndCluster=10 elif (cluster==2) and (cap2>60): cluster=scndCluster scndCluster=10 elif (cluster==3) and (cap3>70): cluster=scndCluster scndCluster=10 elif (cluster==4) and (cap4>80): cluster=scndCluster scndCluster=10 elif (cluster==5) and (cap5>50): cluster=scndCluster scndCluster=10 elif (cluster==6) and (cap6>50): cluster=scndCluster scndCluster=10 # if 2nd nearest also full assign to 3rd nearest # # if (cluster==0) and (cap0>100) and (scndCluster==10): # cluster=trdCluster # trdCluster=10 # if (cluster==1) and (cap1>40) and (scndCluster==10): # cluster=trdCluster # trdCluster=10 # if (cluster==2) and (cap2>60): # cluster=trdCluster # trdCluster=10 # if (cluster==3) and (cap3>70): # cluster=trdCluster # trdCluster=10 # if (cluster==4) and (cap4>80): # cluster=trdCluster # trdCluster=10 # if (cluster==5) and (cap5>50): # cluster=trdCluster # trdCluster=10 # if (cluster==6) and (cap6>50): # cluster=trdCluster # trdCluster=10 # count if 2nd nearest if (cluster==0) and (scndCluster==10) and (trdCluster!=10): cap0=cap0+customer1['qtyOrdered'].loc[i] elif (cluster==1) and (scndCluster==10) and (trdCluster!=10): cap1=cap1+customer1['qtyOrdered'].loc[i] elif (cluster==2) and (scndCluster==10) and (trdCluster!=10): cap2=cap2+customer1['qtyOrdered'].loc[i] elif (cluster==3) and (scndCluster==10) and (trdCluster!=10): cap3=cap3+customer1['qtyOrdered'].loc[i] elif (cluster==4) and (scndCluster==10) and (trdCluster!=10): cap4=cap4+customer1['qtyOrdered'].loc[i] elif (cluster==5) and (scndCluster==10) and (trdCluster!=10): cap5=cap5+customer1['qtyOrdered'].loc[i] elif (cluster==6) and (scndCluster==10) and (trdCluster!=10): cap6=cap6+customer1['qtyOrdered'].loc[i] # count if 3rd nearest # # if (cluster==0) and (scndCluster==10) and (trdCluster==10): # cap0=cap0+customer1['qtyOrdered'].loc[i] # if (cluster==1) and (scndCluster==10) and (trdCluster==10): # cap1=cap1+customer1['qtyOrdered'].loc[i] # if (cluster==2) and (scndCluster==10) and (trdCluster==10): # cap2=cap2+customer1['qtyOrdered'].loc[i] # if (cluster==3) and (scndCluster==10) and (trdCluster==10): # cap3=cap3+customer1['qtyOrdered'].loc[i] # if (cluster==4) and (scndCluster==10) and (trdCluster==10): # cap4=cap4+customer1['qtyOrdered'].loc[i] # if (cluster==5) and (scndCluster==10) and (trdCluster==10): # cap5=cap5+customer1['qtyOrdered'].loc[i] # if (cluster==6) and (scndCluster==10) and (trdCluster==10): # cap6=cap6+customer1['qtyOrdered'].loc[i] clusters.append(cluster) customer1['cluster'] = clusters print(cap0+cap1+cap2+cap3+cap4+cap5) # - customer1['qtyOrdered'].sum() customer1.head() # + # Data visulization customer assigned to its kitchen def visualize(data): x = data['long'] y = data['lat'] Cluster = data['cluster'] fig = plt.figure() ax = fig.add_subplot(111) scatter = ax.scatter(x,y,c=Cluster, cmap=plt.cm.Paired, s=10, label='customer') ax.scatter(kitchen['long'],kitchen['lat'], s=10, c='r', marker="x", label='second') ax.set_xlabel('longitude') ax.set_ylabel('latitude') plt.colorbar(scatter) fig.show() # + # Visualization Example customer assigned to kitchen (without following constraint) # THIS IS ONLY EXAMPLE #y = kitchen['kitchenName'] #X = pd.DataFrame(kitchen.drop('kitchenName', axis=1)) #clf = NearestCentroid() #clf.fit(X, y) #pred = clf.predict(customer) #customer1['cluster'] = pd.Series(pred, index=customer1.index) #customer['cluster'] = pd.Series(pred, index=customer.index) # - visualize(customer1) # + # Count customer order assigned to Kitchen dapurMiji = (customer1.where(customer1['cluster'] == 0))['qtyOrdered'].sum() dapurNusantara = (customer1.where(customer1['cluster'] == 1))['qtyOrdered'].sum() familiaCatering = (customer1.where(customer1['cluster'] == 2))['qtyOrdered'].sum() pondokRawon = (customer1.where(customer1['cluster'] == 3))['qtyOrdered'].sum() roseCatering = (customer1.where(customer1['cluster'] == 4))['qtyOrdered'].sum() tigaKitchenCatering = (customer1.where(customer1['cluster'] == 5))['qtyOrdered'].sum() ummuUwais = (customer1.where(customer1['cluster'] == 6))['qtyOrdered'].sum() d = {'<NAME>': dapurMiji , '<NAME>': dapurNusantara, 'Familia Catering': familiaCatering, '<NAME>': pondokRawon,'Rose Catering': roseCatering, 'Tiga Kitchen Catering': tigaKitchenCatering, 'Ummu Uwais': ummuUwais} # - print(customer1.cluster.value_counts()) # Print sum of assigned print(d) print(kitchen1) # # Assign driver in group based on degree and distance # + # Get degree for each customer in the cluster def getDegree(data): # distance # center long lat (start of routing) center_latitude = #Tiap Kitchen center_longitude = #Tiap Kitchen degrees = [] degree = 0 # For each row in the column, for row in data['longitude']: degrees = np.rint(np.rad2deg(np.arctan2((data['latitude']-center_latitude),(data['longitude']-center_longitude)))) #center di pulogadung data['degrees'] = degrees return data # + # Assign driver dari kitchen ke customer berdasarkan degree dan jarak # Priority utama berdasarkan degree jadi gaada driver yang deket doang # Tapi belum dipikir gimana bisa optimize waktu harus satu jam max, tapi seenggaknya driver udah agak rata jaraknya # Kasus khusus apabila yg degree nya kecil jaraknya jauh banget, dia driver baru. # BELUM SELESAI YANG INI
kulina.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Weighted K-Means Clustering # # In this exercise we will simulate finding good locations for production plants of a company in order to minimize its logistical costs. In particular, we would like to place production plants near customers so as to reduce shipping costs and delivery time. # # We assume that the probability of someone being a customer is independent of its geographical location and that the overall cost of delivering products to customers is proportional to the squared Euclidean distance to the closest production plant. Under these assumptions, the K-Means algorithm is an appropriate method to find a good set of locations. Indeed, K-Means finds a spatial clustering of potential customers and the centroid of each cluster can be chosen to be the location of the plant. # # Because there are potentially millions of customers, and that it is not scalable to model each customer as a data point in the K-Means procedure, we consider instead as many points as there are geographical locations, and assign to each geographical location a weight $w_i$ corresponding to the number of inhabitants at that location. The resulting problem becomes a weighted version of K-Means where we seek to minimize the objective: # # $$ # J(c_1,\dots,c_K) = \frac{\sum_{i} w_i \min_k ||x_i-c_k||^2}{\sum_{i} w_i}, # $$ # # where $c_k$ is the $k$th centroid, and $w_i$ is the weight of each geographical coordinate $x_i$. In order to minimize this cost function, we iteratively perform the following EM computations: # # * **Expectation step:** Compute the set of points associated to each centroid: # $$ # \forall~1 \leq k \leq K: \quad \mathcal{C}(k) \leftarrow \Big\{ i ~:~ k = \mathrm{arg}\min_k \| x_i - c_k \|^2 \Big\} # $$ # # # * **Minimization step:** Recompute the centroid as a the (weighted) mean of the associated data points: # $$ # \forall~1 \leq k \leq K: \quad c_k \leftarrow \frac{\sum_{i \in \mathcal{C}(k)} w_i \cdot x_i}{\sum_{i \in \mathcal{C}(k)} w_i} # $$ # # # until the objective $J(c_1,\dots,c_K)$ has converged. # # # ## Getting started # # In this exercise we will use data from http://sedac.ciesin.columbia.edu/, that we store in the files `data.mat` as part of the zip archive. The data contains for each geographical coordinates (latitude and longitude), the number of inhabitants and the corresponding country. Several variables and methods are provided in the file `utils.py`: # # # * **`utils.population`** A 2D array with the number of inhabitants at each latitude/longitude. # # # * **`utils.plot(latitudes,longitudes)`** Plot a list of centroids given as geographical coordinates in overlay to the population density map. # # The code below plots three factories (white squares) with geographical coordinates (60,80), # (60,90),(60,100) given as input. import utils, numpy # %matplotlib inline utils.plot([60,60,60],[80,90,100]) # Also, to get a dataset of geographical coordinates associated to the image given as an array, we can use: x,y = numpy.indices(utils.population.shape) locations = numpy.array([x.flatten(),y.flatten()]).T print(x[0], y[0], locations[0]) # ## Initializing Weighted K-Means (25 P) # # Because K-means has a non-convex objective, choosing a good initial set of centroids is important. Centroids are drawn from from the following discrete probability distribution: # # $$ # P(x,y) = \frac1Z \cdot \text{population}(x,y) # $$ # # where $Z$ is a normalization constant. Furthermore, to avoid identical centroids, we add a small Gaussian noise to the location of centroids, with standard deviation $0.01$. # **Task:** # # * **Implement the initialization procedure above.** # + import numpy as np def initialize(K,population): population = population.astype('float') p = population / population.sum() centroids = np.random.choice(np.arange(p.size), [K], p=p.flatten()) centroids = np.unravel_index(centroids, p.shape) centroids = np.concatenate([centroids[0][:, np.newaxis], centroids[1][:,np.newaxis]], axis=1) centroids = centroids + np.random.normal(0, 0.01, centroids.shape) return centroids # - # The following code runs the initialization procedure for K=200 clusters and visualizes the centroids obtained with the initialization procedure using `utils.plot`. centroids_init = initialize(200, utils.population) utils.plot(centroids_init[:,0], centroids_init[:,1]) # ## Implementing Weighted K-Means (75 P) # # **Task:** # # # * **Implement the weighted K-Means algorithm. Your algorithm should run for `nbit` iterations and print the value of the objective after training. If `verbose`, it should also print the value of the objective at each iteration.** # + import scipy def wkmeans(centroids, points, weights, verbose, nbit): for i in range(nbit): distance = scipy.spatial.distance.cdist(points, centroids, "sqeuclidean") allocation = np.argmin(distance, axis=1) J = 0 for k, ck in enumerate(centroids): p = points[allocation==k] w = weights[allocation==k] centroids[k] = (p * w[:, np.newaxis]).sum(axis=0) / (w.sum(axis=0)+1e-9) J = J + (w*((p-centroids[k])**2).sum(axis=1)).sum() J = J / weights.sum() if verbose or i == nbit-1: print("Iteration = %2d: J = %6.2f"%(i+1, J)) return centroids # - # The following code runs the weighted k-means on this data, and displays the final centroids. # + weights = utils.population.flatten()*1.0 centroids = wkmeans(centroids_init, locations, weights, True, 50) utils.plot(centroids[:,0], centroids[:,1]) # - # Observe that the k-means algorithm is non-convex, and arrives in local optima of different quality depending on the initialization: for i in range(5): wkmeans(initialize(200, utils.population), locations, weights, False, 50)
Ex13 - Weighted K Mean/sheet13-programming.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline survey_df = pd.read_csv('survey_results_public.csv') # + #Prepping Data #Below splits the data first into columns of interest, then into two separate dataframe groups. #One who completed a Computer Science degree and one that didn't. #If nan answer to the group question was given, these rows were dropped. #As we will be looking to the spread and percentage comparisons the few nan values will have little effect #on conclusions. # + major_df = survey_df[['UndergradMajor', 'NEWEdImpt', 'EdLevel', 'Employment']].copy() cs_df = major_df[major_df['UndergradMajor'] == 'Computer science, computer engineering, or software engineering'].copy() non_cs_df = major_df[major_df['UndergradMajor'] != 'Computer science, computer engineering, or software engineering'].copy() cs_df = cs_df.dropna(subset = ['UndergradMajor']) non_cs_df = non_cs_df.dropna(subset = ['UndergradMajor']) #Creates the two dataframes # - pie_list = [] pie_list.append(len(cs_df)) pie_list.append(len(non_cs_df)) pie_labels = ['Computer Science Major', 'No Computer Science Major'] fig, ax = plt.subplots(figsize=(5,5)) ax.pie(pie_list, labels = pie_labels, autopct='%1.1f%%') plt.tight_layout() plt.title('Major Held by Repsondents') plt.savefig('MajorPieChart.jpg') #Comparison of group size def get_percent(pd_series): pd_series = pd_series.astype('float64') total = pd_series.sum() for x in range(len(pd_series)): pd_series[x] = (pd_series[x]/total)*100 return pd_series #function to convert the pandas series from objects into percentages cs = cs_df['NEWEdImpt'].value_counts() non_cs = non_cs_df['NEWEdImpt'].value_counts() #Gets value counts for education importance cs = get_percent(cs) non_cs = get_percent(non_cs) #converts value counts to percentages frame = { 'Computer Science Major': cs, 'No Computer Science Major': non_cs } cs_result = pd.DataFrame(frame) cs_result = cs_result.reindex(['Critically important','Very important','Fairly important','Somewhat important','Not at all important/not necessary']) #creates dataframe then orders index in desired order ax = cs_result.plot(kind = 'barh', figsize = (8,5),title = 'How Important is formal education to your career?') ax.set(xlabel="Percent Selected(%)") plt.tight_layout() plt.savefig('ImpEduRslt.jpg') #Plots horizontal bar graph to compare CS Major vs no CS Major cs_employ = cs_df['Employment'].value_counts() cs_employ = get_percent(cs_employ) #gets value counts for employment and converts to percentage non_cs_employ = non_cs_df['Employment'].value_counts() non_cs_employ = get_percent(non_cs_employ) #gets value counts for employment and converts to percentage frame_e = { 'Computer Science Major': cs_employ, 'No Computer Science Major': non_cs_employ } em_result = pd.DataFrame(frame_e) em_result = em_result.reindex(['Employed full-time', 'Employed part-time', 'Not employed, but looking for work', 'Not employed, and not looking for work', 'Student', 'Retired']) #creates dataframe then orders index in desired order plt.figure() ax1 = em_result.plot(kind = 'barh', figsize = (8,5),title = 'Employment Percentage') ax1.set(xlabel="Percent(%)") plt.tight_layout() plt.savefig('EmployRslt.jpg') #Plots horizontal bargraph to compare results
DoesEduMatter.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + # default_exp data.external # - # # External data # # > Helper functions used to download and extract common time series datasets. #export from tqdm import tqdm import zipfile import tempfile try: from urllib import urlretrieve except ImportError: from urllib.request import urlretrieve import shutil import distutils from tsai.imports import * from tsai.utils import * from tsai.data.validation import * # + #export # This code was adapted from https://github.com/ChangWeiTan/TSRegression. # It's used to load time series examples to demonstrate tsai's functionality. # Copyright for above source is below. # GNU GENERAL PUBLIC LICENSE # Version 3, 29 June 2007 # Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> # Everyone is permitted to copy and distribute verbatim copies # of this license document, but changing it is not allowed. # Preamble # The GNU General Public License is a free, copyleft license for # software and other kinds of works. # The licenses for most software and other practical works are designed # to take away your freedom to share and change the works. By contrast, # the GNU General Public License is intended to guarantee your freedom to # share and change all versions of a program--to make sure it remains free # software for all its users. We, the Free Software Foundation, use the # GNU General Public License for most of our software; it applies also to # any other work released this way by its authors. You can apply it to # your programs, too. # When we speak of free software, we are referring to freedom, not # price. Our General Public Licenses are designed to make sure that you # have the freedom to distribute copies of free software (and charge for # them if you wish), that you receive source code or can get it if you # want it, that you can change the software or use pieces of it in new # free programs, and that you know you can do these things. # To protect your rights, we need to prevent others from denying you # these rights or asking you to surrender the rights. Therefore, you have # certain responsibilities if you distribute copies of the software, or if # you modify it: responsibilities to respect the freedom of others. # For example, if you distribute copies of such a program, whether # gratis or for a fee, you must pass on to the recipients the same # freedoms that you received. You must make sure that they, too, receive # or can get the source code. And you must show them these terms so they # know their rights. # Developers that use the GNU GPL protect your rights with two steps: # (1) assert copyright on the software, and (2) offer you this License # giving you legal permission to copy, distribute and/or modify it. # For the developers' and authors' protection, the GPL clearly explains # that there is no warranty for this free software. For both users' and # authors' sake, the GPL requires that modified versions be marked as # changed, so that their problems will not be attributed erroneously to # authors of previous versions. # Some devices are designed to deny users access to install or run # modified versions of the software inside them, although the manufacturer # can do so. This is fundamentally incompatible with the aim of # protecting users' freedom to change the software. The systematic # pattern of such abuse occurs in the area of products for individuals to # use, which is precisely where it is most unacceptable. Therefore, we # have designed this version of the GPL to prohibit the practice for those # products. If such problems arise substantially in other domains, we # stand ready to extend this provision to those domains in future versions # of the GPL, as needed to protect the freedom of users. # Finally, every program is threatened constantly by software patents. # States should not allow patents to restrict development and use of # software on general-purpose computers, but in those that do, we wish to # avoid the special danger that patents applied to a free program could # make it effectively proprietary. To prevent this, the GPL assures that # patents cannot be used to render the program non-free. # The precise terms and conditions for copying, distribution and # modification follow. # TERMS AND CONDITIONS # 0. Definitions. # "This License" refers to version 3 of the GNU General Public License. # "Copyright" also means copyright-like laws that apply to other kinds of # works, such as semiconductor masks. # "The Program" refers to any copyrightable work licensed under this # License. Each licensee is addressed as "you". "Licensees" and # "recipients" may be individuals or organizations. # To "modify" a work means to copy from or adapt all or part of the work # in a fashion requiring copyright permission, other than the making of an # exact copy. The resulting work is called a "modified version" of the # earlier work or a work "based on" the earlier work. # A "covered work" means either the unmodified Program or a work based # on the Program. # To "propagate" a work means to do anything with it that, without # permission, would make you directly or secondarily liable for # infringement under applicable copyright law, except executing it on a # computer or modifying a private copy. Propagation includes copying, # distribution (with or without modification), making available to the # public, and in some countries other activities as well. # To "convey" a work means any kind of propagation that enables other # parties to make or receive copies. Mere interaction with a user through # a computer network, with no transfer of a copy, is not conveying. # An interactive user interface displays "Appropriate Legal Notices" # to the extent that it includes a convenient and prominently visible # feature that (1) displays an appropriate copyright notice, and (2) # tells the user that there is no warranty for the work (except to the # extent that warranties are provided), that licensees may convey the # work under this License, and how to view a copy of this License. If # the interface presents a list of user commands or options, such as a # menu, a prominent item in the list meets this criterion. # 1. Source Code. # The "source code" for a work means the preferred form of the work # for making modifications to it. "Object code" means any non-source # form of a work. # A "Standard Interface" means an interface that either is an official # standard defined by a recognized standards body, or, in the case of # interfaces specified for a particular programming language, one that # is widely used among developers working in that language. # The "System Libraries" of an executable work include anything, other # than the work as a whole, that (a) is included in the normal form of # packaging a Major Component, but which is not part of that Major # Component, and (b) serves only to enable use of the work with that # Major Component, or to implement a Standard Interface for which an # implementation is available to the public in source code form. A # "Major Component", in this context, means a major essential component # (kernel, window system, and so on) of the specific operating system # (if any) on which the executable work runs, or a compiler used to # produce the work, or an object code interpreter used to run it. # The "Corresponding Source" for a work in object code form means all # the source code needed to generate, install, and (for an executable # work) run the object code and to modify the work, including scripts to # control those activities. However, it does not include the work's # System Libraries, or general-purpose tools or generally available free # programs which are used unmodified in performing those activities but # which are not part of the work. For example, Corresponding Source # includes interface definition files associated with source files for # the work, and the source code for shared libraries and dynamically # linked subprograms that the work is specifically designed to require, # such as by intimate data communication or control flow between those # subprograms and other parts of the work. # The Corresponding Source need not include anything that users # can regenerate automatically from other parts of the Corresponding # Source. # The Corresponding Source for a work in source code form is that # same work. # 2. Basic Permissions. # All rights granted under this License are granted for the term of # copyright on the Program, and are irrevocable provided the stated # conditions are met. This License explicitly affirms your unlimited # permission to run the unmodified Program. The output from running a # covered work is covered by this License only if the output, given its # content, constitutes a covered work. This License acknowledges your # rights of fair use or other equivalent, as provided by copyright law. # You may make, run and propagate covered works that you do not # convey, without conditions so long as your license otherwise remains # in force. You may convey covered works to others for the sole purpose # of having them make modifications exclusively for you, or provide you # with facilities for running those works, provided that you comply with # the terms of this License in conveying all material for which you do # not control copyright. Those thus making or running the covered works # for you must do so exclusively on your behalf, under your direction # and control, on terms that prohibit them from making any copies of # your copyrighted material outside their relationship with you. # Conveying under any other circumstances is permitted solely under # the conditions stated below. Sublicensing is not allowed; section 10 # makes it unnecessary. # 3. Protecting Users' Legal Rights From Anti-Circumvention Law. # No covered work shall be deemed part of an effective technological # measure under any applicable law fulfilling obligations under article # 11 of the WIPO copyright treaty adopted on 20 December 1996, or # similar laws prohibiting or restricting circumvention of such # measures. # When you convey a covered work, you waive any legal power to forbid # circumvention of technological measures to the extent such circumvention # is effected by exercising rights under this License with respect to # the covered work, and you disclaim any intention to limit operation or # modification of the work as a means of enforcing, against the work's # users, your or third parties' legal rights to forbid circumvention of # technological measures. # 4. Conveying Verbatim Copies. # You may convey verbatim copies of the Program's source code as you # receive it, in any medium, provided that you conspicuously and # appropriately publish on each copy an appropriate copyright notice; # keep intact all notices stating that this License and any # non-permissive terms added in accord with section 7 apply to the code; # keep intact all notices of the absence of any warranty; and give all # recipients a copy of this License along with the Program. # You may charge any price or no price for each copy that you convey, # and you may offer support or warranty protection for a fee. # 5. Conveying Modified Source Versions. # You may convey a work based on the Program, or the modifications to # produce it from the Program, in the form of source code under the # terms of section 4, provided that you also meet all of these conditions: # a) The work must carry prominent notices stating that you modified # it, and giving a relevant date. # b) The work must carry prominent notices stating that it is # released under this License and any conditions added under section # 7. This requirement modifies the requirement in section 4 to # "keep intact all notices". # c) You must license the entire work, as a whole, under this # License to anyone who comes into possession of a copy. This # License will therefore apply, along with any applicable section 7 # additional terms, to the whole of the work, and all its parts, # regardless of how they are packaged. This License gives no # permission to license the work in any other way, but it does not # invalidate such permission if you have separately received it. # d) If the work has interactive user interfaces, each must display # Appropriate Legal Notices; however, if the Program has interactive # interfaces that do not display Appropriate Legal Notices, your # work need not make them do so. # A compilation of a covered work with other separate and independent # works, which are not by their nature extensions of the covered work, # and which are not combined with it such as to form a larger program, # in or on a volume of a storage or distribution medium, is called an # "aggregate" if the compilation and its resulting copyright are not # used to limit the access or legal rights of the compilation's users # beyond what the individual works permit. Inclusion of a covered work # in an aggregate does not cause this License to apply to the other # parts of the aggregate. # 6. Conveying Non-Source Forms. # You may convey a covered work in object code form under the terms # of sections 4 and 5, provided that you also convey the # machine-readable Corresponding Source under the terms of this License, # in one of these ways: # a) Convey the object code in, or embodied in, a physical product # (including a physical distribution medium), accompanied by the # Corresponding Source fixed on a durable physical medium # customarily used for software interchange. # b) Convey the object code in, or embodied in, a physical product # (including a physical distribution medium), accompanied by a # written offer, valid for at least three years and valid for as # long as you offer spare parts or customer support for that product # model, to give anyone who possesses the object code either (1) a # copy of the Corresponding Source for all the software in the # product that is covered by this License, on a durable physical # medium customarily used for software interchange, for a price no # more than your reasonable cost of physically performing this # conveying of source, or (2) access to copy the # Corresponding Source from a network server at no charge. # c) Convey individual copies of the object code with a copy of the # written offer to provide the Corresponding Source. This # alternative is allowed only occasionally and noncommercially, and # only if you received the object code with such an offer, in accord # with subsection 6b. # d) Convey the object code by offering access from a designated # place (gratis or for a charge), and offer equivalent access to the # Corresponding Source in the same way through the same place at no # further charge. You need not require recipients to copy the # Corresponding Source along with the object code. If the place to # copy the object code is a network server, the Corresponding Source # may be on a different server (operated by you or a third party) # that supports equivalent copying facilities, provided you maintain # clear directions next to the object code saying where to find the # Corresponding Source. Regardless of what server hosts the # Corresponding Source, you remain obligated to ensure that it is # available for as long as needed to satisfy these requirements. # e) Convey the object code using peer-to-peer transmission, provided # you inform other peers where the object code and Corresponding # Source of the work are being offered to the general public at no # charge under subsection 6d. # A separable portion of the object code, whose source code is excluded # from the Corresponding Source as a System Library, need not be # included in conveying the object code work. # A "User Product" is either (1) a "consumer product", which means any # tangible personal property which is normally used for personal, family, # or household purposes, or (2) anything designed or sold for incorporation # into a dwelling. In determining whether a product is a consumer product, # doubtful cases shall be resolved in favor of coverage. For a particular # product received by a particular user, "normally used" refers to a # typical or common use of that class of product, regardless of the status # of the particular user or of the way in which the particular user # actually uses, or expects or is expected to use, the product. A product # is a consumer product regardless of whether the product has substantial # commercial, industrial or non-consumer uses, unless such uses represent # the only significant mode of use of the product. # "Installation Information" for a User Product means any methods, # procedures, authorization keys, or other information required to install # and execute modified versions of a covered work in that User Product from # a modified version of its Corresponding Source. The information must # suffice to ensure that the continued functioning of the modified object # code is in no case prevented or interfered with solely because # modification has been made. # If you convey an object code work under this section in, or with, or # specifically for use in, a User Product, and the conveying occurs as # part of a transaction in which the right of possession and use of the # User Product is transferred to the recipient in perpetuity or for a # fixed term (regardless of how the transaction is characterized), the # Corresponding Source conveyed under this section must be accompanied # by the Installation Information. But this requirement does not apply # if neither you nor any third party retains the ability to install # modified object code on the User Product (for example, the work has # been installed in ROM). # The requirement to provide Installation Information does not include a # requirement to continue to provide support service, warranty, or updates # for a work that has been modified or installed by the recipient, or for # the User Product in which it has been modified or installed. Access to a # network may be denied when the modification itself materially and # adversely affects the operation of the network or violates the rules and # protocols for communication across the network. # Corresponding Source conveyed, and Installation Information provided, # in accord with this section must be in a format that is publicly # documented (and with an implementation available to the public in # source code form), and must require no special password or key for # unpacking, reading or copying. # 7. Additional Terms. # "Additional permissions" are terms that supplement the terms of this # License by making exceptions from one or more of its conditions. # Additional permissions that are applicable to the entire Program shall # be treated as though they were included in this License, to the extent # that they are valid under applicable law. If additional permissions # apply only to part of the Program, that part may be used separately # under those permissions, but the entire Program remains governed by # this License without regard to the additional permissions. # When you convey a copy of a covered work, you may at your option # remove any additional permissions from that copy, or from any part of # it. (Additional permissions may be written to require their own # removal in certain cases when you modify the work.) You may place # additional permissions on material, added by you to a covered work, # for which you have or can give appropriate copyright permission. # Notwithstanding any other provision of this License, for material you # add to a covered work, you may (if authorized by the copyright holders of # that material) supplement the terms of this License with terms: # a) Disclaiming warranty or limiting liability differently from the # terms of sections 15 and 16 of this License; or # b) Requiring preservation of specified reasonable legal notices or # author attributions in that material or in the Appropriate Legal # Notices displayed by works containing it; or # c) Prohibiting misrepresentation of the origin of that material, or # requiring that modified versions of such material be marked in # reasonable ways as different from the original version; or # d) Limiting the use for publicity purposes of names of licensors or # authors of the material; or # e) Declining to grant rights under trademark law for use of some # trade names, trademarks, or service marks; or # f) Requiring indemnification of licensors and authors of that # material by anyone who conveys the material (or modified versions of # it) with contractual assumptions of liability to the recipient, for # any liability that these contractual assumptions directly impose on # those licensors and authors. # All other non-permissive additional terms are considered "further # restrictions" within the meaning of section 10. If the Program as you # received it, or any part of it, contains a notice stating that it is # governed by this License along with a term that is a further # restriction, you may remove that term. If a license document contains # a further restriction but permits relicensing or conveying under this # License, you may add to a covered work material governed by the terms # of that license document, provided that the further restriction does # not survive such relicensing or conveying. # If you add terms to a covered work in accord with this section, you # must place, in the relevant source files, a statement of the # additional terms that apply to those files, or a notice indicating # where to find the applicable terms. # Additional terms, permissive or non-permissive, may be stated in the # form of a separately written license, or stated as exceptions; # the above requirements apply either way. # 8. Termination. # You may not propagate or modify a covered work except as expressly # provided under this License. Any attempt otherwise to propagate or # modify it is void, and will automatically terminate your rights under # this License (including any patent licenses granted under the third # paragraph of section 11). # However, if you cease all violation of this License, then your # license from a particular copyright holder is reinstated (a) # provisionally, unless and until the copyright holder explicitly and # finally terminates your license, and (b) permanently, if the copyright # holder fails to notify you of the violation by some reasonable means # prior to 60 days after the cessation. # Moreover, your license from a particular copyright holder is # reinstated permanently if the copyright holder notifies you of the # violation by some reasonable means, this is the first time you have # received notice of violation of this License (for any work) from that # copyright holder, and you cure the violation prior to 30 days after # your receipt of the notice. # Termination of your rights under this section does not terminate the # licenses of parties who have received copies or rights from you under # this License. If your rights have been terminated and not permanently # reinstated, you do not qualify to receive new licenses for the same # material under section 10. # 9. Acceptance Not Required for Having Copies. # You are not required to accept this License in order to receive or # run a copy of the Program. Ancillary propagation of a covered work # occurring solely as a consequence of using peer-to-peer transmission # to receive a copy likewise does not require acceptance. However, # nothing other than this License grants you permission to propagate or # modify any covered work. These actions infringe copyright if you do # not accept this License. Therefore, by modifying or propagating a # covered work, you indicate your acceptance of this License to do so. # 10. Automatic Licensing of Downstream Recipients. # Each time you convey a covered work, the recipient automatically # receives a license from the original licensors, to run, modify and # propagate that work, subject to this License. You are not responsible # for enforcing compliance by third parties with this License. # An "entity transaction" is a transaction transferring control of an # organization, or substantially all assets of one, or subdividing an # organization, or merging organizations. If propagation of a covered # work results from an entity transaction, each party to that # transaction who receives a copy of the work also receives whatever # licenses to the work the party's predecessor in interest had or could # give under the previous paragraph, plus a right to possession of the # Corresponding Source of the work from the predecessor in interest, if # the predecessor has it or can get it with reasonable efforts. # You may not impose any further restrictions on the exercise of the # rights granted or affirmed under this License. For example, you may # not impose a license fee, royalty, or other charge for exercise of # rights granted under this License, and you may not initiate litigation # (including a cross-claim or counterclaim in a lawsuit) alleging that # any patent claim is infringed by making, using, selling, offering for # sale, or importing the Program or any portion of it. # 11. Patents. # A "contributor" is a copyright holder who authorizes use under this # License of the Program or a work on which the Program is based. The # work thus licensed is called the contributor's "contributor version". # A contributor's "essential patent claims" are all patent claims # owned or controlled by the contributor, whether already acquired or # hereafter acquired, that would be infringed by some manner, permitted # by this License, of making, using, or selling its contributor version, # but do not include claims that would be infringed only as a # consequence of further modification of the contributor version. For # purposes of this definition, "control" includes the right to grant # patent sublicenses in a manner consistent with the requirements of # this License. # Each contributor grants you a non-exclusive, worldwide, royalty-free # patent license under the contributor's essential patent claims, to # make, use, sell, offer for sale, import and otherwise run, modify and # propagate the contents of its contributor version. # In the following three paragraphs, a "patent license" is any express # agreement or commitment, however denominated, not to enforce a patent # (such as an express permission to practice a patent or covenant not to # sue for patent infringement). To "grant" such a patent license to a # party means to make such an agreement or commitment not to enforce a # patent against the party. # If you convey a covered work, knowingly relying on a patent license, # and the Corresponding Source of the work is not available for anyone # to copy, free of charge and under the terms of this License, through a # publicly available network server or other readily accessible means, # then you must either (1) cause the Corresponding Source to be so # available, or (2) arrange to deprive yourself of the benefit of the # patent license for this particular work, or (3) arrange, in a manner # consistent with the requirements of this License, to extend the patent # license to downstream recipients. "Knowingly relying" means you have # actual knowledge that, but for the patent license, your conveying the # covered work in a country, or your recipient's use of the covered work # in a country, would infringe one or more identifiable patents in that # country that you have reason to believe are valid. # If, pursuant to or in connection with a single transaction or # arrangement, you convey, or propagate by procuring conveyance of, a # covered work, and grant a patent license to some of the parties # receiving the covered work authorizing them to use, propagate, modify # or convey a specific copy of the covered work, then the patent license # you grant is automatically extended to all recipients of the covered # work and works based on it. # A patent license is "discriminatory" if it does not include within # the scope of its coverage, prohibits the exercise of, or is # conditioned on the non-exercise of one or more of the rights that are # specifically granted under this License. You may not convey a covered # work if you are a party to an arrangement with a third party that is # in the business of distributing software, under which you make payment # to the third party based on the extent of your activity of conveying # the work, and under which the third party grants, to any of the # parties who would receive the covered work from you, a discriminatory # patent license (a) in connection with copies of the covered work # conveyed by you (or copies made from those copies), or (b) primarily # for and in connection with specific products or compilations that # contain the covered work, unless you entered into that arrangement, # or that patent license was granted, prior to 28 March 2007. # Nothing in this License shall be construed as excluding or limiting # any implied license or other defenses to infringement that may # otherwise be available to you under applicable patent law. # 12. No Surrender of Others' Freedom. # If conditions are imposed on you (whether by court order, agreement or # otherwise) that contradict the conditions of this License, they do not # excuse you from the conditions of this License. If you cannot convey a # covered work so as to satisfy simultaneously your obligations under this # License and any other pertinent obligations, then as a consequence you may # not convey it at all. For example, if you agree to terms that obligate you # to collect a royalty for further conveying from those to whom you convey # the Program, the only way you could satisfy both those terms and this # License would be to refrain entirely from conveying the Program. # 13. Use with the GNU Affero General Public License. # Notwithstanding any other provision of this License, you have # permission to link or combine any covered work with a work licensed # under version 3 of the GNU Affero General Public License into a single # combined work, and to convey the resulting work. The terms of this # License will continue to apply to the part which is the covered work, # but the special requirements of the GNU Affero General Public License, # section 13, concerning interaction through a network will apply to the # combination as such. # 14. Revised Versions of this License. # The Free Software Foundation may publish revised and/or new versions of # the GNU General Public License from time to time. Such new versions will # be similar in spirit to the present version, but may differ in detail to # address new problems or concerns. # Each version is given a distinguishing version number. If the # Program specifies that a certain numbered version of the GNU General # Public License "or any later version" applies to it, you have the # option of following the terms and conditions either of that numbered # version or of any later version published by the Free Software # Foundation. If the Program does not specify a version number of the # GNU General Public License, you may choose any version ever published # by the Free Software Foundation. # If the Program specifies that a proxy can decide which future # versions of the GNU General Public License can be used, that proxy's # public statement of acceptance of a version permanently authorizes you # to choose that version for the Program. # Later license versions may give you additional or different # permissions. However, no additional obligations are imposed on any # author or copyright holder as a result of your choosing to follow a # later version. # 15. Disclaimer of Warranty. # THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY # APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT # HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY # OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM # IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF # ALL NECESSARY SERVICING, REPAIR OR CORRECTION. # 16. Limitation of Liability. # IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING # WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS # THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY # GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE # USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF # DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD # PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), # EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF # SUCH DAMAGES. # 17. Interpretation of Sections 15 and 16. # If the disclaimer of warranty and limitation of liability provided # above cannot be given local legal effect according to their terms, # reviewing courts shall apply local law that most closely approximates # an absolute waiver of all civil liability in connection with the # Program, unless a warranty or assumption of liability accompanies a # # copy of the Program in return for a fee. # END OF TERMS AND CONDITIONS # How to Apply These Terms to Your New Programs # If you develop a new program, and you want it to be of the greatest # possible use to the public, the best way to achieve this is to make it # free software which everyone can redistribute and change under these terms. # To do so, attach the following notices to the program. It is safest # to attach them to the start of each source file to most effectively # state the exclusion of warranty; and each file should have at least # the "copyright" line and a pointer to where the full""" notice is found. # <one line to give the program's name and a brief idea of what it does.> # Copyright (C) <year> <name of author> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # Also add information on how to contact you by electronic and paper mail. # If the program does terminal interaction, make it output a short # notice like this when it starts in an interactive mode: # <program> Copyright (C) <year> <name of author> # This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. # This is free software, and you are welcome to redistribute it # under certain conditions; type `show c' for details. # The hypothetical commands `show w' and `show c' should show the appropriate # parts of the General Public License. Of course, your program's commands # might be different; for a GUI interface, you would use an "about box". # You should also get your employer (if you work as a programmer) or school, # if any, to sign a "copyright disclaimer" for the program, if necessary. # For more information on this, and how to apply and follow the GNU GPL, see # <https://www.gnu.org/licenses/>. # The GNU General Public License does not permit incorporating your program # into proprietary programs. If your program is a subroutine library, you # may consider it more useful to permit linking proprietary applications with # the library. If this is what you want to do, use the GNU Lesser General # Public License instead of this License. But first, please read # <https://www.gnu.org/licenses/why-not-lgpl.html>. class _TsFileParseException(Exception): """ Should be rcomesaised when parsing a .ts file and the format is incorrect. """ pass def _ts2dfV2(full_file_path_and_name, return_separate_X_and_y=True, replace_missing_vals_with='NaN'): """Loads data from a .ts file into a Pandas DataFrame. Parameters ---------- full_file_path_and_name: str The full pathname of the .ts file to read. return_separate_X_and_y: bool true if X and Y values should be returned as separate Data Frames (X) and a numpy array (y), false otherwise. This is only relevant for data that replace_missing_vals_with: str The value that missing values in the text file should be replaced with prior to parsing. Returns ------- DataFrame, ndarray If return_separate_X_and_y then a tuple containing a DataFrame and a numpy array containing the relevant time-series and corresponding class values. DataFrame If not return_separate_X_and_y then a single DataFrame containing all time-series and (if relevant) a column "class_vals" the associated class values. """ # Initialize flags and variables used when parsing the file metadata_started = False data_started = False has_problem_name_tag = False has_timestamps_tag = False has_univariate_tag = False has_class_labels_tag = False has_target_labels_tag = False has_data_tag = False previous_timestamp_was_float = None previous_timestamp_was_int = None previous_timestamp_was_timestamp = None num_dimensions = None is_first_case = True instance_list = [] class_val_list = [] line_num = 0 # Parse the file # print(full_file_path_and_name) with open(full_file_path_and_name, 'r', encoding='utf-8') as file: for line in tqdm(file): # print(".", end='') # Strip white space from start/end of line and change to lowercase for use below line = line.strip().lower() # Empty lines are valid at any point in a file if line: # Check if this line contains metadata # Please note that even though metadata is stored in this function it is not currently published externally if line.startswith("@problemname"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(' ') token_len = len(tokens) if token_len == 1: raise _TsFileParseException("problemname tag requires an associated value") problem_name = line[len("@problemname") + 1:] has_problem_name_tag = True metadata_started = True elif line.startswith("@timestamps"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(' ') token_len = len(tokens) if token_len != 2: raise _TsFileParseException("timestamps tag requires an associated Boolean value") elif tokens[1] == "true": timestamps = True elif tokens[1] == "false": timestamps = False else: raise _TsFileParseException("invalid timestamps value") has_timestamps_tag = True metadata_started = True elif line.startswith("@univariate"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(' ') token_len = len(tokens) if token_len != 2: raise _TsFileParseException("univariate tag requires an associated Boolean value") elif tokens[1] == "true": univariate = True elif tokens[1] == "false": univariate = False else: raise _TsFileParseException("invalid univariate value") has_univariate_tag = True metadata_started = True elif line.startswith("@classlabel"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(' ') token_len = len(tokens) if token_len == 1: raise _TsFileParseException("classlabel tag requires an associated Boolean value") if tokens[1] == "true": class_labels = True elif tokens[1] == "false": class_labels = False else: raise _TsFileParseException("invalid classLabel value") # Check if we have any associated class values if token_len == 2 and class_labels: raise _TsFileParseException("if the classlabel tag is true then class values must be supplied") has_class_labels_tag = True class_label_list = [token.strip() for token in tokens[2:]] metadata_started = True elif line.startswith("@targetlabel"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(' ') token_len = len(tokens) if token_len == 1: raise _TsFileParseException("targetlabel tag requires an associated Boolean value") if tokens[1] == "true": target_labels = True elif tokens[1] == "false": target_labels = False else: raise _TsFileParseException("invalid targetLabel value") has_target_labels_tag = True class_val_list = [] metadata_started = True # Check if this line contains the start of data elif line.startswith("@data"): if line != "@data": raise _TsFileParseException("data tag should not have an associated value") if data_started and not metadata_started: raise _TsFileParseException("metadata must come before data") else: has_data_tag = True data_started = True # If the 'data tag has been found then metadata has been parsed and data can be loaded elif data_started: # Check that a full set of metadata has been provided incomplete_regression_meta_data = not has_problem_name_tag or not has_timestamps_tag or not has_univariate_tag or not has_target_labels_tag or not has_data_tag incomplete_classification_meta_data = not has_problem_name_tag or not has_timestamps_tag or not has_univariate_tag or not has_class_labels_tag or not has_data_tag if incomplete_regression_meta_data and incomplete_classification_meta_data: raise _TsFileParseException("a full set of metadata has not been provided before the data") # Replace any missing values with the value specified line = line.replace("?", replace_missing_vals_with) # Check if we dealing with data that has timestamps if timestamps: # We're dealing with timestamps so cannot just split line on ':' as timestamps may contain one has_another_value = False has_another_dimension = False timestamps_for_dimension = [] values_for_dimension = [] this_line_num_dimensions = 0 line_len = len(line) char_num = 0 while char_num < line_len: # Move through any spaces while char_num < line_len and str.isspace(line[char_num]): char_num += 1 # See if there is any more data to read in or if we should validate that read thus far if char_num < line_len: # See if we have an empty dimension (i.e. no values) if line[char_num] == ":": if len(instance_list) < (this_line_num_dimensions + 1): instance_list.append([]) instance_list[this_line_num_dimensions].append(pd.Series()) this_line_num_dimensions += 1 has_another_value = False has_another_dimension = True timestamps_for_dimension = [] values_for_dimension = [] char_num += 1 else: # Check if we have reached a class label if line[char_num] != "(" and target_labels: class_val = line[char_num:].strip() # if class_val not in class_val_list: # raise _TsFileParseException( # "the class value '" + class_val + "' on line " + str( # line_num + 1) + " is not valid") class_val_list.append(float(class_val)) char_num = line_len has_another_value = False has_another_dimension = False timestamps_for_dimension = [] values_for_dimension = [] else: # Read in the data contained within the next tuple if line[char_num] != "(" and not target_labels: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " does not start with a '('") char_num += 1 tuple_data = "" while char_num < line_len and line[char_num] != ")": tuple_data += line[char_num] char_num += 1 if char_num >= line_len or line[char_num] != ")": raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " does not end with a ')'") # Read in any spaces immediately after the current tuple char_num += 1 while char_num < line_len and str.isspace(line[char_num]): char_num += 1 # Check if there is another value or dimension to process after this tuple if char_num >= line_len: has_another_value = False has_another_dimension = False elif line[char_num] == ",": has_another_value = True has_another_dimension = False elif line[char_num] == ":": has_another_value = False has_another_dimension = True char_num += 1 # Get the numeric value for the tuple by reading from the end of the tuple data backwards to the last comma last_comma_index = tuple_data.rfind(',') if last_comma_index == -1: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " contains a tuple that has no comma inside of it") try: value = tuple_data[last_comma_index + 1:] value = float(value) except ValueError: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " contains a tuple that does not have a valid numeric value") # Check the type of timestamp that we have timestamp = tuple_data[0: last_comma_index] try: timestamp = int(timestamp) timestamp_is_int = True timestamp_is_timestamp = False except ValueError: timestamp_is_int = False if not timestamp_is_int: try: timestamp = float(timestamp) timestamp_is_float = True timestamp_is_timestamp = False except ValueError: timestamp_is_float = False if not timestamp_is_int and not timestamp_is_float: try: timestamp = timestamp.strip() timestamp_is_timestamp = True except ValueError: timestamp_is_timestamp = False # Make sure that the timestamps in the file (not just this dimension or case) are consistent if not timestamp_is_timestamp and not timestamp_is_int and not timestamp_is_float: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " contains a tuple that has an invalid timestamp '" + timestamp + "'") if previous_timestamp_was_float is not None and previous_timestamp_was_float and not timestamp_is_float: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " contains tuples where the timestamp format is inconsistent") if previous_timestamp_was_int is not None and previous_timestamp_was_int and not timestamp_is_int: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " contains tuples where the timestamp format is inconsistent") if previous_timestamp_was_timestamp is not None and previous_timestamp_was_timestamp and not timestamp_is_timestamp: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " contains tuples where the timestamp format is inconsistent") # Store the values timestamps_for_dimension += [timestamp] values_for_dimension += [value] # If this was our first tuple then we store the type of timestamp we had if previous_timestamp_was_timestamp is None and timestamp_is_timestamp: previous_timestamp_was_timestamp = True previous_timestamp_was_int = False previous_timestamp_was_float = False if previous_timestamp_was_int is None and timestamp_is_int: previous_timestamp_was_timestamp = False previous_timestamp_was_int = True previous_timestamp_was_float = False if previous_timestamp_was_float is None and timestamp_is_float: previous_timestamp_was_timestamp = False previous_timestamp_was_int = False previous_timestamp_was_float = True # See if we should add the data for this dimension if not has_another_value: if len(instance_list) < (this_line_num_dimensions + 1): instance_list.append([]) if timestamp_is_timestamp: timestamps_for_dimension = pd.DatetimeIndex(timestamps_for_dimension) instance_list[this_line_num_dimensions].append( pd.Series(index=timestamps_for_dimension, data=values_for_dimension)) this_line_num_dimensions += 1 timestamps_for_dimension = [] values_for_dimension = [] elif has_another_value: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " ends with a ',' that is not followed by another tuple") elif has_another_dimension and target_labels: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " ends with a ':' while it should list a class value") elif has_another_dimension and not target_labels: if len(instance_list) < (this_line_num_dimensions + 1): instance_list.append([]) instance_list[this_line_num_dimensions].append(pd.Series(dtype=np.float32)) this_line_num_dimensions += 1 num_dimensions = this_line_num_dimensions # If this is the 1st line of data we have seen then note the dimensions if not has_another_value and not has_another_dimension: if num_dimensions is None: num_dimensions = this_line_num_dimensions if num_dimensions != this_line_num_dimensions: raise _TsFileParseException("line " + str( line_num + 1) + " does not have the same number of dimensions as the previous line of data") # Check that we are not expecting some more data, and if not, store that processed above if has_another_value: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " ends with a ',' that is not followed by another tuple") elif has_another_dimension and target_labels: raise _TsFileParseException( "dimension " + str(this_line_num_dimensions + 1) + " on line " + str( line_num + 1) + " ends with a ':' while it should list a class value") elif has_another_dimension and not target_labels: if len(instance_list) < (this_line_num_dimensions + 1): instance_list.append([]) instance_list[this_line_num_dimensions].append(pd.Series()) this_line_num_dimensions += 1 num_dimensions = this_line_num_dimensions # If this is the 1st line of data we have seen then note the dimensions if not has_another_value and num_dimensions != this_line_num_dimensions: raise _TsFileParseException("line " + str( line_num + 1) + " does not have the same number of dimensions as the previous line of data") # Check if we should have class values, and if so that they are contained in those listed in the metadata if target_labels and len(class_val_list) == 0: raise _TsFileParseException("the cases have no associated class values") else: dimensions = line.split(":") # If first row then note the number of dimensions (that must be the same for all cases) if is_first_case: num_dimensions = len(dimensions) if target_labels: num_dimensions -= 1 for dim in range(0, num_dimensions): instance_list.append([]) is_first_case = False # See how many dimensions that the case whose data in represented in this line has this_line_num_dimensions = len(dimensions) if target_labels: this_line_num_dimensions -= 1 # All dimensions should be included for all series, even if they are empty if this_line_num_dimensions != num_dimensions: raise _TsFileParseException("inconsistent number of dimensions. Expecting " + str( num_dimensions) + " but have read " + str(this_line_num_dimensions)) # Process the data for each dimension for dim in range(0, num_dimensions): dimension = dimensions[dim].strip() if dimension: data_series = dimension.split(",") data_series = [float(i) for i in data_series] instance_list[dim].append(pd.Series(data_series)) else: instance_list[dim].append(pd.Series()) if target_labels: class_val_list.append(float(dimensions[num_dimensions].strip())) line_num += 1 # Check that the file was not empty if line_num: # Check that the file contained both metadata and data complete_regression_meta_data = has_problem_name_tag and has_timestamps_tag and has_univariate_tag and has_target_labels_tag and has_data_tag complete_classification_meta_data = has_problem_name_tag and has_timestamps_tag and has_univariate_tag and has_class_labels_tag and has_data_tag if metadata_started and not complete_regression_meta_data and not complete_classification_meta_data: raise _TsFileParseException("metadata incomplete") elif metadata_started and not data_started: raise _TsFileParseException("file contained metadata but no data") elif metadata_started and data_started and len(instance_list) == 0: raise _TsFileParseException("file contained metadata but no data") # Create a DataFrame from the data parsed above data = pd.DataFrame(dtype=np.float32) for dim in range(0, num_dimensions): data['dim_' + str(dim)] = instance_list[dim] # Check if we should return any associated class labels separately if target_labels: if return_separate_X_and_y: return data, np.asarray(class_val_list) else: data['class_vals'] = pd.Series(class_val_list) return data else: return data else: raise _TsFileParseException("empty file") # + #export # This code was adapted from sktime. # It's used to load time series examples to demonstrate tsai's functionality. # Copyright for above source is below. # Copyright (c) 2019 - 2020 The sktime developers. # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def _check_X( X:(pd.DataFrame, np.array), # Input data ): "Validate input data" # check np.array format if isinstance(X, np.ndarray): if X.ndim == 2: X = X.reshape(X.shape[0], 1, X.shape[1]) # check pd.DataFrame if isinstance(X, pd.DataFrame): X = _from_nested_to_3d_numpy(X) return X def _from_nested_to_3d_numpy( X:pd.DataFrame, # Nested pandas DataFrame ): "Convert nested Panel to 3D numpy Panel" # n_columns = X.shape[1] nested_col_mask = [*_are_columns_nested(X)] # If all the columns are nested in structure if nested_col_mask.count(True) == len(nested_col_mask): X_3d = np.stack( X.applymap(_convert_series_cell_to_numpy) .apply(lambda row: np.stack(row), axis=1) .to_numpy() ) # If some columns are primitive (non-nested) then first convert to # multi-indexed DataFrame where the same value of these columns is # repeated for each timepoint # Then the multi-indexed DataFrame can be converted to 3d NumPy array else: X_mi = _from_nested_to_multi_index(X) X_3d = _from_multi_index_to_3d_numpy( X_mi, instance_index="instance", time_index="timepoints" ) return X_3d def _are_columns_nested( X:pd.DataFrame # DataFrame to check for nested data structures. ): "Check whether any cells have nested structure in each DataFrame column" any_nested = _nested_cell_mask(X).any().values return any_nested def _nested_cell_mask(X): return X.applymap(_cell_is_series_or_array) def _cell_is_series_or_array(cell): return isinstance(cell, (pd.Series, np.ndarray)) def _convert_series_cell_to_numpy(cell): if isinstance(cell, pd.Series): return cell.to_numpy() else: return cell def _from_nested_to_multi_index( X: pd.DataFrame, # The nested DataFrame to convert to a multi-indexed pandas DataFrame )->pd.DataFrame: "Convert nested pandas Panel to multi-index pandas Panel" time_index_name = "timepoints" # n_columns = X.shape[1] nested_col_mask = [*_are_columns_nested(X)] instance_idxs = X.index.get_level_values(-1).unique() # n_instances = instance_idxs.shape[0] instance_index_name = "instance" instances = [] for instance_idx in instance_idxs: iidx = instance_idx instance = [ pd.DataFrame(i[1], columns=[i[0]]) for i in X.loc[iidx, :].iteritems() # noqa ] instance = pd.concat(instance, axis=1) # For primitive (non-nested column) assume the same # primitive value applies to every timepoint of the instance for col_idx, is_nested in enumerate(nested_col_mask): if not is_nested: instance.iloc[:, col_idx] = instance.iloc[:, col_idx].ffill() # Correctly assign multi-index multi_index = pd.MultiIndex.from_product( [[instance_idx], instance.index], names=[instance_index_name, time_index_name], ) instance.index = multi_index instances.append(instance) X_mi = pd.concat(instances) X_mi.columns = X.columns return X_mi def _from_multi_index_to_3d_numpy( X:pd.DataFrame, # The multi-index pandas DataFrame instance_index:str=None, # Name of the multi-index level corresponding to the DataFrame's instances time_index:str=None # Name of multi-index level corresponding to DataFrame's timepoints )->np.ndarray: "Convert pandas multi-index Panel to numpy 3D Panel." if X.index.nlevels != 2: raise ValueError("Multi-index DataFrame should have 2 levels.") if (instance_index is None) or (time_index is None): msg = "Must supply parameters instance_index and time_index" raise ValueError(msg) n_instances = len(X.groupby(level=instance_index)) # Alternative approach is more verbose # n_instances = (multi_ind_dataframe # .index # .get_level_values(instance_index) # .unique()).shape[0] n_timepoints = len(X.groupby(level=time_index)) # Alternative approach is more verbose # n_instances = (multi_ind_dataframe # .index # .get_level_values(time_index) # .unique()).shape[0] n_columns = X.shape[1] X_3d = X.values.reshape(n_instances, n_timepoints, n_columns).swapaxes(1, 2) return X_3d # - #export def _ts2df( full_file_path_and_name:str, # The full pathname of the .ts file to read. replace_missing_vals_with:str="NaN", # The value that missing values in the text file should be replaced with prior to parsing. ): "Load data from a .ts file into a Pandas DataFrame" # Initialize flags and variables used when parsing the file metadata_started = False data_started = False has_problem_name_tag = False has_timestamps_tag = False has_univariate_tag = False has_class_labels_tag = False has_data_tag = False previous_timestamp_was_int = None prev_timestamp_was_timestamp = None num_dimensions = None is_first_case = True instance_list = [] class_val_list = [] line_num = 0 # Parse the file # print(full_file_path_and_name) with open(full_file_path_and_name, "r", encoding="utf-8") as file: for line in file: # Strip white space from start/end of line and change to # lowercase for use below line = line.strip().lower() # Empty lines are valid at any point in a file if line: # Check if this line contains metadata # Please note that even though metadata is stored in this # function it is not currently published externally if line.startswith("@problemname"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(" ") token_len = len(tokens) if token_len == 1: raise _TsFileParseException( "problemname tag requires an associated value" ) # problem_name = line[len("@problemname") + 1:] has_problem_name_tag = True metadata_started = True elif line.startswith("@timestamps"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(" ") token_len = len(tokens) if token_len != 2: raise _TsFileParseException( "timestamps tag requires an associated Boolean " "value" ) elif tokens[1] == "true": timestamps = True elif tokens[1] == "false": timestamps = False else: raise _TsFileParseException("invalid timestamps value") has_timestamps_tag = True metadata_started = True elif line.startswith("@univariate"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(" ") token_len = len(tokens) if token_len != 2: raise _TsFileParseException( "univariate tag requires an associated Boolean " "value" ) elif tokens[1] == "true": # univariate = True pass elif tokens[1] == "false": # univariate = False pass else: raise _TsFileParseException("invalid univariate value") has_univariate_tag = True metadata_started = True elif line.startswith("@classlabel"): # Check that the data has not started if data_started: raise _TsFileParseException("metadata must come before data") # Check that the associated value is valid tokens = line.split(" ") token_len = len(tokens) if token_len == 1: raise _TsFileParseException( "classlabel tag requires an associated Boolean " "value" ) if tokens[1] == "true": class_labels = True elif tokens[1] == "false": class_labels = False else: raise _TsFileParseException("invalid classLabel value") # Check if we have any associated class values if token_len == 2 and class_labels: raise _TsFileParseException( "if the classlabel tag is true then class values " "must be supplied" ) has_class_labels_tag = True class_label_list = [token.strip() for token in tokens[2:]] metadata_started = True # Check if this line contains the start of data elif line.startswith("@data"): if line != "@data": raise _TsFileParseException( "data tag should not have an associated value" ) if data_started and not metadata_started: raise _TsFileParseException("metadata must come before data") else: has_data_tag = True data_started = True # If the 'data tag has been found then metadata has been # parsed and data can be loaded elif data_started: # Check that a full set of metadata has been provided if ( not has_problem_name_tag or not has_timestamps_tag or not has_univariate_tag or not has_class_labels_tag or not has_data_tag ): raise _TsFileParseException( "a full set of metadata has not been provided " "before the data" ) # Replace any missing values with the value specified line = line.replace("?", replace_missing_vals_with) # Check if we dealing with data that has timestamps if timestamps: # We're dealing with timestamps so cannot just split # line on ':' as timestamps may contain one has_another_value = False has_another_dimension = False timestamp_for_dim = [] values_for_dimension = [] this_line_num_dim = 0 line_len = len(line) char_num = 0 while char_num < line_len: # Move through any spaces while char_num < line_len and str.isspace(line[char_num]): char_num += 1 # See if there is any more data to read in or if # we should validate that read thus far if char_num < line_len: # See if we have an empty dimension (i.e. no # values) if line[char_num] == ":": if len(instance_list) < (this_line_num_dim + 1): instance_list.append([]) instance_list[this_line_num_dim].append( pd.Series(dtype="object") ) this_line_num_dim += 1 has_another_value = False has_another_dimension = True timestamp_for_dim = [] values_for_dimension = [] char_num += 1 else: # Check if we have reached a class label if line[char_num] != "(" and class_labels: class_val = line[char_num:].strip() if class_val not in class_label_list: raise _TsFileParseException( "the class value '" + class_val + "' on line " + str(line_num + 1) + " is not " "valid" ) class_val_list.append(class_val) char_num = line_len has_another_value = False has_another_dimension = False timestamp_for_dim = [] values_for_dimension = [] else: # Read in the data contained within # the next tuple if line[char_num] != "(" and not class_labels: raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " does " "not " "start " "with a " "'('" ) char_num += 1 tuple_data = "" while ( char_num < line_len and line[char_num] != ")" ): tuple_data += line[char_num] char_num += 1 if ( char_num >= line_len or line[char_num] != ")" ): raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " does " "not end" " with a " "')'" ) # Read in any spaces immediately # after the current tuple char_num += 1 while char_num < line_len and str.isspace( line[char_num] ): char_num += 1 # Check if there is another value or # dimension to process after this tuple if char_num >= line_len: has_another_value = False has_another_dimension = False elif line[char_num] == ",": has_another_value = True has_another_dimension = False elif line[char_num] == ":": has_another_value = False has_another_dimension = True char_num += 1 # Get the numeric value for the # tuple by reading from the end of # the tuple data backwards to the # last comma last_comma_index = tuple_data.rfind(",") if last_comma_index == -1: raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " contains a tuple that has " "no comma inside of it" ) try: value = tuple_data[last_comma_index + 1 :] value = float(value) except ValueError: raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " contains a tuple that does " "not have a valid numeric " "value" ) # Check the type of timestamp that # we have timestamp = tuple_data[0:last_comma_index] try: timestamp = int(timestamp) timestamp_is_int = True timestamp_is_timestamp = False except ValueError: timestamp_is_int = False if not timestamp_is_int: try: timestamp = timestamp.strip() timestamp_is_timestamp = True except ValueError: timestamp_is_timestamp = False # Make sure that the timestamps in # the file (not just this dimension # or case) are consistent if ( not timestamp_is_timestamp and not timestamp_is_int ): raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " contains a tuple that " "has an invalid timestamp '" + timestamp + "'" ) if ( previous_timestamp_was_int is not None and previous_timestamp_was_int and not timestamp_is_int ): raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " contains tuples where the " "timestamp format is " "inconsistent" ) if ( prev_timestamp_was_timestamp is not None and prev_timestamp_was_timestamp and not timestamp_is_timestamp ): raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " contains tuples where the " "timestamp format is " "inconsistent" ) # Store the values timestamp_for_dim += [timestamp] values_for_dimension += [value] # If this was our first tuple then # we store the type of timestamp we # had if ( prev_timestamp_was_timestamp is None and timestamp_is_timestamp ): prev_timestamp_was_timestamp = True previous_timestamp_was_int = False if ( previous_timestamp_was_int is None and timestamp_is_int ): prev_timestamp_was_timestamp = False previous_timestamp_was_int = True # See if we should add the data for # this dimension if not has_another_value: if len(instance_list) < ( this_line_num_dim + 1 ): instance_list.append([]) if timestamp_is_timestamp: timestamp_for_dim = pd.DatetimeIndex( timestamp_for_dim ) instance_list[this_line_num_dim].append( pd.Series( index=timestamp_for_dim, data=values_for_dimension, ) ) this_line_num_dim += 1 timestamp_for_dim = [] values_for_dimension = [] elif has_another_value: raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on " "line " + str(line_num + 1) + " ends with a ',' that " "is not followed by " "another tuple" ) elif has_another_dimension and class_labels: raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on " "line " + str(line_num + 1) + " ends with a ':' while " "it should list a class " "value" ) elif has_another_dimension and not class_labels: if len(instance_list) < (this_line_num_dim + 1): instance_list.append([]) instance_list[this_line_num_dim].append( pd.Series(dtype=np.float32) ) this_line_num_dim += 1 num_dimensions = this_line_num_dim # If this is the 1st line of data we have seen # then note the dimensions if not has_another_value and not has_another_dimension: if num_dimensions is None: num_dimensions = this_line_num_dim if num_dimensions != this_line_num_dim: raise _TsFileParseException( "line " + str(line_num + 1) + " does not have the " "same number of " "dimensions as the " "previous line of " "data" ) # Check that we are not expecting some more data, # and if not, store that processed above if has_another_value: raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " ends with a ',' that is " "not followed by another " "tuple" ) elif has_another_dimension and class_labels: raise _TsFileParseException( "dimension " + str(this_line_num_dim + 1) + " on line " + str(line_num + 1) + " ends with a ':' while it " "should list a class value" ) elif has_another_dimension and not class_labels: if len(instance_list) < (this_line_num_dim + 1): instance_list.append([]) instance_list[this_line_num_dim].append( pd.Series(dtype="object") ) this_line_num_dim += 1 num_dimensions = this_line_num_dim # If this is the 1st line of data we have seen then # note the dimensions if ( not has_another_value and num_dimensions != this_line_num_dim ): raise _TsFileParseException( "line " + str(line_num + 1) + " does not have the same " "number of dimensions as the " "previous line of data" ) # Check if we should have class values, and if so # that they are contained in those listed in the # metadata if class_labels and len(class_val_list) == 0: raise _TsFileParseException( "the cases have no associated class values" ) else: dimensions = line.split(":") # If first row then note the number of dimensions ( # that must be the same for all cases) if is_first_case: num_dimensions = len(dimensions) if class_labels: num_dimensions -= 1 for _dim in range(0, num_dimensions): instance_list.append([]) is_first_case = False # See how many dimensions that the case whose data # in represented in this line has this_line_num_dim = len(dimensions) if class_labels: this_line_num_dim -= 1 # All dimensions should be included for all series, # even if they are empty if this_line_num_dim != num_dimensions: raise _TsFileParseException( "inconsistent number of dimensions. " "Expecting " + str(num_dimensions) + " but have read " + str(this_line_num_dim) ) # Process the data for each dimension for dim in range(0, num_dimensions): dimension = dimensions[dim].strip() if dimension: data_series = dimension.split(",") data_series = [float(i) for i in data_series] instance_list[dim].append(pd.Series(data_series)) else: instance_list[dim].append(pd.Series(dtype="object")) if class_labels: class_val_list.append(dimensions[num_dimensions].strip()) line_num += 1 # Check that the file was not empty if line_num: # Check that the file contained both metadata and data if metadata_started and not ( has_problem_name_tag and has_timestamps_tag and has_univariate_tag and has_class_labels_tag and has_data_tag ): raise _TsFileParseException("metadata incomplete") elif metadata_started and not data_started: raise _TsFileParseException("file contained metadata but no data") elif metadata_started and data_started and len(instance_list) == 0: raise _TsFileParseException("file contained metadata but no data") # Create a DataFrame from the data parsed above data = pd.DataFrame(dtype=np.float32) for dim in range(0, num_dimensions): data["dim_" + str(dim)] = instance_list[dim] # Check if we should return any associated class labels separately if class_labels: return data, np.asarray(class_val_list) else: return data else: raise _TsFileParseException("empty file") #export def decompress_from_url(url, target_dir=None, verbose=False): # Download try: pv("downloading data...", verbose) fname = os.path.basename(url) tmpdir = tempfile.mkdtemp() tmpfile = os.path.join(tmpdir, fname) urlretrieve(url, tmpfile) pv("...data downloaded", verbose) # Decompress try: pv("decompressing data...", verbose) if not os.path.exists(target_dir): os.makedirs(target_dir) shutil.unpack_archive(tmpfile, target_dir) shutil.rmtree(tmpdir) pv("...data decompressed", verbose) return target_dir except: shutil.rmtree(tmpdir) if verbose: sys.stderr.write("Could not decompress file, aborting.\n") except: shutil.rmtree(tmpdir) if verbose: sys.stderr.write("Could not download url. Please, check url.\n") #export def download_data(url, fname=None, c_key='archive', force_download=False, timeout=4, verbose=False): "Download `url` to `fname`." from fastai.data.external import URLs from fastdownload import download_url fname = Path(fname or URLs.path(url, c_key=c_key)) fname.parent.mkdir(parents=True, exist_ok=True) if not fname.exists() or force_download: download_url(url, dest=fname, timeout=timeout, show_progress=verbose) return fname # + # export def get_UCR_univariate_list(): return [ 'ACSF1', 'Adiac', 'AllGestureWiimoteX', 'AllGestureWiimoteY', 'AllGestureWiimoteZ', 'ArrowHead', 'Beef', 'BeetleFly', 'BirdChicken', 'BME', 'Car', 'CBF', 'Chinatown', 'ChlorineConcentration', 'CinCECGTorso', 'Coffee', 'Computers', 'CricketX', 'CricketY', 'CricketZ', 'Crop', 'DiatomSizeReduction', 'DistalPhalanxOutlineAgeGroup', 'DistalPhalanxOutlineCorrect', 'DistalPhalanxTW', 'DodgerLoopDay', 'DodgerLoopGame', 'DodgerLoopWeekend', 'Earthquakes', 'ECG200', 'ECG5000', 'ECGFiveDays', 'ElectricDevices', 'EOGHorizontalSignal', 'EOGVerticalSignal', 'EthanolLevel', 'FaceAll', 'FaceFour', 'FacesUCR', 'FiftyWords', 'Fish', 'FordA', 'FordB', 'FreezerRegularTrain', 'FreezerSmallTrain', 'Fungi', 'GestureMidAirD1', 'GestureMidAirD2', 'GestureMidAirD3', 'GesturePebbleZ1', 'GesturePebbleZ2', 'GunPoint', 'GunPointAgeSpan', 'GunPointMaleVersusFemale', 'GunPointOldVersusYoung', 'Ham', 'HandOutlines', 'Haptics', 'Herring', 'HouseTwenty', 'InlineSkate', 'InsectEPGRegularTrain', 'InsectEPGSmallTrain', 'InsectWingbeatSound', 'ItalyPowerDemand', 'LargeKitchenAppliances', 'Lightning2', 'Lightning7', 'Mallat', 'Meat', 'MedicalImages', 'MelbournePedestrian', 'MiddlePhalanxOutlineAgeGroup', 'MiddlePhalanxOutlineCorrect', 'MiddlePhalanxTW', 'MixedShapesRegularTrain', 'MixedShapesSmallTrain', 'MoteStrain', 'NonInvasiveFetalECGThorax1', 'NonInvasiveFetalECGThorax2', 'OliveOil', 'OSULeaf', 'PhalangesOutlinesCorrect', 'Phoneme', 'PickupGestureWiimoteZ', 'PigAirwayPressure', 'PigArtPressure', 'PigCVP', 'PLAID', 'Plane', 'PowerCons', 'ProximalPhalanxOutlineAgeGroup', 'ProximalPhalanxOutlineCorrect', 'ProximalPhalanxTW', 'RefrigerationDevices', 'Rock', 'ScreenType', 'SemgHandGenderCh2', 'SemgHandMovementCh2', 'SemgHandSubjectCh2', 'ShakeGestureWiimoteZ', 'ShapeletSim', 'ShapesAll', 'SmallKitchenAppliances', 'SmoothSubspace', 'SonyAIBORobotSurface1', 'SonyAIBORobotSurface2', 'StarLightCurves', 'Strawberry', 'SwedishLeaf', 'Symbols', 'SyntheticControl', 'ToeSegmentation1', 'ToeSegmentation2', 'Trace', 'TwoLeadECG', 'TwoPatterns', 'UMD', 'UWaveGestureLibraryAll', 'UWaveGestureLibraryX', 'UWaveGestureLibraryY', 'UWaveGestureLibraryZ', 'Wafer', 'Wine', 'WordSynonyms', 'Worms', 'WormsTwoClass', 'Yoga' ] test_eq(len(get_UCR_univariate_list()), 128) UTSC_datasets = get_UCR_univariate_list() UCR_univariate_list = get_UCR_univariate_list() # + #export def get_UCR_multivariate_list(): return [ 'ArticularyWordRecognition', 'AtrialFibrillation', 'BasicMotions', 'CharacterTrajectories', 'Cricket', 'DuckDuckGeese', 'EigenWorms', 'Epilepsy', 'ERing', 'EthanolConcentration', 'FaceDetection', 'FingerMovements', 'HandMovementDirection', 'Handwriting', 'Heartbeat', 'InsectWingbeat', 'JapaneseVowels', 'Libras', 'LSST', 'MotorImagery', 'NATOPS', 'PEMS-SF', 'PenDigits', 'PhonemeSpectra', 'RacketSports', 'SelfRegulationSCP1', 'SelfRegulationSCP2', 'SpokenArabicDigits', 'StandWalkJump', 'UWaveGestureLibrary' ] test_eq(len(get_UCR_multivariate_list()), 30) MTSC_datasets = get_UCR_multivariate_list() UCR_multivariate_list = get_UCR_multivariate_list() UCR_list = sorted(UCR_univariate_list + UCR_multivariate_list) classification_list = UCR_list TSC_datasets = classification_datasets = UCR_list len(UCR_list) # + hide_input=false #export def get_UCR_data(dsid, path='.', parent_dir='data/UCR', on_disk=True, mode='c', Xdtype='float32', ydtype=None, return_split=True, split_data=True, force_download=False, verbose=False): dsid_list = [ds for ds in UCR_list if ds.lower() == dsid.lower()] assert len(dsid_list) > 0, f'{dsid} is not a UCR dataset' dsid = dsid_list[0] return_split = return_split and split_data # keep return_split for compatibility. It will be replaced by split_data if dsid in ['InsectWingbeat']: warnings.warn(f'Be aware that download of the {dsid} dataset is very slow!') pv(f'Dataset: {dsid}', verbose) full_parent_dir = Path(path)/parent_dir full_tgt_dir = full_parent_dir/dsid # if not os.path.exists(full_tgt_dir): os.makedirs(full_tgt_dir) full_tgt_dir.parent.mkdir(parents=True, exist_ok=True) if force_download or not all([os.path.isfile(f'{full_tgt_dir}/{fn}.npy') for fn in ['X_train', 'X_valid', 'y_train', 'y_valid', 'X', 'y']]): # Option A src_website = 'http://www.timeseriesclassification.com/Downloads' decompress_from_url(f'{src_website}/{dsid}.zip', target_dir=full_tgt_dir, verbose=verbose) if dsid == 'DuckDuckGeese': with zipfile.ZipFile(Path(f'{full_parent_dir}/DuckDuckGeese/DuckDuckGeese_ts.zip'), 'r') as zip_ref: zip_ref.extractall(Path(parent_dir)) if not os.path.exists(full_tgt_dir/f'{dsid}_TRAIN.ts') or not os.path.exists(full_tgt_dir/f'{dsid}_TRAIN.ts') or \ Path(full_tgt_dir/f'{dsid}_TRAIN.ts').stat().st_size == 0 or Path(full_tgt_dir/f'{dsid}_TEST.ts').stat().st_size == 0: print('It has not been possible to download the required files') if return_split: return None, None, None, None else: return None, None, None pv('loading ts files to dataframe...', verbose) X_train_df, y_train = _ts2df(full_tgt_dir/f'{dsid}_TRAIN.ts') X_valid_df, y_valid = _ts2df(full_tgt_dir/f'{dsid}_TEST.ts') pv('...ts files loaded', verbose) pv('preparing numpy arrays...', verbose) X_train_ = [] X_valid_ = [] for i in progress_bar(range(X_train_df.shape[-1]), display=verbose, leave=False): X_train_.append(stack_pad(X_train_df[f'dim_{i}'])) # stack arrays even if they have different lengths X_valid_.append(stack_pad(X_valid_df[f'dim_{i}'])) # stack arrays even if they have different lengths X_train = np.transpose(np.stack(X_train_, axis=-1), (0, 2, 1)) X_valid = np.transpose(np.stack(X_valid_, axis=-1), (0, 2, 1)) X_train, X_valid = match_seq_len(X_train, X_valid) np.save(f'{full_tgt_dir}/X_train.npy', X_train) np.save(f'{full_tgt_dir}/y_train.npy', y_train) np.save(f'{full_tgt_dir}/X_valid.npy', X_valid) np.save(f'{full_tgt_dir}/y_valid.npy', y_valid) np.save(f'{full_tgt_dir}/X.npy', concat(X_train, X_valid)) np.save(f'{full_tgt_dir}/y.npy', concat(y_train, y_valid)) del X_train, X_valid, y_train, y_valid delete_all_in_dir(full_tgt_dir, exception='.npy') pv('...numpy arrays correctly saved', verbose) mmap_mode = mode if on_disk else None X_train = np.load(f'{full_tgt_dir}/X_train.npy', mmap_mode=mmap_mode) y_train = np.load(f'{full_tgt_dir}/y_train.npy', mmap_mode=mmap_mode) X_valid = np.load(f'{full_tgt_dir}/X_valid.npy', mmap_mode=mmap_mode) y_valid = np.load(f'{full_tgt_dir}/y_valid.npy', mmap_mode=mmap_mode) if return_split: if Xdtype is not None: X_train = X_train.astype(Xdtype) X_valid = X_valid.astype(Xdtype) if ydtype is not None: y_train = y_train.astype(ydtype) y_valid = y_valid.astype(ydtype) if verbose: print('X_train:', X_train.shape) print('y_train:', y_train.shape) print('X_valid:', X_valid.shape) print('y_valid:', y_valid.shape, '\n') return X_train, y_train, X_valid, y_valid else: X = np.load(f'{full_tgt_dir}/X.npy', mmap_mode=mmap_mode) y = np.load(f'{full_tgt_dir}/y.npy', mmap_mode=mmap_mode) splits = get_predefined_splits(X_train, X_valid) if Xdtype is not None: X = X.astype(Xdtype) if verbose: print('X :', X .shape) print('y :', y .shape) print('splits :', coll_repr(splits[0]), coll_repr(splits[1]), '\n') return X, y, splits get_classification_data = get_UCR_data # - from fastai.data.transforms import get_files PATH = Path('.') dsids = ['ECGFiveDays', 'AtrialFibrillation'] # univariate and multivariate for dsid in dsids: print(dsid) tgt_dir = PATH/f'data/UCR/{dsid}' if os.path.isdir(tgt_dir): shutil.rmtree(tgt_dir) test_eq(len(get_files(tgt_dir)), 0) # no file left X_train, y_train, X_valid, y_valid = get_UCR_data(dsid) test_eq(len(get_files(tgt_dir, '.npy')), 6) test_eq(len(get_files(tgt_dir, '.npy')), len(get_files(tgt_dir))) # test no left file/ dir del X_train, y_train, X_valid, y_valid start = time.time() X_train, y_train, X_valid, y_valid = get_UCR_data(dsid) elapsed = time.time() - start test_eq(elapsed < 1, True) test_eq(X_train.ndim, 3) test_eq(y_train.ndim, 1) test_eq(X_valid.ndim, 3) test_eq(y_valid.ndim, 1) test_eq(len(get_files(tgt_dir, '.npy')), 6) test_eq(len(get_files(tgt_dir, '.npy')), len(get_files(tgt_dir))) # test no left file/ dir test_eq(X_train.ndim, 3) test_eq(y_train.ndim, 1) test_eq(X_valid.ndim, 3) test_eq(y_valid.ndim, 1) test_eq(X_train.dtype, np.float32) test_eq(X_train.__class__.__name__, 'memmap') del X_train, y_train, X_valid, y_valid X_train, y_train, X_valid, y_valid = get_UCR_data(dsid, on_disk=False) test_eq(X_train.__class__.__name__, 'ndarray') del X_train, y_train, X_valid, y_valid X_train, y_train, X_valid, y_valid = get_UCR_data('natops') dsid = 'natops' X_train, y_train, X_valid, y_valid = get_UCR_data(dsid, verbose=True) X, y, splits = get_UCR_data(dsid, split_data=False) test_eq(X[splits[0]], X_train) test_eq(y[splits[1]], y_valid) test_eq(X[splits[0]], X_train) test_eq(y[splits[1]], y_valid) test_type(X, X_train) test_type(y, y_train) #export def check_data(X, y=None, splits=None, show_plot=True): try: X_is_nan = np.isnan(X).sum() except: X_is_nan = 'could not be checked' if X.ndim == 3: shape = f'[{X.shape[0]} samples x {X.shape[1]} features x {X.shape[-1]} timesteps]' print(f'X - shape: {shape} type: {cls_name(X)} dtype:{X.dtype} isnan: {X_is_nan}') else: print(f'X - shape: {X.shape} type: {cls_name(X)} dtype:{X.dtype} isnan: {X_is_nan}') if X_is_nan: warnings.warn('X contains nan values') if y is not None: y_shape = y.shape y = y.ravel() if isinstance(y[0], str): n_classes = f'{len(np.unique(y))} ({len(y)//len(np.unique(y))} samples per class) {L(np.unique(y).tolist())}' y_is_nan = 'nan' in [c.lower() for c in np.unique(y)] print(f'y - shape: {y_shape} type: {cls_name(y)} dtype:{y.dtype} n_classes: {n_classes} isnan: {y_is_nan}') else: y_is_nan = np.isnan(y).sum() print(f'y - shape: {y_shape} type: {cls_name(y)} dtype:{y.dtype} isnan: {y_is_nan}') if y_is_nan: warnings.warn('y contains nan values') if splits is not None: _splits = get_splits_len(splits) overlap = check_splits_overlap(splits) print(f'splits - n_splits: {len(_splits)} shape: {_splits} overlap: {overlap}') if show_plot: plot_splits(splits) dsid = 'ECGFiveDays' X, y, splits = get_UCR_data(dsid, split_data=False, on_disk=False, force_download=False) check_data(X, y, splits) check_data(X[:, 0], y, splits) y = y.astype(np.float32) check_data(X, y, splits) y[:10] = np.nan check_data(X[:, 0], y, splits) X, y, splits = get_UCR_data(dsid, split_data=False, on_disk=False, force_download=False) splits = get_splits(y, 3) check_data(X, y, splits) check_data(X[:, 0], y, splits) y[:5]= np.nan check_data(X[:, 0], y, splits) X, y, splits = get_UCR_data(dsid, split_data=False, on_disk=False, force_download=False) # + #export def get_Monash_regression_list(): return sorted([ "AustraliaRainfall", "HouseholdPowerConsumption1", "HouseholdPowerConsumption2", "BeijingPM25Quality", "BeijingPM10Quality", "Covid3Month", "LiveFuelMoistureContent", "FloodModeling1", "FloodModeling2", "FloodModeling3", "AppliancesEnergy", "BenzeneConcentration", "NewsHeadlineSentiment", "NewsTitleSentiment", "IEEEPPG", #"BIDMC32RR", "BIDMC32HR", "BIDMC32SpO2", "PPGDalia" # Cannot be downloaded ]) Monash_regression_list = get_Monash_regression_list() regression_list = Monash_regression_list TSR_datasets = regression_datasets = regression_list len(Monash_regression_list) # + #export def get_Monash_regression_data(dsid, path='./data/Monash', on_disk=True, mode='c', Xdtype='float32', ydtype=None, split_data=True, force_download=False, verbose=False, timeout=4): dsid_list = [rd for rd in Monash_regression_list if rd.lower() == dsid.lower()] assert len(dsid_list) > 0, f'{dsid} is not a Monash dataset' dsid = dsid_list[0] full_tgt_dir = Path(path)/dsid pv(f'Dataset: {dsid}', verbose) if force_download or not all([os.path.isfile(f'{path}/{dsid}/{fn}.npy') for fn in ['X_train', 'X_valid', 'y_train', 'y_valid', 'X', 'y']]): if dsid == 'AppliancesEnergy': dset_id = 3902637 elif dsid == 'HouseholdPowerConsumption1': dset_id = 3902704 elif dsid == 'HouseholdPowerConsumption2': dset_id = 3902706 elif dsid == 'BenzeneConcentration': dset_id = 3902673 elif dsid == 'BeijingPM25Quality': dset_id = 3902671 elif dsid == 'BeijingPM10Quality': dset_id = 3902667 elif dsid == 'LiveFuelMoistureContent': dset_id = 3902716 elif dsid == 'FloodModeling1': dset_id = 3902694 elif dsid == 'FloodModeling2': dset_id = 3902696 elif dsid == 'FloodModeling3': dset_id = 3902698 elif dsid == 'AustraliaRainfall': dset_id = 3902654 elif dsid == 'PPGDalia': dset_id = 3902728 elif dsid == 'IEEEPPG': dset_id = 3902710 elif dsid == 'BIDMCRR' or dsid == 'BIDM32CRR': dset_id = 3902685 elif dsid == 'BIDMCHR' or dsid == 'BIDM32CHR': dset_id = 3902676 elif dsid == 'BIDMCSpO2' or dsid == 'BIDM32CSpO2': dset_id = 3902688 elif dsid == 'NewsHeadlineSentiment': dset_id = 3902718 elif dsid == 'NewsTitleSentiment': dset_id= 3902726 elif dsid == 'Covid3Month': dset_id = 3902690 for split in ['TRAIN', 'TEST']: url = f"https://zenodo.org/record/{dset_id}/files/{dsid}_{split}.ts" fname = Path(path)/f'{dsid}/{dsid}_{split}.ts' pv('downloading data...', verbose) try: download_data(url, fname, c_key='archive', force_download=force_download, timeout=timeout) except Exception as inst: print(inst) warnings.warn(f'Cannot download {dsid} dataset') if split_data: return None, None, None, None else: return None, None, None pv('...download complete', verbose) try: if split == 'TRAIN': X_train, y_train = _ts2dfV2(fname) X_train = _check_X(X_train) else: X_valid, y_valid = _ts2dfV2(fname) X_valid = _check_X(X_valid) except Exception as inst: print(inst) warnings.warn(f'Cannot create numpy arrays for {dsid} dataset') if split_data: return None, None, None, None else: return None, None, None np.save(f'{full_tgt_dir}/X_train.npy', X_train) np.save(f'{full_tgt_dir}/y_train.npy', y_train) np.save(f'{full_tgt_dir}/X_valid.npy', X_valid) np.save(f'{full_tgt_dir}/y_valid.npy', y_valid) np.save(f'{full_tgt_dir}/X.npy', concat(X_train, X_valid)) np.save(f'{full_tgt_dir}/y.npy', concat(y_train, y_valid)) del X_train, X_valid, y_train, y_valid delete_all_in_dir(full_tgt_dir, exception='.npy') pv('...numpy arrays correctly saved', verbose) mmap_mode = mode if on_disk else None X_train = np.load(f'{full_tgt_dir}/X_train.npy', mmap_mode=mmap_mode) y_train = np.load(f'{full_tgt_dir}/y_train.npy', mmap_mode=mmap_mode) X_valid = np.load(f'{full_tgt_dir}/X_valid.npy', mmap_mode=mmap_mode) y_valid = np.load(f'{full_tgt_dir}/y_valid.npy', mmap_mode=mmap_mode) if Xdtype is not None: X_train = X_train.astype(Xdtype) X_valid = X_valid.astype(Xdtype) if ydtype is not None: y_train = y_train.astype(ydtype) y_valid = y_valid.astype(ydtype) if split_data: if verbose: print('X_train:', X_train.shape) print('y_train:', y_train.shape) print('X_valid:', X_valid.shape) print('y_valid:', y_valid.shape, '\n') return X_train, y_train, X_valid, y_valid else: X = np.load(f'{full_tgt_dir}/X.npy', mmap_mode=mmap_mode) y = np.load(f'{full_tgt_dir}/y.npy', mmap_mode=mmap_mode) splits = get_predefined_splits(X_train, X_valid) if verbose: print('X :', X .shape) print('y :', y .shape) print('splits :', coll_repr(splits[0]), coll_repr(splits[1]), '\n') return X, y, splits get_regression_data = get_Monash_regression_data # - dsid = "Covid3Month" X_train, y_train, X_valid, y_valid = get_Monash_regression_data(dsid, on_disk=False, split_data=True, force_download=False) X, y, splits = get_Monash_regression_data(dsid, on_disk=True, split_data=False, force_download=False, verbose=True) if X_train is not None: test_eq(X_train.shape, (140, 1, 84)) if X is not None: test_eq(X.shape, (201, 1, 84)) # + hide_input=false #export def get_forecasting_list(): return sorted([ "Sunspots", "Weather" ]) forecasting_time_series = get_forecasting_list() # + hide_input=false #export def get_forecasting_time_series(dsid, path='./data/forecasting/', force_download=False, verbose=True, **kwargs): dsid_list = [fd for fd in forecasting_time_series if fd.lower() == dsid.lower()] assert len(dsid_list) > 0, f'{dsid} is not a forecasting dataset' dsid = dsid_list[0] if dsid == 'Weather': full_tgt_dir = Path(path)/f'{dsid}.csv.zip' else: full_tgt_dir = Path(path)/f'{dsid}.csv' pv(f'Dataset: {dsid}', verbose) if dsid == 'Sunspots': url = "https://storage.googleapis.com/laurencemoroney-blog.appspot.com/Sunspots.csv" elif dsid == 'Weather': url = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2016.csv.zip' try: pv("downloading data...", verbose) if force_download: try: os.remove(full_tgt_dir) except OSError: pass download_data(url, full_tgt_dir, force_download=force_download, **kwargs) pv(f"...data downloaded. Path = {full_tgt_dir}", verbose) if dsid == 'Sunspots': df = pd.read_csv(full_tgt_dir, parse_dates=['Date'], index_col=['Date']) return df['Monthly Mean Total Sunspot Number'].asfreq('1M').to_frame() elif dsid == 'Weather': # This code comes from a great Keras time-series tutorial notebook (https://www.tensorflow.org/tutorials/structured_data/time_series) df = pd.read_csv(full_tgt_dir) df = df[5::6] # slice [start:stop:step], starting from index 5 take every 6th record. date_time = pd.to_datetime(df.pop('Date Time'), format='%d.%m.%Y %H:%M:%S') # remove error (negative wind) wv = df['wv (m/s)'] bad_wv = wv == -9999.0 wv[bad_wv] = 0.0 max_wv = df['max. wv (m/s)'] bad_max_wv = max_wv == -9999.0 max_wv[bad_max_wv] = 0.0 wv = df.pop('wv (m/s)') max_wv = df.pop('max. wv (m/s)') # Convert to radians. wd_rad = df.pop('wd (deg)')*np.pi / 180 # Calculate the wind x and y components. df['Wx'] = wv*np.cos(wd_rad) df['Wy'] = wv*np.sin(wd_rad) # Calculate the max wind x and y components. df['max Wx'] = max_wv*np.cos(wd_rad) df['max Wy'] = max_wv*np.sin(wd_rad) timestamp_s = date_time.map(datetime.timestamp) day = 24*60*60 year = (365.2425)*day df['Day sin'] = np.sin(timestamp_s * (2 * np.pi / day)) df['Day cos'] = np.cos(timestamp_s * (2 * np.pi / day)) df['Year sin'] = np.sin(timestamp_s * (2 * np.pi / year)) df['Year cos'] = np.cos(timestamp_s * (2 * np.pi / year)) df.reset_index(drop=True, inplace=True) return df else: return full_tgt_dir except Exception as inst: print(inst) warnings.warn(f"Cannot download {dsid} dataset") return # + hide_input=false ts = get_forecasting_time_series("sunspots", force_download=False) test_eq(len(ts), 3235) ts # - ts = get_forecasting_time_series("weather", force_download=False) if ts is not None: test_eq(len(ts), 70091) print(ts) # + # export Monash_forecasting_list = ['m1_yearly_dataset', 'm1_quarterly_dataset', 'm1_monthly_dataset', 'm3_yearly_dataset', 'm3_quarterly_dataset', 'm3_monthly_dataset', 'm3_other_dataset', 'm4_yearly_dataset', 'm4_quarterly_dataset', 'm4_monthly_dataset', 'm4_weekly_dataset', 'm4_daily_dataset', 'm4_hourly_dataset', 'tourism_yearly_dataset', 'tourism_quarterly_dataset', 'tourism_monthly_dataset', 'nn5_daily_dataset_with_missing_values', 'nn5_daily_dataset_without_missing_values', 'nn5_weekly_dataset', 'cif_2016_dataset', 'kaggle_web_traffic_dataset_with_missing_values', 'kaggle_web_traffic_dataset_without_missing_values', 'kaggle_web_traffic_weekly_dataset', 'solar_10_minutes_dataset', 'solar_weekly_dataset', 'electricity_hourly_dataset', 'electricity_weekly_dataset', 'london_smart_meters_dataset_with_missing_values', 'london_smart_meters_dataset_without_missing_values', 'wind_farms_minutely_dataset_with_missing_values', 'wind_farms_minutely_dataset_without_missing_values', 'car_parts_dataset_with_missing_values', 'car_parts_dataset_without_missing_values', 'dominick_dataset', 'fred_md_dataset', 'traffic_hourly_dataset', 'traffic_weekly_dataset', 'pedestrian_counts_dataset', 'hospital_dataset', 'covid_deaths_dataset', 'kdd_cup_2018_dataset_with_missing_values', 'kdd_cup_2018_dataset_without_missing_values', 'weather_dataset', 'sunspot_dataset_with_missing_values', 'sunspot_dataset_without_missing_values', 'saugeenday_dataset', 'us_births_dataset', 'elecdemand_dataset', 'solar_4_seconds_dataset', 'wind_4_seconds_dataset', 'Sunspots', 'Weather'] forecasting_list = Monash_forecasting_list # + # export ## Original code available at: https://github.com/rakshitha123/TSForecasting # This repository contains the implementations related to the experiments of a set of publicly available datasets that are used in # the time series forecasting research space. # The benchmark datasets are available at: https://zenodo.org/communities/forecasting. For more details, please refer to our website: # https://forecastingdata.org/ and paper: https://arxiv.org/abs/2105.06643. # Citation: # @misc{godahewa2021monash, # author="<NAME> and <NAME>. and <NAME>. and <NAME>", # title="Monash Time Series Forecasting Archive", # howpublished ="\url{https://arxiv.org/abs/2105.06643}", # year="2021" # } # Converts the contents in a .tsf file into a dataframe and returns it along with other meta-data of the dataset: frequency, horizon, whether the dataset contains missing values and whether the series have equal lengths # # Parameters # full_file_path_and_name - complete .tsf file path # replace_missing_vals_with - a term to indicate the missing values in series in the returning dataframe # value_column_name - Any name that is preferred to have as the name of the column containing series values in the returning dataframe def convert_tsf_to_dataframe(full_file_path_and_name, replace_missing_vals_with = 'NaN', value_column_name = "series_value"): col_names = [] col_types = [] all_data = {} line_count = 0 frequency = None forecast_horizon = None contain_missing_values = None contain_equal_length = None found_data_tag = False found_data_section = False started_reading_data_section = False with open(full_file_path_and_name, 'r', encoding='cp1252') as file: for line in file: # Strip white space from start/end of line line = line.strip() if line: if line.startswith("@"): # Read meta-data if not line.startswith("@data"): line_content = line.split(" ") if line.startswith("@attribute"): if (len(line_content) != 3): # Attributes have both name and type raise _TsFileParseException("Invalid meta-data specification.") col_names.append(line_content[1]) col_types.append(line_content[2]) else: if len(line_content) != 2: # Other meta-data have only values raise _TsFileParseException("Invalid meta-data specification.") if line.startswith("@frequency"): frequency = line_content[1] elif line.startswith("@horizon"): forecast_horizon = int(line_content[1]) elif line.startswith("@missing"): contain_missing_values = bool(distutils.util.strtobool(line_content[1])) elif line.startswith("@equallength"): contain_equal_length = bool(distutils.util.strtobool(line_content[1])) else: if len(col_names) == 0: raise _TsFileParseException("Missing attribute section. Attribute section must come before data.") found_data_tag = True elif not line.startswith("#"): if len(col_names) == 0: raise _TsFileParseException("Missing attribute section. Attribute section must come before data.") elif not found_data_tag: raise _TsFileParseException("Missing @data tag.") else: if not started_reading_data_section: started_reading_data_section = True found_data_section = True all_series = [] for col in col_names: all_data[col] = [] full_info = line.split(":") if len(full_info) != (len(col_names) + 1): raise _TsFileParseException("Missing attributes/values in series.") series = full_info[len(full_info) - 1] series = series.split(",") if(len(series) == 0): raise _TsFileParseException("A given series should contains a set of comma separated numeric values. At least one numeric value should be there in a series. Missing values should be indicated with ? symbol") numeric_series = [] for val in series: if val == "?": numeric_series.append(replace_missing_vals_with) else: numeric_series.append(float(val)) if (numeric_series.count(replace_missing_vals_with) == len(numeric_series)): raise _TsFileParseException("All series values are missing. A given series should contains a set of comma separated numeric values. At least one numeric value should be there in a series.") all_series.append(pd.Series(numeric_series).array) for i in range(len(col_names)): att_val = None if col_types[i] == "numeric": att_val = int(full_info[i]) elif col_types[i] == "string": att_val = str(full_info[i]) elif col_types[i] == "date": att_val = datetime.datetime.strptime(full_info[i], '%Y-%m-%d %H-%M-%S') else: raise _TsFileParseException("Invalid attribute type.") # Currently, the code supports only numeric, string and date types. Extend this as required. if(att_val == None): raise _TsFileParseException("Invalid attribute value.") else: all_data[col_names[i]].append(att_val) line_count = line_count + 1 if line_count == 0: raise _TsFileParseException("Empty file.") if len(col_names) == 0: raise _TsFileParseException("Missing attribute section.") if not found_data_section: raise _TsFileParseException("Missing series information under data section.") all_data[value_column_name] = all_series loaded_data = pd.DataFrame(all_data) return loaded_data, frequency, forecast_horizon, contain_missing_values, contain_equal_length # + # export def get_Monash_forecasting_data(dsid, path='./data/forecasting/', force_download=False, remove_from_disk=False, verbose=True): pv(f'Dataset: {dsid}', verbose) dsid = dsid.lower() assert dsid in Monash_forecasting_list, f'{dsid} not available in Monash_forecasting_list' if dsid == 'm1_yearly_dataset': url = 'https://zenodo.org/record/4656193/files/m1_yearly_dataset.zip' elif dsid == 'm1_quarterly_dataset': url = 'https://zenodo.org/record/4656154/files/m1_quarterly_dataset.zip' elif dsid == 'm1_monthly_dataset': url = 'https://zenodo.org/record/4656159/files/m1_monthly_dataset.zip' elif dsid == 'm3_yearly_dataset': url = 'https://zenodo.org/record/4656222/files/m3_yearly_dataset.zip' elif dsid == 'm3_quarterly_dataset': url = 'https://zenodo.org/record/4656262/files/m3_quarterly_dataset.zip' elif dsid == 'm3_monthly_dataset': url = 'https://zenodo.org/record/4656298/files/m3_monthly_dataset.zip' elif dsid == 'm3_other_dataset': url = 'https://zenodo.org/record/4656335/files/m3_other_dataset.zip' elif dsid == 'm4_yearly_dataset': url = 'https://zenodo.org/record/4656379/files/m4_yearly_dataset.zip' elif dsid == 'm4_quarterly_dataset': url = 'https://zenodo.org/record/4656410/files/m4_quarterly_dataset.zip' elif dsid == 'm4_monthly_dataset': url = 'https://zenodo.org/record/4656480/files/m4_monthly_dataset.zip' elif dsid == 'm4_weekly_dataset': url = 'https://zenodo.org/record/4656522/files/m4_weekly_dataset.zip' elif dsid == 'm4_daily_dataset': url = 'https://zenodo.org/record/4656548/files/m4_daily_dataset.zip' elif dsid == 'm4_hourly_dataset': url = 'https://zenodo.org/record/4656589/files/m4_hourly_dataset.zip' elif dsid == 'tourism_yearly_dataset': url = 'https://zenodo.org/record/4656103/files/tourism_yearly_dataset.zip' elif dsid == 'tourism_quarterly_dataset': url = 'https://zenodo.org/record/4656093/files/tourism_quarterly_dataset.zip' elif dsid == 'tourism_monthly_dataset': url = 'https://zenodo.org/record/4656096/files/tourism_monthly_dataset.zip' elif dsid == 'nn5_daily_dataset_with_missing_values': url = 'https://zenodo.org/record/4656110/files/nn5_daily_dataset_with_missing_values.zip' elif dsid == 'nn5_daily_dataset_without_missing_values': url = 'https://zenodo.org/record/4656117/files/nn5_daily_dataset_without_missing_values.zip' elif dsid == 'nn5_weekly_dataset': url = 'https://zenodo.org/record/4656125/files/nn5_weekly_dataset.zip' elif dsid == 'cif_2016_dataset': url = 'https://zenodo.org/record/4656042/files/cif_2016_dataset.zip' elif dsid == 'kaggle_web_traffic_dataset_with_missing_values': url = 'https://zenodo.org/record/4656080/files/kaggle_web_traffic_dataset_with_missing_values.zip' elif dsid == 'kaggle_web_traffic_dataset_without_missing_values': url = 'https://zenodo.org/record/4656075/files/kaggle_web_traffic_dataset_without_missing_values.zip' elif dsid == 'kaggle_web_traffic_weekly': url = 'https://zenodo.org/record/4656664/files/kaggle_web_traffic_weekly_dataset.zip' elif dsid == 'solar_10_minutes_dataset': url = 'https://zenodo.org/record/4656144/files/solar_10_minutes_dataset.zip' elif dsid == 'solar_weekly_dataset': url = 'https://zenodo.org/record/4656151/files/solar_weekly_dataset.zip' elif dsid == 'electricity_hourly_dataset': url = 'https://zenodo.org/record/4656140/files/electricity_hourly_dataset.zip' elif dsid == 'electricity_weekly_dataset': url = 'https://zenodo.org/record/4656141/files/electricity_weekly_dataset.zip' elif dsid == 'london_smart_meters_dataset_with_missing_values': url = 'https://zenodo.org/record/4656072/files/london_smart_meters_dataset_with_missing_values.zip' elif dsid == 'london_smart_meters_dataset_without_missing_values': url = 'https://zenodo.org/record/4656091/files/london_smart_meters_dataset_without_missing_values.zip' elif dsid == 'wind_farms_minutely_dataset_with_missing_values': url = 'https://zenodo.org/record/4654909/files/wind_farms_minutely_dataset_with_missing_values.zip' elif dsid == 'wind_farms_minutely_dataset_without_missing_values': url = 'https://zenodo.org/record/4654858/files/wind_farms_minutely_dataset_without_missing_values.zip' elif dsid == 'car_parts_dataset_with_missing_values': url = 'https://zenodo.org/record/4656022/files/car_parts_dataset_with_missing_values.zip' elif dsid == 'car_parts_dataset_without_missing_values': url = 'https://zenodo.org/record/4656021/files/car_parts_dataset_without_missing_values.zip' elif dsid == 'dominick_dataset': url = 'https://zenodo.org/record/4654802/files/dominick_dataset.zip' elif dsid == 'fred_md_dataset': url = 'https://zenodo.org/record/4654833/files/fred_md_dataset.zip' elif dsid == 'traffic_hourly_dataset': url = 'https://zenodo.org/record/4656132/files/traffic_hourly_dataset.zip' elif dsid == 'traffic_weekly_dataset': url = 'https://zenodo.org/record/4656135/files/traffic_weekly_dataset.zip' elif dsid == 'pedestrian_counts_dataset': url = 'https://zenodo.org/record/4656626/files/pedestrian_counts_dataset.zip' elif dsid == 'hospital_dataset': url = 'https://zenodo.org/record/4656014/files/hospital_dataset.zip' elif dsid == 'covid_deaths_dataset': url = 'https://zenodo.org/record/4656009/files/covid_deaths_dataset.zip' elif dsid == 'kdd_cup_2018_dataset_with_missing_values': url = 'https://zenodo.org/record/4656719/files/kdd_cup_2018_dataset_with_missing_values.zip' elif dsid == 'kdd_cup_2018_dataset_without_missing_values': url = 'https://zenodo.org/record/4656756/files/kdd_cup_2018_dataset_without_missing_values.zip' elif dsid == 'weather_dataset': url = 'https://zenodo.org/record/4654822/files/weather_dataset.zip' elif dsid == 'sunspot_dataset_with_missing_values': url = 'https://zenodo.org/record/4654773/files/sunspot_dataset_with_missing_values.zip' elif dsid == 'sunspot_dataset_without_missing_values': url = 'https://zenodo.org/record/4654722/files/sunspot_dataset_without_missing_values.zip' elif dsid == 'saugeenday_dataset': url = 'https://zenodo.org/record/4656058/files/saugeenday_dataset.zip' elif dsid == 'us_births_dataset': url = 'https://zenodo.org/record/4656049/files/us_births_dataset.zip' elif dsid == 'elecdemand_dataset': url = 'https://zenodo.org/record/4656069/files/elecdemand_dataset.zip' elif dsid == 'solar_4_seconds_dataset': url = 'https://zenodo.org/record/4656027/files/solar_4_seconds_dataset.zip' elif dsid == 'wind_4_seconds_dataset': url = 'https://zenodo.org/record/4656032/files/wind_4_seconds_dataset.zip' path = Path(path) full_path = path/f'{dsid}.tsf' if not full_path.exists() or force_download: try: decompress_from_url(url, target_dir=path, verbose=verbose) except Exception as inst: print(inst) pv("converting dataframe to numpy array...", verbose) data, frequency, forecast_horizon, contain_missing_values, contain_equal_length = convert_tsf_to_dataframe(full_path) X = to3d(stack_pad(data['series_value'])) pv("...dataframe converted to numpy array", verbose) pv(f'\nX.shape: {X.shape}', verbose) pv(f'freq: {frequency}', verbose) pv(f'forecast_horizon: {forecast_horizon}', verbose) pv(f'contain_missing_values: {contain_missing_values}', verbose) pv(f'contain_equal_length: {contain_equal_length}', verbose=verbose) if remove_from_disk: os.remove(full_path) return X get_forecasting_data = get_Monash_forecasting_data # - dsid = 'm1_yearly_dataset' X = get_Monash_forecasting_data(dsid, force_download=False) if X is not None: test_eq(X.shape, (181, 1, 58)) # + hide_input=false #hide from tsai.imports import create_scripts from tsai.export import get_nb_name nb_name = get_nb_name() nb_name = "012_data.external.ipynb" create_scripts(nb_name); # -
nbs/012_data.external.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import folium from folium.plugins import MousePosition m = folium.Map() MousePosition().add_to(m) m # + m = folium.Map() formatter = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};" MousePosition( position="topright", separator=" | ", empty_string="NaN", lng_first=True, num_digits=20, prefix="Coordinates:", lat_formatter=formatter, lng_formatter=formatter, ).add_to(m) m
prototype/examples/plugin-MousePosition.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Chapter 4 - Clustering Models # ## Segment 3 - DBSCan clustering to identify outliers # + import pandas as pd import matplotlib.pyplot as plt from pylab import rcParams import seaborn as sb import sklearn from sklearn.cluster import DBSCAN from collections import Counter # - # %matplotlib inline rcParams['figure.figsize'] = 5, 4 sb.set_style('whitegrid') # ### DBSCan clustering to identify outliers # #### Train your model and identify outliers import pathlib import os address = pathlib.Path(os.getcwd()).parent address = pathlib.Path(os.path.join(address, 'Data/iris.data.csv')) # + # with this example, we're going to use the same data that we used for the rest of this chapter. So we're going to copy and # paste in the code. df = pd.read_csv(address, header=None, sep=',') df.columns=['Sepal Length','Sepal Width','Petal Length','Petal Width', 'Species'] data = df.iloc[:,0:4].values target = df.iloc[:,4].values df[:5] # + tags=[] model = DBSCAN(eps=0.8, min_samples=19).fit(data) print(model) # - # #### Visualize your results # + tags=[] outliers_df = pd.DataFrame(data) print(Counter(model.labels_)) print(outliers_df[model.labels_ ==-1]) # + fig = plt.figure() ax = fig.add_axes([.1, .1, 1, 1]) colors = model.labels_ ax.scatter(data[:,2], data[:,1], c=colors, s=120) ax.set_xlabel('Petal Length') ax.set_ylabel('Sepal Width') plt.title('DBSCAN for Outlier Detection')
Pt_2/04_03_DBSCan_clustering_to_identify_outliers/04_03_end.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.5 # language: python # name: python3 # --- # # IoT Equipment Failure Prediction using Sensor data # ## 1 Environment Setup # ### 1.1 Import dependent libraries # Import libraries import pandas as pd import numpy as np import pdb import json import re import requests import sys import types import ibm_boto3 # Import libraries from io import StringIO from sklearn.cross_validation import train_test_split from sklearn.linear_model import LogisticRegression from sklearn import metrics from botocore.client import Config # ## 2 Create IoT Predictive Analytics Functions # + # Function to extract Column names of dataset def dataset_columns(dataset): return list(dataset.columns.values) # Function to train Logistic regression model def train_logistic_regression(x_vals, y_vals): logistic_regression_model = LogisticRegression() logistic_regression_model.fit(x_vals, y_vals) return logistic_regression_model # Function to return Predicted values def score_data(trained_model, x_vals): ypredict = trained_model.predict(x_vals) return ypredict # Function to calculate Prediction accuracy of model def model_accuracy(trained_model, variables, targets): accuracy_score = trained_model.score(variables, targets) return accuracy_score # Function to generate Confusion matrix def confusion_matrix(actfail, predictfail): # Compute Confusion matrix print("Actual, Predicted Observations: ",len(actfail), len(predictfail)) # print(actfail, predictfail) anpn = 0 anpy = 0 aypn = 0 aypy = 0 for i in range(len(actfail)): if (actfail[i]==0 and predictfail[i]==0): anpn = anpn + 1 elif (actfail[i]==0 and predictfail[i]==1): anpy = anpy + 1 elif (actfail[i]==1 and predictfail[i]==0): aypn = aypn + 1 else: aypy = aypy + 1 # Confusoin matrix print ("--------------------------------------------") print ("Confusion Matrix") print ("--------------------------------------------") print (" ", "Predicted N", "Predicted Y") print ("Actual N ", anpn," ", anpy) print ("Actual Y ", aypn," ", aypy) print ("--------------------------------------------") print ("Total observations : ", anpn+anpy+aypn+aypy) print ("False Positives : ", anpy) print ("False Negatives : ", aypn) print ("Overall Accuracy : ", round((float(anpn+aypy)/float(anpn+anpy+aypn+aypy))*100, 2), "%") print ("Sensitivity/Recall : ", round((float(aypy)/float(aypn+aypy))*100, 2), "%") print ("Specificity : ", round((float(anpn)/float(anpn+anpy))*100, 2), "%") print ("Precision : ", round((float(aypy)/float(anpy+aypy))*100, 2), "%") print ("--------------------------------------------") # - # ## 3 Configure Parameters for Change Point Detection # ### 3.1 Read DSX Configuration file and load all parameters # # Complete below 2 steps before executing the rest of the cells # # 1. Configure the parameters in JSON file and upload to Object storage # 2. Set the Configuration .json file name in the next section # # #### 3.1.1 Set the name of the .json configuration file # Specify file names for configuration files v_sampleConfigFileName = "iotpredict_config.json" # #### 3.1.2 Insert the Object Storage file credentials to read the .json configuration file # @hidden_cell # The section below needs to be modified: # Insert your credentials to read data from your data sources and replace # the credentials_1 = {} section below # @hidden_cell # The following code contains the credentials for a file in your IBM Cloud Object Storage. # You might want to remove those credentials before you share your notebook. credentials_1 = { 'IBM_API_KEY_ID': '<KEY>', 'IAM_SERVICE_ID': 'iam-ServiceId-b0697259-99e2-4f0c-a221-2c8836944929', 'ENDPOINT': 'https://s3-api.us-geo.objectstorage.service.networklayer.com', 'IBM_AUTH_ENDPOINT': 'https://iam.ng.bluemix.net/oidc/token', 'BUCKET': 'iotpredictivecloudstorage-donotdelete-pr-yezu9utshquhes', 'FILE': 'iotpredict_config.txt' } # ### 3.2 Read Configuration parametric values # + # This function accesses a file in your Object Storage. # The definition uses your credentials that you set in the previous step. cos = ibm_boto3.client('s3', ibm_api_key_id=credentials_1['IBM_API_KEY_ID'], ibm_service_instance_id=credentials_1['IAM_SERVICE_ID'], ibm_auth_endpoint=credentials_1['IBM_AUTH_ENDPOINT'], config=Config(signature_version='oauth'), endpoint_url=credentials_1['ENDPOINT']) def get_file(filename): '''Retrieve file from Cloud Object Storage''' fileobject = cos.get_object(Bucket=credentials_1['BUCKET'], Key=filename)['Body'] return fileobject def load_string(fileobject): '''Load the file contents into a Python string''' text = fileobject.read() return text def put_file(filename, filecontents): '''Write file to Cloud Object Storage''' resp = cos.put_object(Bucket=credentials_1['BUCKET'], Key=filename, Body=filecontents) return resp # - # Function to Read json parametric values def f_getconfigval(injsonstr, invarname): # paramname, paramvalue # Unpack the json parameter values # This section requires regex for i in range(len(injsonstr)): pair = injsonstr[i] # Return parametric value if pair['paramname'] == invarname: return(pair['paramvalue']) # + # Read configuration parameters from JSON file # @hidden_cell # The section below needs to be modified: # Insert your credentials to read data from your data sources and replace # the idaConnect() section below # This function accesses a file in your Object Storage. The definition contains your # credentials # Your data file was loaded into a StringIO object and you can process the data. # Please read the documentation of pandas to learn more about your possibilities to load your data. # pandas documentation: http://pandas.pydata.org/pandas-docs/stable/io.html inputfo = load_string(get_file(v_sampleConfigFileName)) inputfo = inputfo.decode('utf-8') d = json.loads(inputfo) print(d) # - # Read JSON configuration parametric values # Unpack the json parameter values # This section uses regex v_feature_list = eval("list("+ f_getconfigval(d, "features") +")") v_target = str(f_getconfigval(d, "target")) v_train_datasize = float(f_getconfigval(d, "data_size")) # Verify configuration parametric values # print (feature_list, target, train_datasize) print (v_feature_list, v_target, v_train_datasize) # ## 4 Read IoT Sensor data from database # + # Read data from DB2 warehouse in BMX # ----------------------------------- from ibmdbpy import IdaDataBase, IdaDataFrame # Call function to read data for specific sensor # @hidden_cell # The section below needs to be modified: # Insert your credentials to read data from your data sources and replace # the idaConnect() section below # This connection object is used to access your data and contains your credentials. idadb_d281f6cd34eb4bc98f0183a45598dbb9 = IdaDataBase(dsn='DASHDB;Database=BLUDB;Hostname=dashdb-entry-yp-lon02-01.services.eu-gb.bluemix.net;Port=50000;PROTOCOL=TCPIP;UID=dash100002;PWD=<PASSWORD>_<PASSWORD>_') df_iotdata = IdaDataFrame(idadb_d281f6cd34eb4bc98f0183a45598dbb9, 'DASH100002.IOT_SENSOR_DATA').as_dataframe() # Check Number of observations read for analysis print ("Number of Observations :", len(df_iotdata)) # Inspect a few observations df_iotdata.head() # - # Print dataset column names datacolumns = dataset_columns(df_iotdata) print ("Data set columns : ", list(datacolumns)) # ## 5 Run Failure Prediction algorithm on IoT data # ### 5.1 Split data into Training and Test data # + # Split Training and Testing data train_x, test_x, train_y, test_y = train_test_split(df_iotdata[v_feature_list], df_iotdata[v_target], train_size=v_train_datasize) print ("Train x counts : ", len(train_x), len(train_x.columns.values)) print ("Train y counts : ", len(train_y)) print ("Test x counts : ", len(test_x), len(test_x.columns.values)) print ("Test y counts : ", len(test_y)) # - # ### 5.2 Train the Predictive model # + # Training Logistic regression model trained_logistic_regression_model = train_logistic_regression(train_x, train_y) train_accuracy = model_accuracy(trained_logistic_regression_model, train_x, train_y) # Testing the logistic regression model test_accuracy = model_accuracy(trained_logistic_regression_model, test_x, test_y) print ("Training Accuracy : ", round(train_accuracy * 100, 2), "%") # - # ### 5.3 Score the Test data using the Trained model # Model accuracy: Score and construct Confusion matrix for Test data actfail = test_y.values predictfail = score_data(trained_logistic_regression_model, test_x) # ## 6 Confusion matrix for deeper analysis of Prediction accuracy # ##### Confusion matrix outputs below can be used for calculating more customised Accuracy metrics # Print Count of Actual fails, Predicted fails # Print Confusion matrix confusion_matrix(actfail, predictfail)
notebook/watson_iotfailure_prediction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline happines_data = pd.read_csv('2019.csv', parse_dates=True, encoding = "cp1252") happines_data.head() # + X = happines_data[['GDP per capita', 'Social support', 'Healthy life expectancy', 'Freedom to make life choices', 'Generosity', 'Perceptions of corruption']] y = happines_data['Score'] # + from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # - # # Support Vector Regression # + from sklearn.svm import SVR svr_rbf = SVR(kernel='rbf', C=1.2, gamma=6.4) svr_rbf.fit(X_train, y_train) print(f"""train: {svr_rbf.score(X_train, y_train)}\ntest: {svr_rbf.score(X_test, y_test)}""") # + svr_lin = SVR(kernel='linear', C=10) svr_lin.fit(X_train, y_train) print(f"""train: {svr_lin.score(X_train, y_train)}\ntest: {svr_lin.score(X_test, y_test)}""") # - pd.Series(abs(svr_lin.coef_[0]), index=X.columns).nlargest(10).plot(kind='barh') # + svr_poly = SVR(kernel='poly', C=10, degree=4) svr_poly.fit(X_train, y_train) print(f"""train: {svr_poly.score(X_train, y_train)}\ntest: {svr_poly.score(X_test, y_test)}""") # + gamma = np.arange(0.1, 10, 0.1) # gamma = [0.1, 1, 10, 100] results = [] for feature in gamma: dt = SVR(kernel='rbf', gamma=feature) dt.fit(X_train, y_train) results.append(dt.score(X_test, y_test)) fig, ax = plt.subplots(figsize=(17,8)) plt.plot(gamma, results, 'b') ax.set_axisbelow(True) ax.minorticks_on() ax.grid(which='major', linestyle='-', linewidth=0.5, color='black',) ax.grid(which='minor', linestyle=':', linewidth=0.5, color='black', alpha=0.7) plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1)) # + results = [] gammas=[] for i in np.arange(0.1,10,0.1): nnm = SVR(kernel='rbf',gamma=i) nnm.fit(X_train, y_train) results.append(nnm.score(X_test, y_test)) gammas.append(i) print(max(results)) print(results.index(max(results))) print(results[results.index(max(results))]) print(gammas[results.index(max(results))]) # + cs = np.arange(0.1, 3, 0.1) # cs = [0.1, 1, 10, 100, 1000] results = [] for feature in cs: dt = SVR(kernel='rbf', C=feature, gamma=6.4) dt.fit(X_train, y_train) results.append(dt.score(X_test, y_test)) fig, ax = plt.subplots(figsize=(17,8)) plt.plot(cs, results, 'b') ax.set_axisbelow(True) ax.minorticks_on() ax.grid(which='major', linestyle='-', linewidth=0.5, color='black',) ax.grid(which='minor', linestyle=':', linewidth=0.5, color='black', alpha=0.7) plt.gca().xaxis.set_major_locator(plt.MultipleLocator(0.1)) # - print(results[results.index(max(results))]) print(cs[results.index(max(results))])
Regression algorithms/Support Vector Regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### First Try of Predicting Salary # # For the last two questions regarding what are related to relationships of variables with salary and job satisfaction - Each of these questions will involve not only building some sort of predictive model, but also finding and interpretting the influential components of whatever model we build. # # To get started let's read in the necessary libraries and take a look at some of our columns of interest. # + import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error import WhatHappened as t import seaborn as sns # %matplotlib inline df = pd.read_csv('./survey_results_public.csv') df.head() # - # Now take a look at the summary statistics associated with the quantitative variables in your dataset. df.describe() # #### Question 1 # # **1.** Use the above to match each variable (**a**, **b**, **c**, **d**, **e**, or **f**) as the appropriate key that describes the value in the **desc_sol** dictionary. # + a = 40 b = 'HoursPerWeek' c = 'Salary' d = 'Respondent' e = 10 f = 'ExpectedSalary' desc_sol = {'A column just listing an index for each row': #letter here, 'The maximum Satisfaction on the scales for the survey': #letter here, 'The column with the most missing values': #letter here, 'The variable with the highest spread of values': #letter here} # Check your solution t.describe_check(desc_sol) # - # A picture can often tell us more than numbers. df.hist(); # Often a useful plot is a correlation matrix - this can tell you which variables are related to one another. sns.heatmap(df.corr(), annot=True, fmt=".2f"); # #### Question 2 # # **2.** Use the scatterplot matrix above to match each variable (**a**, **b**, **c**, **d**, **e**, **f**, or **g**) as the appropriate key that describes the value in the **scatter_sol** dictionary. # + a = 0.65 b = -0.01 c = 'ExpectedSalary' d = 'No' e = 'Yes' f = 'CareerSatisfaction' g = -0.15 scatter_sol = {'The column with the strongest correlation with Salary': #letter here, 'The data suggests more hours worked relates to higher salary': #letter here, 'Data in the ______ column meant missing data in three other columns': #letter here, 'The strongest negative relationship had what correlation?': #letter here} t.scatter_check(scatter_sol) # - # Here we move our quantitative variables to an X matrix, which we will use to predict our response. We also create our response. We then split our data into training and testing data. Then when starting our four step process, our fit step breaks. # # ### Remember from the Video, this code will break! # + # Consider only numerica variables X = df[['CareerSatisfaction', 'HoursPerWeek', 'JobSatisfaction', 'StackOverflowSatisfaction']] y = df['Salary'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .30, random_state=42) #Four steps: #Instantiate lm_model = LinearRegression(normalize=True) #Fit - why does this break? lm_model.fit(X_train, y_train) #Predict #Score # - # #### Question 3 # # **3.** Use the results above to match each variable (**a**, **b**, **c**, **d**, **e**, or **f** ) as the appropriate key that describes the value in the **lm_fit_sol** dictionary. # + a = 'it is a way to assure your model extends well to new data' b = 'it assures the same train and test split will occur for different users' c = 'there is no correct match of this question' d = 'sklearn fit methods cannot accept NAN values' e = 'it is just a convention people do that will likely go away soon' f = 'python just breaks for no reason sometimes' lm_fit_sol = {'What is the reason that the fit method broke?': #letter here, 'What does the random_state parameter do for the train_test_split function?': #letter here, 'What is the purpose of creating a train test split?': #letter here} t.lm_fit_check(lm_fit_sol)
lessons/CRISP_DM/.ipynb_checkpoints/What Happened?-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd train = pd.read_csv('data/train.tsv', sep='\t') test = pd.read_csv('data/valid.tsv', sep='\t') text = list(train.Post.values) text += list(test.Post.values) len(text) with open('texts.txt', 'w+') as f: f.write('\n'.join(text)) # + active="" # python -m scripts.run_language_modeling --train_data_file "../constraint-hate/clean.txt" \ # --line_by_line \ # --output_dir "/scratch/indic-tapt2" \ # --model_type "ai4bharat/indic-bert" \ # --mlm \ # --per_gpu_train_batch_size 4 \ # --gradient_accumulation_steps 8 \ # --model_name_or_path "ai4bharat/indic-bert" \ # --do_train \ # --num_train_epochs 100 \ # --learning_rate 0.0001 \ # --logging_steps 50 \ # --block_size 128 # - import pickle with open('train.pickle', 'rb') as f: dict1 = pickle.load(f) with open('valid.pickle', 'rb') as f: dict2 = pickle.load(f) dict1['clean'][0:20] dict2['clean'][0:20] clean = dict1['clean'][1:] clean += dict2['clean'][1:] len(clean) with open('clean.txt', 'w+') as f: f.write('\n'.join(clean))
preprocessing/.ipynb_checkpoints/tapt_preprocessor-checkpoint.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # # 📝 Exercise M1.03 # # The goal of this exercise is to compare the performance of our classifier in # the previous notebook (roughly 81% accuracy with `LogisticRegression`) to # some simple baseline classifiers. The simplest baseline classifier is one # that always predicts the same class, irrespective of the input data. # # - What would be the score of a model that always predicts `' >50K'`? # - What would be the score of a model that always predicts `' <=50K'`? # - Is 81% or 82% accuracy a good score for this problem? # # Use a `DummyClassifier` and do a train-test split to evaluate # its accuracy on the test set. This # [link](https://scikit-learn.org/stable/modules/model_evaluation.html#dummy-estimators) # shows a few examples of how to evaluate the generalization performance of these # baseline models. # + import pandas as pd adult_census = pd.read_csv("../datasets/adult-census.csv") # - # We will first split our dataset to have the target separated from the data # used to train our predictive model. target_name = "class" target = adult_census[target_name] data = adult_census.drop(columns=target_name) # We start by selecting only the numerical columns as seen in the previous # notebook. # + numerical_columns = [ "age", "capital-gain", "capital-loss", "hours-per-week"] data_numeric = data[numerical_columns] # - # Split the data and target into a train and test set. # + from sklearn.model_selection import train_test_split # Write your code here. # - # Use a `DummyClassifier` such that the resulting classifier will always # predict the class `' >50K'`. What is the accuracy score on the test set? # Repeat the experiment by always predicting the class `' <=50K'`. # # Hint: you can set the `strategy` parameter of the `DummyClassifier` to # achieve the desired behavior. # + from sklearn.dummy import DummyClassifier # Write your code here.
notebooks/02_numerical_pipeline_ex_01.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import numpy.random as rnd import importlib from tcpr import TargetContrastivePessimisticClassifier from util import one_hot from viz import plotqda # + # %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['text.usetex'] = True plt.rcParams['font.family'] = "normal" plt.rcParams['font.size'] = 20 plt.rcParams["font.weight"] = "bold" xl = [-8, 8] yl = [-6, 10] fS = 20 # - # Generate source data N = 100 N0 = 50 N1 = N - N0 X0 = rnd.multivariate_normal([-2, 0], [[1, 0], [0, 1]], N0) X1 = rnd.multivariate_normal([+2, 0], [[1, 0], [0, 1]], N1) X = np.vstack((X0, X1)) y = np.hstack((np.ones((N0,)), 2*np.ones((N1,)))) # + # Divergence alpha = 1 # Generate target data M = 100 M0 = 50 M1 = M - M0 Z0 = rnd.multivariate_normal(alpha*np.array([-1, 2]), alpha*np.array([[3, 2], [2, 4]]), M0) Z1 = rnd.multivariate_normal(alpha*np.array([+2, 1]), alpha*np.array([[3, 2], [2, 4]]), M1) Z = np.vstack((Z0, Z1)) u = np.hstack((np.ones((M0,)), 2*np.ones((M1,)))) # + # Train TCPR C = TargetContrastivePessimisticClassifier(loss='qda', l2=1e-0) C.fit(X, y, Z) Y, labels = one_hot(y) eta = C.discriminant_parameters(X, Y) theta = C.get_params() # + # Visualize setting fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(10,5)) ax[0].set_xlim(xl) ax[0].set_ylim(yl) ax[0].scatter(X0[:, 0], X0[:, 1], c='r', marker='o') ax[0].scatter(X1[:, 0], X1[:, 1], c='b', marker='x') ax[1].scatter(Z0[:, 0], Z0[:, 1], c='r', marker='o') ax[1].scatter(Z1[:, 0], Z1[:, 1], c='b', marker='x') ax[0].set_ylabel("$$x_2$$", fontsize=fS+2) ax[0].set_xlabel("$$x_1$$", fontsize=fS+2) ax[1].set_xlabel("$$x_1$$", fontsize=fS+2) fig.savefig("viz/da_problem-setting_alpha" + str(alpha) + ".png", dpi=300, bbox_inches='tight') # + # Show source QDA fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(10,5)) ax[0].set_xlim(xl) ax[0].set_ylim(yl) ax[0].scatter(X0[:, 0], X0[:, 1], c='r', marker='o') ax[0].scatter(X1[:, 0], X1[:, 1], c='b', marker='x') ax[1].scatter(Z0[:, 0], Z0[:, 1], c='r', marker='o') ax[1].scatter(Z1[:, 0], Z1[:, 1], c='b', marker='x') plotqda(eta, ax=ax[0], colors='g') ax[0].set_ylabel("$$x_2$$", fontsize=fS+2) ax[0].set_xlabel("$$x_1$$", fontsize=fS+2) ax[1].set_xlabel("$$x_1$$", fontsize=fS+2) # fig.savefig("viz/da_qda_alpha" + str(alpha) + ".png", dpi=100, bbox_inches='tight') # + # Show source QDA fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(10,5)) ax[0].set_xlim(xl) ax[0].set_ylim(yl) ax[0].scatter(X0[:, 0], X0[:, 1], c='r', marker='o') ax[0].scatter(X1[:, 0], X1[:, 1], c='b', marker='x') ax[1].scatter(Z0[:, 0], Z0[:, 1], c='r', marker='o') ax[1].scatter(Z1[:, 0], Z1[:, 1], c='b', marker='x') plotqda(eta, ax=ax[0], colors='k') plotqda(eta, ax=ax[1], colors='k') ax[0].set_ylabel("$x_2$", fontsize=fS+2) ax[0].set_xlabel("$x_1$", fontsize=fS+2) ax[1].set_xlabel("$x_1$", fontsize=fS+2) fig.savefig("viz/example_target-risk-of-source-classifier.png", dpi=100, bbox_inches='tight') fig.savefig("viz/example_target-risk-of-source-classifier.eps", dpi=100, bbox_inches='tight') # + # Show source QDA fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(10,5)) ax[0].set_xlim(xl) ax[0].set_ylim(yl) ax[0].scatter(X0[:, 0], X0[:, 1], c='r', marker='o') ax[0].scatter(X1[:, 0], X1[:, 1], c='b', marker='x') ax[1].scatter(Z0[:, 0], Z0[:, 1], c='k', marker='o') ax[1].scatter(Z1[:, 0], Z1[:, 1], c='k', marker='x') plotqda(eta, ax=ax[0], colors='k') plotqda(eta, ax=ax[1], colors='k') ax[0].set_ylabel("$x_2$", fontsize=fS+2) ax[0].set_xlabel("$x_1$", fontsize=fS+2) ax[1].set_xlabel("$x_1$", fontsize=fS+2) fig.savefig("viz/example_target-risk-of-source-classifier-black.png", dpi=100, bbox_inches='tight') fig.savefig("viz/example_target-risk-of-source-classifier-black.eps", dpi=100, bbox_inches='tight') # + # Visualize QDA decision boundary fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(10,5)) ax[0].set_xlim(xl) ax[0].set_ylim(yl) ax[0].scatter(Z0[:, 0], Z0[:, 1], c='r', marker='o') ax[0].scatter(Z1[:, 0], Z1[:, 1], c='b', marker='x') ax[1].scatter(Z0[:, 0], Z0[:, 1], c='r', marker='o') ax[1].scatter(Z1[:, 0], Z1[:, 1], c='b', marker='x') plotqda(eta, ax=ax[0], colors='k') plotqda(theta, ax=ax[1], colors='k') ax[0].set_ylabel("$x_2$", fontsize=fS+4) ax[0].set_xlabel("$x_1$", fontsize=fS+4) ax[1].set_xlabel("$x_1$", fontsize=fS+4) fig.savefig("viz/example_classifiers-on-target-data.png", dpi=100, bbox_inches='tight') fig.savefig("viz/example_classifiers-on-target-data.eps", dpi=100, bbox_inches='tight') # + # Visualize QDA decision boundary fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(10,5)) ax[0].set_xlim(xl) ax[0].set_ylim(yl) ax[0].scatter(Z0[:, 0], Z0[:, 1], c='k', marker='o') ax[0].scatter(Z1[:, 0], Z1[:, 1], c='k', marker='x') ax[1].scatter(Z0[:, 0], Z0[:, 1], c='k', marker='o') ax[1].scatter(Z1[:, 0], Z1[:, 1], c='k', marker='x') plotqda(eta, ax=ax[0], colors='k') plotqda(theta, ax=ax[1], colors='k') ax[0].set_ylabel("$x_2$", fontsize=fS+2) ax[0].set_xlabel("$x_1$", fontsize=fS+2) ax[1].set_xlabel("$x_1$", fontsize=fS+2) fig.savefig("viz/example_classifiers-on-target-data-black.png", dpi=100, bbox_inches='tight') fig.savefig("viz/example_classifiers-on-target-data-black.eps", dpi=100, bbox_inches='tight') # + # Show source QDA fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(10,5)) ax[0].set_xlim(xl) ax[0].set_ylim(yl) ax[0].scatter(X0[:, 0], X0[:, 1], c='r', marker='o') ax[0].scatter(X1[:, 0], X1[:, 1], c='b', marker='x') ax[1].scatter(Z0[:, 0], Z0[:, 1], c='r', marker='o') ax[1].scatter(Z1[:, 0], Z1[:, 1], c='b', marker='x') plotqda(eta, ax=ax[0], colors='k') plotqda(eta, ax=ax[1], colors='k') ax[0].set_ylabel("$x_2$", fontsize=fS+4) ax[0].set_xlabel("$x_1$", fontsize=fS+4) ax[1].set_xlabel("$x_1$", fontsize=fS+4) fig.savefig("viz/example_target-risk-of-source-classifier.png", dpi=100, bbox_inches='tight') fig.savefig("viz/example_target-risk-of-source-classifier.eps", dpi=100, bbox_inches='tight') # -
examples/bivarGaussians.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "bba802c376893d7e912e9a3376849398", "grade": false, "grade_id": "cell-37b1bbf6f43609e8", "locked": true, "schema_version": 3, "solution": false, "task": false} # ## Module 3 # # In this assignment, you will implement some functions related to strings, lists, sets and tuples. Each function has # been defined for you, but without the code. See the docstring in each function for instructions on what the function # is supposed to do and how to write the code. It should be clear enough. In some cases, we have provided hints to help # you get started. # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "b0746b7ee0e53995bb16dd7c9d76ab0e", "grade": true, "grade_id": "init_test", "locked": true, "points": 0, "schema_version": 3, "solution": false, "task": false} ########################################################### ### EXECUTE THIS CELL BEFORE YOU TO TEST YOUR SOLUTIONS ### ########################################################### import unittest from nose.tools import assert_equal, assert_true import nose.tools # + deletable=false name="multiply" nbgrader={"cell_type": "code", "checksum": "e0e7763f8a85e95b4edf1ee41f6f1bac", "grade": false, "grade_id": "concatenate", "locked": false, "schema_version": 3, "solution": true, "task": false} def concatenate(strings): """ Concatenates the given list of strings into a single string. Returns the single string. If the given list is empty, returns an empty string. For example: - If we call concatenate(["a","b","c"]), we'll get "abc" in return - If we call concatenate([]), we'll get "" in return Hint(s): - Remember, you can create a single string from a list of multiple strings by using the join() function """ # your code here # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "1a7ab3518b11e9ba99da4761923f0583", "grade": true, "grade_id": "test_concatenate", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false} ########################## ### TEST YOUR SOLUTION ### ########################## lst = ["a","b","c"] assert_equal("abc",concatenate(lst)) lst = [] assert_equal("",concatenate(lst)) print("Success!") # + deletable=false nbgrader={"cell_type": "code", "checksum": "0870b29f2016f1e007592b0c8966538f", "grade": false, "grade_id": "all_but_last", "locked": false, "schema_version": 3, "solution": true, "task": false} def all_but_last(seq): """ Returns a new list containing all but the last element in the given list. If the list is empty, returns None. For example: - If we call all_but_last([1,2,3,4,5]), we'll get [1,2,3,4] in return - If we call all_but_last(["a","d",1,3,4,None]), we'll get ["a","d",1,3,4] in return - If we call all_but_last([]), we'll get None in return """ # your code here # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "a40b1a246dcabfc4c69cdb69c9ed7f23", "grade": true, "grade_id": "test_all_but_last", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false} ########################## ### TEST YOUR SOLUTION ### ########################## lst = [] assert_equal(None,all_but_last(lst)) lst = [1,2,3,4,5] nose.tools.assert_list_equal([1,2,3,4],all_but_last(lst)) lst = ["a","d",1,3,4,None] nose.tools.assert_list_equal(["a","d",1,3,4],all_but_last(lst)) print("Success!") # + deletable=false nbgrader={"cell_type": "code", "checksum": "91077995ab1c6f14efa17a9eec9675c2", "grade": false, "grade_id": "remove_duplicates", "locked": false, "schema_version": 3, "solution": true, "task": false} def remove_duplicates(lst): """ Returns the given list without duplicates. The order of the returned list doesn't matter. For example: - If we call remove_duplicates([1,2,1,3,4]), we'll get [1,2,3,4] in return - If we call remove_duplicates([]), we'll get [] in return Hint(s): - Remember, you can create a set from a string, which will remove the duplicate elements """ # your code here # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "8f757ddb4fc4360551d2b19e73aed450", "grade": true, "grade_id": "test_remove_duplicates", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false} ########################## ### TEST YOUR SOLUTION ### ########################## lst = [1,3,4,3,4,5,2] nose.tools.assert_count_equal([1,3,4,5,2],remove_duplicates(lst)) lst = [] nose.tools.assert_count_equal([],remove_duplicates(lst)) print("Success!") # + deletable=false nbgrader={"cell_type": "code", "checksum": "255701202f3074ab3e4932a5da05e2c1", "grade": false, "grade_id": "reverse_word", "locked": false, "schema_version": 3, "solution": true, "task": false} def reverse_word(word): """ Reverses the order of the characters in the given word. For example: - If we call reverse_word("abcde"), we'll get "edcba" in return - If we call reverse_word("a b c d e"), we'll get "e d c b a" in return - If we call reverse_word("a b"), we'll get "b a" in return - If we call reverse_word(""), we'll get "" in return Hint(s): - You can iterate over a word in reverse and access each character """ # your code here # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "625c0b1d6030edea8e48afa8e65abf38", "grade": true, "grade_id": "test_reverse_word", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false} ########################## ### TEST YOUR SOLUTION ### ########################## word = "abcdefg" assert_equal("gfedcba",reverse_word(word)) word = "a b c d e f g" assert_equal("g f e d c b a",reverse_word(word)) word = "a b" assert_equal("b a",reverse_word(word)) word = "" assert_equal("",reverse_word(word)) print("Success!") # + deletable=false nbgrader={"cell_type": "code", "checksum": "3a99669c674b556d187fe56432dfc572", "grade": false, "grade_id": "divisors", "locked": false, "schema_version": 3, "solution": true, "task": false} def divisors(n): """ Returns a list with all divisors of the given number n. As a reminder, a divisor is a number that evenly divides another number. The returned list should include 1 and the given number n itself. The order of the returned list doesn't matter. For example: - If we call divisors(10), we'll get [1,2,5,10] in return - If we call divisors(1), we'll get [1] in return """ # your code here # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "89980aca8c0d977ab40e986b752ceeeb", "grade": true, "grade_id": "test_divisors", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false} ########################## ### TEST YOUR SOLUTION ### ########################## number = 10 nose.tools.assert_count_equal([1,2,5,10],divisors(number)) number = 1 nose.tools.assert_count_equal([1],divisors(number)) number = 7 nose.tools.assert_count_equal([1,7],divisors(number)) print("Success!") # + deletable=false nbgrader={"cell_type": "code", "checksum": "748cdfabc5cd8e9327cb62dc4eeadd49", "grade": false, "grade_id": "capitalize_or_join", "locked": false, "schema_version": 3, "solution": true, "task": false} def capitalize_or_join_words(sentence): """ If the given sentence starts with *, capitalizes the first and last letters of each word in the sentence, and returns the sentence without *. Else, joins all the words in the given sentence, separating them with a comma, and returns the result. For example: - If we call capitalize_or_join_words("*i love python"), we'll get "I LovE PythoN" in return. - If we call capitalize_or_join_words("i love python"), we'll get "i,love,python" in return. - If we call capitalize_or_join_words("i love python "), we'll get "i,love,python" in return. Hint(s): - The startswith() function checks whether a string starts with a particualr character - The capitalize() function capitalizes the first letter of a string - The upper() function converts all lowercase characters in a string to uppercase - The join() function creates a single string from a list of multiple strings """ # your code here # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "92bd2774d292a5700f0d6980355dd50c", "grade": true, "grade_id": "test_capitalize_or_join", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false} ########################## ### TEST YOUR SOLUTION ### ########################## string = "*i love python" assert_equal("I LovE PythoN",capitalize_or_join_words(string)) string = "i love python" assert_equal("i,love,python",capitalize_or_join_words(string)) string = "i love python " assert_equal("i,love,python",capitalize_or_join_words(string)) print("Success!") # + deletable=false nbgrader={"cell_type": "code", "checksum": "b934daf8bd77c0cff4f44dffc20315e9", "grade": false, "grade_id": "move_zero", "locked": false, "schema_version": 3, "solution": true, "task": false} def move_zero(lst): """ Given a list of integers, moves all non-zero numbers to the beginning of the list and moves all zeros to the end of the list. This function returns nothing and changes the given list itself. For example: - After calling move_zero([0,1,0,2,0,3,0,4]), the given list should be [1,2,3,4,0,0,0,0] and the function returns nothing - After calling move_zero([0,1,2,0,1]), the given list should be [1,2,1,0,0] and the function returns nothing - After calling move_zero([1,2,3,4,5,6,7,8]), the given list should be [1,2,3,4,5,6,7,8] and the function returns nothing - After calling move_zero([]), the given list should be [] and the function returns nothing """ # your code here # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "f608eba28d0aa4f01949e79aadcc161d", "grade": true, "grade_id": "test_move_zero", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false} ########################## ### TEST YOUR SOLUTION ### ########################## lst = [0,1,0,2,0,3,0,4] assert_equal(None,move_zero(lst)) nose.tools.assert_list_equal([1,2,3,4,0,0,0,0],lst) lst = [] move_zero(lst) nose.tools.assert_list_equal([],lst) lst = [0,0,0,0,0,0,0,0,0] move_zero(lst) nose.tools.assert_list_equal([0,0,0,0,0,0,0,0,0],lst) lst = [1,2,3,4,5,6,7,8] move_zero(lst) nose.tools.assert_list_equal([1,2,3,4,5,6,7,8],lst) print("Success!") # + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "f38ff9888bf35eb5dbdd3b0a4ded5a70", "grade": true, "grade_id": "main", "locked": true, "points": 0, "schema_version": 3, "solution": false, "task": false} def main(): """ Calls all the functions above to see whether they've been implemented correctly. """ # test concatenate print("test concatenate") word = concatenate(["b", "e", "a", "t", "l", "e", "s"]) print(word == "beatles") print("=" * 50) # test all_but_last print("test all_but_last") seq = all_but_last(["john", "paul", "george", "ringo", "tommy"]) print(seq == ["john", "paul", "george", "ringo"]) print("=" * 50) # test remove_duplicates print("test remove_duplicates") res = remove_duplicates([1, 3, 4, 2, 1]) print(res == [1, 3, 4, 2]) print("=" * 50) # test reverse_word print("test reverse_word") res = reverse_word("alphabet") print(res == "tebahpla") print("=" * 50) # test divisors print("test divisors") res = divisors(120) print(set(res) == set([1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120])) print("=" * 50) # test capitalize_or_join_words print("test capitalize_or_join_words") print("Result for String Start With *: ") # Should return "I LovE CodinG AnD I'M HavinG FuN" res = capitalize_or_join_words("*i love coding and i'm having fun") print(res == "I LovE CodinG AnD I'M HavinG FuN") print("Result for Other String: ") # Should print "I,love,coding,and,I'm,having,fun" res = capitalize_or_join_words("I love coding and I'm having fun") print(res == "I,love,coding,and,I'm,having,fun") print("=" * 50) # test move_zero print("test move_zero") lst = [0, 1, 0, 2, 0, 3, 4, 0] print("Before move,the list looks like\n", lst) move_zero(lst) print("After move,the list looks like\n", lst) print("=" * 50) #This will automatically run the main function in your program #Don't change this if __name__ == '__main__': main()
release/module 3/module3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # 이미지 자르기 def crop(src_dir, dst_dir, start_idx, end_idx, x, y, w, h): for i in range(start_idx, end_idx+1): src_path = src_dir + str(i) + '.jpg' dst_path = dst_dir + str(i) + '.jpg' src_img = Image.open(src_path) dst_img = src_img.crop((x, y, x + w, y + h)) dst_img.save(dst_path, quality=90) def zoom_out(src_dir, dst_dir, start_idx, end_idx, ratio): for i in range(start_idx, end_idx+1): src_path = src_dir + str(i) + '.jpg' dst_path = dst_dir + str(i) + '.jpg' src_img = Image.open(src_path) dst_img = Image.new('RGB', (256, 256)) dst_img.paste(src_img, (0, 0, 256, 256)) w = int(256*ratio) h = int(256*ratio) x = (256 - w) / 2 y = (256 - h) / 2 src_img = src_img.resize((w, h), Image.ANTIALIAS) dst_img.paste(src_img, (x, y, x+w, y+h)) dst_img.save(dst_path, quality=90) # + src_dir = './warehouse/cards_ab/train_a/' dst_dir = './warehouse/cards_ab/train_a_s/' zoom_out(src_dir, dst_dir, 1, 13, 0.7) # + src_dir = './warehouse/cards_ab/train_/' dst_dir = './warehouse/cards_ab/train_a/' crop(src_dir, dst_dir, 1, 13, 0, 0, 256, 256) src_dir = './warehouse/cards_ab/train_/' dst_dir = './warehouse/cards_ab/train_b/' crop(src_dir, dst_dir, 1, 13, 256, 0, 256, 256) # - def combine(src_dir1, src_dir2, dst_dir, start_idx, end_idx): for i in range(start_idx, end_idx+1): src_path1 = src_dir1 + str(i) + '.jpg' src_path2 = src_dir2 + str(i) + '.jpg' dst_path = dst_dir + str(i) + '.jpg' src_img1 = Image.open(src_path1) src_img2 = Image.open(src_path2) dst_img = Image.new('RGB', (512, 256)) dst_img.paste(src_img1, (0, 0, 256, 256)) dst_img.paste(src_img2, (256, 0, 512, 256)) dst_img.save(dst_path, quality=90) # + src_dir1 = './warehouse/cards_ab/train_a_s/' src_dir2 = './warehouse/cards_ab/train_b_s/' dst_dir = './warehouse/cards_ab/train/' combine(src_dir1, src_dir2, dst_dir, 1, 13) # + from PIL import Image for idx in range(1, 14): str_a = './cards/raw/A/' + str(idx) + '.jpg' str_b = './cards/raw/B/' + str(idx) + '.jpg' str_c = './cards/train/' + str(idx) + '.jpg' im_a = Image.open(str_a) im_b = Image.open(str_b) im_c = Image.new('RGB', (512, 256)) im_a_resize = im_a.resize((256, 256), Image.ANTIALIAS) im_b_resize = im_b.resize((256, 256), Image.ANTIALIAS) im_c.paste(im_a_resize, (0, 0, 256, 256)) im_c.paste(im_b_resize, (256, 0, 512, 256)) im_c.save(str_c, quality=90) # - # # 합치기 # + img_id_list = ['IMG_6177', 'IMG_6178', 'IMG_6180', 'IMG_6181', 'IMG_6182', 'IMG_6183', 'IMG_6184', 'IMG_6185', 'IMG_6186', 'IMG_6187', 'IMG_6188'] img_frame_list = [875, 133, 636, 596, 727, 810, 2032, 802, 635, 951, 701] for i in range(len(img_id_list)): src_dir_1 = './warehouse/' + img_id_list[i] + '/' src_dir_2 = './warehouse/' + img_id_list[i] + '_out/' dst_dir = './warehouse/' + img_id_list[i] + '_comb/' print(img_id_list[i] + ' ...') for j in range(img_frame_list[i]+1): src_img_1 = Image.open(src_dir_1 + str(j) + '.jpg') src_img_2 = Image.open(src_dir_2 + str(j) + '.jpg') dst_img = Image.new('RGB', (512, 256)) dst_img.paste(src_img_1, (0, 0, 256, 256)) dst_img.paste(src_img_2, (256, 0, 512, 256)) dst_img.save(dst_dir + str(j) + '.jpg', quality=90) # + from PIL import Image for idx in range(0, 415): str_a = './warehouse/frame_in_v1/' + str(idx) + '.jpg' str_b = './warehouse/frame_out_v1/' + str(idx) + '.jpg' str_c = './warehouse/frame_v1/' + str(idx) + '.jpg' im_a = Image.open(str_a) im_b = Image.open(str_b) im_c = Image.new('RGB', (512, 256)) im_a_resize = im_a.resize((256, 256), Image.ANTIALIAS) im_b_resize = im_b.resize((256, 256), Image.ANTIALIAS) im_c.paste(im_a_resize, (0, 0, 256, 256)) im_c.paste(im_b_resize, (256, 0, 512, 256)) im_c.save(str_c, quality=90) # - # ### 회전 # + def pair_random_transform(x1, x2, rotation_range = 0): if rotation_range: theta = np.random.uniform(-self.rotation_range, self.rotation_range) dst_img = src_img.rotate(90) # + # 회전 # 0~414 max_idx = 414 src_dir = './warehouse/frame_in_v1_org/' dst_dir = './warehouse/frame_in_v1/' for idx in range(max_idx+1): src_path = src_dir + str(idx) + '.jpg' dst_path = dst_dir + str(idx) + '.jpg' src_img = Image.open(src_path) dst_img = src_img.rotate(90) dst_img.save(dst_path, quality=90) # - # # 동영상 각 프레임을 이미지로 저장하기 # + import cv2 import numpy as np import os def frames_to_video(inputpath, outputpath, fps, start_idx, end_idx): image_array = [] for i in range(start_idx, end_idx+1): filename= str(i) + '.jpg' tt = inputpath + filename img = cv2.imread(inputpath + filename) size = (img.shape[1], img.shape[0]) img = cv2.resize(img,size) image_array.append(img) fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X') out = cv2.VideoWriter(outputpath,fourcc, fps, size) for i in range(len(image_array)): out.write(image_array[i]) out.release() def frames_from_video(src_path, dst_dir): vidcap = cv2.VideoCapture(src_path) success,image = vidcap.read() count = 0 success = True while success: success, image = vidcap.read() #print ('Read a new frame: ', success) cv2.imwrite( dst_dir + "%d.jpg" % count, image) # save frame as JPEG file count += 1 def frames_to_images(src_dir, dst_dir, start_idx, end_idx): for i in range(start_idx, end_idx+1): src_path = src_dir + str(i) + '.jpg' dst_path = dst_dir + str(i) + '.jpg' src_img = Image.open(src_path) dst_img = src_img.crop((420, 0, 1500, 1080)) dst_img = dst_img.resize((256, 256), Image.ANTIALIAS) dst_img.save(dst_path, quality=90) # + img_id_list = ['IMG_6177', 'IMG_6178', 'IMG_6180', 'IMG_6181', 'IMG_6182', 'IMG_6183', 'IMG_6184', 'IMG_6185', 'IMG_6186', 'IMG_6187', 'IMG_6188'] img_frame_list = [875, 133, 636, 596, 727, 810, 2032, 802, 635, 951, 701] for i in range(len(img_id_list)): src_dir = './warehouse/' + img_id_list[i] + '_comb/' dst_path = './warehouse/' + img_id_list[i] + '_out.mp4' start_idx = 0 end_idx = img_frame_list[i] print(src_dir + ' > ' + dst_path) frames_to_video(src_dir, dst_path, 30, start_idx, end_idx) # - # # 프레임을 이미지화 시키기 # + src_path = './warehouse/IMG_6185.MOV' dst_dir = './warehouse/IMG_6185_frame/' frames_from_video(src_path, dst_dir) # + img_id_list = ['IMG_6177', 'IMG_6178', 'IMG_6180', 'IMG_6181', 'IMG_6182', 'IMG_6183', 'IMG_6184', 'IMG_6185', 'IMG_6186', 'IMG_6187', 'IMG_6188'] for img_id in img_id_list: print(img_id) src_path = './warehouse/' + img_id + '.MOV' dst_dir = './warehouse/' + img_id + '_frame/' frames_from_video(src_path, dst_dir) # + img_id_list = ['IMG_6177', 'IMG_6178', 'IMG_6180', 'IMG_6181', 'IMG_6182', 'IMG_6183', 'IMG_6184', 'IMG_6185', 'IMG_6186', 'IMG_6187', 'IMG_6188'] img_frame_list = [875, 133, 636, 596, 727, 810, 2032, 802, 635, 951, 701] for i in range(len(img_id_list)): src_dir = './warehouse/' + img_id_list[i] + '_frame/' dst_dir = './warehouse/' + img_id_list[i] + '/' frames_to_images(src_dir, dst_dir, 0, img_frame_list[i]) # - inputpath = 'warehouse/frame_out_v1/' outpath = 'warehouse/frame_out_v1.mp4' fps = 30 frames_to_video(inputpath,outpath,fps) def frames_to_video(inputpath, outputpath, fps, start_idx, end_idx): # + from PIL import Image as pil_image import scipy.ndimage as ndi def apply_transform(x, transform_matrix, channel_axis=0, fill_mode='nearest', cval=0.): """Apply the image transformation specified by a matrix. # Arguments x: 2D numpy array, single image. transform_matrix: Numpy array specifying the geometric transformation. channel_axis: Index of axis for channels in the input tensor. fill_mode: Points outside the boundaries of the input are filled according to the given mode (one of `{'constant', 'nearest', 'reflect', 'wrap'}`). cval: Value used for points outside the boundaries of the input if `mode='constant'`. # Returns The transformed version of the input. """ x = np.rollaxis(x, channel_axis, 0) final_affine_matrix = transform_matrix[:2, :2] final_offset = transform_matrix[:2, 2] channel_images = [ndi.interpolation.affine_transform( x_channel, final_affine_matrix, final_offset, order=0, mode=fill_mode, cval=cval) for x_channel in x] x = np.stack(channel_images, axis=0) x = np.rollaxis(x, 0, channel_axis + 1) return x def pair_random_transform(x1, x2, rotation_range = 0.0, width_shift_range=0., height_shift_range=0., shear_range=0., zoom_range=0., horizontal_flip=False, vertical_flip=False): """Randomly augment a single image tensor. # Arguments x: 3D tensor, single image. # Returns A randomly transformed version of the input (same shape). """ # x is a single image, so it doesn't have image number at index 0 img_row_axis = 0 img_col_axis = 1 img_channel_axis = 2 if np.isscalar(zoom_range): zoom_range = [1 - zoom_range, 1 + zoom_range] elif len(zoom_range) == 2: zoom_range = [zoom_range[0], zoom_range[1]] else: raise ValueError('zoom_range should be a float or ' 'a tuple or list of two floats. ' 'Received arg: ', zoom_range) # use composition of homographies # to generate final transform that needs to be applied if rotation_range: theta = np.pi / 180 * np.random.uniform(-rotation_range, rotation_range) else: theta = 0 if height_shift_range: tx = np.random.uniform(-height_shift_range, height_shift_range) * x1.shape[img_row_axis] else: tx = 0 if width_shift_range: ty = np.random.uniform(-width_shift_range, width_shift_range) * x1.shape[img_col_axis] else: ty = 0 if shear_range: shear = np.random.uniform(-shear_range, shear_range) else: shear = 0 if zoom_range[0] == 1 and zoom_range[1] == 1: zx, zy = 1, 1 else: # zx, zy = np.random.uniform(zoom_range[0], zoom_range[1], 2) zx = np.random.uniform(zoom_range[0], zoom_range[1]) zy = zx print (shear, zx, zy) transform_matrix = None if theta != 0: rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]]) transform_matrix = rotation_matrix if tx != 0 or ty != 0: shift_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]) transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix) if shear != 0: shear_matrix = np.array([[1, -np.sin(shear), 0], [0, np.cos(shear), 0], [0, 0, 1]]) transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix) if zx != 1 or zy != 1: zoom_matrix = np.array([[zx, 0, 0], [0, zy, 0], [0, 0, 1]]) transform_matrix = zoom_matrix if transform_matrix is None else np.dot(transform_matrix, zoom_matrix) if transform_matrix is not None: h, w = x1.shape[img_row_axis], x1.shape[img_col_axis] transform_matrix = transform_matrix_offset_center(transform_matrix, h, w) x1 = apply_transform(x1, transform_matrix, img_channel_axis, fill_mode = 'reflect') x2 = apply_transform(x2, transform_matrix, img_channel_axis, fill_mode = 'reflect') if horizontal_flip: if np.random.random() < 0.5: x1 = flip_axis(x1, img_col_axis) x2 = flip_axis(x2, img_col_axis) if vertical_flip: if np.random.random() < 0.5: x1 = flip_axis(x1, img_row_axis) x2 = flip_axis(x2, img_row_axis) return x1, x2 def load_img(path, grayscale=False, target_size=None): """Loads an image into PIL format. # Arguments path: Path to image file grayscale: Boolean, whether to load the image as grayscale. target_size: Either `None` (default to original size) or tuple of ints `(img_height, img_width)`. # Returns A PIL Image instance. # Raises ImportError: if PIL is not available. """ if pil_image is None: raise ImportError('Could not import PIL.Image. ' 'The use of `array_to_img` requires PIL.') img = pil_image.open(path) if grayscale: if img.mode != 'L': img = img.convert('L') else: if img.mode != 'RGB': img = img.convert('RGB') if target_size: hw_tuple = (target_size[1], target_size[0]) if img.size != hw_tuple: img = img.resize(hw_tuple) return img def img_to_array(img): # Numpy array x has format (height, width, channel) # or (channel, height, width) # but original PIL image has format (width, height, channel) x = np.asarray(img, dtype=np.float32) return x def array_to_img(x, data_format=None, scale=True): x = np.asarray(x, dtype=np.float32) if scale: x = x + max(-np.min(x), 0) x_max = np.max(x) if x_max != 0: x /= x_max x *= 255 if x.shape[2] == 3: # RGB return pil_image.fromarray(x.astype('uint8'), 'RGB') elif x.shape[2] == 1: # grayscale return pil_image.fromarray(x[:, :, 0].astype('uint8'), 'L') else: raise ValueError('Unsupported channel number: ', x.shape[2]) def transform_matrix_offset_center(matrix, x, y): o_x = float(x) / 2 + 0.5 o_y = float(y) / 2 + 0.5 offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]]) reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]]) transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix) return transform_matrix def flip_axis(x, axis): x = np.asarray(x).swapaxes(axis, 0) x = x[::-1, ...] x = x.swapaxes(0, axis) return x # + count = 1 dst_idx = 0 mul_count = 5 """ param_rotation_range = 180.0 param_width_shift_range=50. param_height_shift_range=50. param_shear_range=1. param_zoom_range=10. param_horizontal_flip=False param_vertical_flip=False """ param_rotation_range = 180. param_width_shift_range=0.2 param_height_shift_range=0.2 param_shear_range=0.1 param_zoom_range=0.1 param_horizontal_flip=False param_vertical_flip=False src_dir1 = './warehouse/cards_a/' src_dir2 = './warehouse/cards_b/' dst_dir1 = './warehouse/cards_a_t/' dst_dir2 = './warehouse/cards_b_t/' for i in range(count): src_path1 = src_dir1 + str(i) + '.jpg' src_path2 = src_dir2 + str(i) + '.jpg' src_img1 = load_img(src_path1) src_img2 = load_img(src_path2) src_x1 = img_to_array(src_img1) src_x2 = img_to_array(src_img2) for j in range(mul_count): dst_x1, dst_x2 = pair_random_transform(src_x1, src_x2, rotation_range = param_rotation_range, width_shift_range = param_width_shift_range, height_shift_range = param_height_shift_range, shear_range = param_shear_range, zoom_range = param_zoom_range, horizontal_flip = param_horizontal_flip, vertical_flip = param_vertical_flip) dst_img1 = array_to_img(dst_x1) dst_img2 = array_to_img(dst_x2) dst_path1 = dst_dir1 + str(dst_idx) + '.jpg' dst_path2 = dst_dir2 + str(dst_idx) + '.jpg' dst_img1.save(dst_path1, quality=90) dst_img2.save(dst_path2, quality=90) dst_idx = dst_idx + 1 # -
_writing/imgtool.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import torch import torch.nn as nn import sys def wSum(X,W): h = torch.from_numpy(X) z = torch.matmul(W,h) return z def activate(x): return 1/(1+torch.exp(-x)) def forwardStep(X,W_list): h = torch.from_numpy(X) for W in W_list: z = torch.matmul(W,h) h = activate(z) return h def updateParams(W_list,dW_list,lr): with torch.no_grad(): for i in range(len(W_list)): W_list[i] -= lr*dW_list[i] return W_list def trainNN_sgd(X,y,W_list,loss_fn,lr=0.0001,nepochs=100): for epoch in range(nepochs): avgLoss = [] for i in range(len(y)): Xin = X[i,:] yTrue = y[i] y_hat = forwardStep(Xin,W_list) loss = loss_fn(y_hat,torch.tensor(yTrue,dtype=torch.double)) loss.backward() avgLoss.append(loss.item()) sys.stdout.flush() dW_list = [] for j in range(len(W_list)): dW_list.append(W_list[j].grad.data) W_list = updateParams(W_list,dW_list,lr) for j in range(len(W_list)): W_list[j].grad.data.zero_() print("Loss after epoch=%d: %f" %(epoch,np.mean(np.array(avgLoss)))) return W_list def trainNN_batch(X,y,W_list,loss_fn,lr=0.0001,nepochs=100): n = len(y) for epoch in range(nepochs): loss = 0 for i in range(n): Xin = X[i,:] yTrue = y[i] y_hat = forwardStep(Xin,W_list) loss += loss_fn(y_hat,torch.tensor(yTrue,dtype=torch.double)) loss = loss/n loss.backward() sys.stdout.flush() dW_list = [] for j in range(len(W_list)): dW_list.append(W_list[j].grad.data) W_list = updateParams(W_list,dW_list,lr) for j in range(len(W_list)): W_list[j].grad.data.zero_() print("Loss after epoch=%d: %f" %(epoch,loss)) return W_list def trainNN_minibatch(X,y,W_list,loss_fn,lr=0.0001,nepochs=100,batchSize=16): n = len(y) numBatches = n//batchSize for epoch in range(nepochs): for batch in range(numBatches): X_batch = X[batch*batchSize:(batch+1)*batchSize,:] y_batch = y[batch*batchSize:(batch+1)*batchSize] loss = 0 for i in range(batchSize): Xin = X_batch[i,:] yTrue = y_batch[i] y_hat = forwardStep(Xin,W_list) loss += loss_fn(y_hat,torch.tensor(yTrue,dtype=torch.double)) loss = loss/batchSize loss.backward() sys.stdout.flush() dW_list = [] for j in range(len(W_list)): dW_list.append(W_list[j].grad.data) W_list = updateParams(W_list,dW_list,lr) for j in range(len(W_list)): W_list[j].grad.data.zero_() print("Loss after epoch=%d: %f" %(epoch,loss/numBatches)) return W_list # + inputDim = 10 n = 1000 X = np.random.rand(n,inputDim) y = np.random.randint(0,2,n) W1 = torch.tensor(np.random.uniform(0,1,(2,inputDim)),requires_grad=True) W2 = torch.tensor(np.random.uniform(0,1,(3,2)),requires_grad=True) W3 = torch.tensor(np.random.uniform(0,1,3),requires_grad=True) W_list = [] W_list.append(W1) W_list.append(W2) W_list.append(W3) loss_fn = nn.BCELoss() #W_list = trainNN_sgd(X,y,W_list,loss_fn,lr=0.0001,nepochs=100) #W_list = trainNN_batch(X,y,W_list,loss_fn,lr=0.0001,nepochs=100) W_list = trainNN_minibatch(X,y,W_list,loss_fn,lr=0.0001,nepochs=100) # - inputDim = 10 n = 1000 X = np.random.rand(n,inputDim) y = np.random.randint(0,2,n) X.shape y.shape np.unique(y) W = torch.tensor(np.random.uniform(0,1,inputDim),requires_grad=True) z = wSum(X[0,:],W) print(z) # + inputDim = 10 n = 1000 X = np.random.rand(n,inputDim) y = np.random.randint(0,2,n) W1 = torch.tensor(np.random.uniform(0,1,(2,inputDim)),requires_grad=True) W2 = torch.tensor(np.random.uniform(0,1,(3,2)),requires_grad=True) W3 = torch.tensor(np.random.uniform(0,1,3),requires_grad=True) W_list = [] W_list.append(W1) W_list.append(W2) W_list.append(W3) z = forwardStep(X[0,:],W_list) print(z) # - m = nn.Sigmoid() loss_fun = nn.BCELoss() lr = 0.0001 x = torch.randn(1) y = torch.randint(0,2,(1,),dtype=torch.float) w = torch.randn(1,requires_grad=True) nIter = 100 for i in range(nIter): y_hat = m(w*x) loss = loss_fun(y_hat,y) loss.backward() dw = w.grad.data with torch.no_grad(): w -= lr*dw w.grad.data.zero_() print(loss.item()) import numpy as np import torch import torch.nn as nn from torch.utils.data import TensorDataset,DataLoader # + inputDim = 10 n = 1000 X = np.random.rand(n,inputDim) y = np.random.randint(0,2,n) tensor_x = torch.Tensor(X) tensor_y = torch.Tensor(y) Xy = TensorDataset(tensor_x,tensor_y) Xy_loader = DataLoader(Xy,batch_size=16,shuffle=True,drop_last=True) # - model = nn.Sequential( nn.Linear(inputDim,200), nn.ReLU(), #nn.BatchNorm1d(num_features=200), nn.Dropout(0.5), nn.Linear(200,100), nn.Tanh(), #nn.BatchNorm1d(num_features=100), nn.Linear(100,1), nn.Sigmoid() ) optimizer = torch.optim.Adam(model.parameters(),lr=0.001) loss_fn = nn.BCELoss() nepochs = 100 for epoch in range(nepochs): for X,y in Xy_loader: batch_size = X.shape[0] y_hat = model(X.view(batch_size,-1)) loss = loss_fn(y_hat,y) optimizer.zero_grad() loss.backward() optimizer.step() print(float(loss)) with torch.no_grad(): xt = torch.tensor(np.random.rand(1,inputDim)) y2 = model(xt.float()) print(y2.detach().numpy()[0][0])
01-Code/4_a_DNN.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Построение рекомендательной системы при помощи библиотеки Surprise with Python. # # # ![recommender.png](attachment:recommender.png) # # # # # # Данная работа выполнена в рамках <a href="https://gpn-cup.ru/" target="_blank">GPN Intelligence Cup осень 2021</a> по направлению Data Science. В связи с ограничениями размера сохраняемых файлов на Github исходные данные для данного проекта можно скачать по <a href="https://drive.google.com/file/d/1Vk0EJmtzXNPgIBWeQS4KJvhCtZ_6e87r/view?usp=sharing" target="_blank">этой ссылке</a> и распаковать в директорию данного ноутбука перед исполнением кода. # # В качестве рекомендательной системы используется библиотека <a href="http://surpriselib.com/" target="_blank">Surprise</a> и некоторые функции,приведенные на ее официальном сайте. # # # ## 1. Анализ входных данных # # Импортируем нужные модули и экспортируем данные из исходных файлов для анализа и выбора дальнейшего решения: # + import pandas as pd import numpy as np from collections import defaultdict from scipy.stats import skew from surprise import Reader from surprise import Dataset from surprise.model_selection import cross_validate from surprise.model_selection import GridSearchCV from surprise.model_selection import KFold from surprise import NormalPredictor from surprise import KNNBasic from surprise import KNNWithMeans from surprise import KNNWithZScore from surprise import KNNBaseline from surprise import SVD from surprise import BaselineOnly from surprise import SVDpp from surprise import NMF from surprise import SlopeOne from surprise import CoClustering from surprise.model_selection import train_test_split pd.options.display.max_columns = 50 pd.options.display.max_rows = 100 sku_raw = pd.read_parquet('nomenclature.parquet') trans_raw = pd.read_parquet('transactions.parquet') trans_subm_raw = pd.read_parquet('transactions-for_submission.parquet') submis_sample = pd.read_parquet('submission-example.parquet') # Проверяем sku NaN - не входят ли они в требуемую нам категорию print("Размерность массива sku товаров: ", sku_raw.shape) print("Сума NaN величин sku товаров\n ", sku_raw.isna().sum()) sku_nan = sku_raw[sku_raw.isna().any(axis=1)] print("\nСписок товаров с NaN sku\n:", sku_nan) # + print("\n1. Размерность `transactions` dataset: строк: {:,}, столбцов: {}.".format( trans_raw.shape[0],trans_raw.shape[1])) print("Сумма NaN значений столбцов для `transactions` dataset:") print(trans_raw.isna().sum()) print("Доля транцзакций без client_id для `transactions` dataset\ - {:.3%}.".format(trans_raw.isna().sum().client_id/trans_raw.shape[0])) print("\n2. Размерность `transactions` dataset: строк: {:,}, столбцов: {}.".format( trans_subm_raw.shape[0],trans_subm_raw.shape[1])) print("Сумма NaN значений столбцов `transactions_for_submision` dataset") print(trans_subm_raw.isna().sum()) print("Доля транцзакций без client_id для `transactions_for_submission` dataset\ - {:.3%}.".format(trans_subm_raw.isna().sum().client_id/trans_subm_raw.shape[0])) # - # Создаем фильтр требуемых нам товаров на основании sku_id и требуемых нам категорий: # + sku_group_filter = [ 'Вода', 'Сладкие Уранированные напитки, холодный чай' , 'Кофейные напитки с молоком', 'Энергетические напитки', 'Снеки', 'Соки и сокосодержащие напитки'] sku_filter = [] for value in sku_group_filter: sku_filter.extend(list(sku_raw[sku_raw.sku_group==value].sku_id.values)) # Отделяем транцзакции и чеки по нужным для рекомендательной системы категориям trans = trans_raw[trans_raw.sku_id.isin(sku_filter)].reset_index() trans_subm = trans_subm_raw[trans_subm_raw.sku_id.isin(sku_filter)].reset_index() trans = trans[["client_id","sku_id", "number", "cheque_id"]] trans_subm = trans_subm_raw[trans_subm_raw.sku_id.isin(sku_filter)].reset_index() # Проверяем совпвдение сlient_id в транцакциях и транзакциях для рекомендаций client_id_trans = trans.client_id.unique() client_id_trans_submis = trans_subm.client_id.unique() # Проверяем client_id submis_subset = set(client_id_trans_submis).issubset(set(client_id_trans)) print("Является ли множество client_id из `transactions_for_submision` подмножеством `transactions`:",submis_subset ) # - # Как видно выше в транзакциях в обоих датасетах нет половины идентификаторов клиентов. # Методы импутации недостающих в данных в Pytnon не обладают высокой <a href="https://machinelearningmastery.com/handle-missing-data-python/" target="_blank">точностью</a>, можно все NaN величины заполнить средним значением — но это обманывать самого себя. Кроме того база транзакций содержит нулевые и вещественные данные менее единицы в полях `number` товаров что заставляет усомнится в `number` как объективном и достоверном показателе. # # Для построения рекомендательной системы я предлагаю использовать sku_id как user_id, # ввести новую переменную item_id через конвертацию числового значения sku_id в виде текста, и каждый sku_id присваивает item_id рейтинг от 1 до 20 на основе счетчиков в транзациях. В Surprise сохраняем все настройки для simularity как для пользователя. # # * Sadly, the scikit-learn implementations of naive bayes, decision trees and k-Nearest Neighbors are not robust to missing values. # + # ============================================================================= # # Группируем данные по счетчику проданных SKU для формирования рейтинга # для `transactions` и `transactions-for_submission` провераем что sku_id # второго dataset являются подмножеством первого # ============================================================================= sku_stat = trans.groupby(["sku_id"]).agg({"sku_id":"count"}) sku_stat.rename(columns={"sku_id":"sell_count"}, inplace=True) sku_stat.reset_index(inplace=True) sku_stat_subm = trans_subm.groupby(["sku_id"]).agg({"sku_id":"count"}) sku_stat_subm.rename(columns={"sku_id":"sell_count" }, inplace=True) sku_stat_subm.reset_index(inplace=True) sku_stat_subm_subset =set(sku_stat.sku_id).issubset(sku_stat_subm.sku_id) # Видим что множества не совпаюат и строим две модели рейтинга для # `transactions` и `transactions-for_submission` print("Skew для сумм транзакций товаров в `transactions` - {:.3f}.".format( skew(sku_stat.sell_count.values))) print("Skew для сумм транзакций товаров в `transactions-for_submission`- \ {:.3f}.".format(skew(sku_stat_subm.sell_count.values))) print("Является ли множество sku_id в `transactions-for_submission` подмножеством `transactions`?:",\ sku_stat_subm_subset) # - # Как мы видим, нельзя посчитать рейтинг по транзакциям используя только данные `transactions` так как множество sku_id различное для `transactions-for_submission`. Поэтому определяем функцию для расчета рейтинга, так как значение модуля skew намного больше 1, распределение очень не симметричное то используем логарифмическую шкалу для расчета рейтингов. Удалять outliers в данном случае бессмысленно, так как мы просто потеряем ценные для нас данные. # + def fillrating(dfcolumn): column_in = dfcolumn.copy() column_out = column_in.copy() column_out.values[:] =float("nan") column_out.rename("out", inplace = True) if column_in.values.min() <= 0: return "Number must be positive value!" scale = np.logspace(np.log(column_in.values.min()), np.log(column_in.values.max()-1), num=21, base = np.exp(1)) scale_range = [[scale[i], scale[i+1]] for i in range(len(scale)-1)] for i, val in enumerate(column_in.values): for j, ranges in enumerate(scale_range): if val >=ranges[0] and val < ranges[1]: column_out.values[i] = j + 1 if val == column_in.values.max(): column_out.values[i] = len(scale_range) return column_out # Создаем два дата фрейма, для построения рекомендательных систем # sku_id будет выступать в роли user_id для item_trans_rating = sku_stat.copy() item_trans_rating["item_id"] = item_trans_rating["sku_id"].astype(str) item_trans_rating["rating"] = fillrating(item_trans_rating.sell_count) item_subm_rating = sku_stat_subm.copy() item_subm_rating["item_id"] = item_subm_rating ["sku_id"].astype(str) item_subm_rating["rating"] = fillrating(item_subm_rating .sell_count) item_trans_intersect = set(item_trans_rating.sku_id) & \ set(item_subm_rating.sku_id) item_subm_diff = set(item_subm_rating.sku_id)\ .difference(set(item_trans_rating.sku_id)) print("Сумма транзакций товаров в `transactions`: {:,}."\ .format(sku_stat.sell_count.sum())) print("Cумма sku_id товаров в `transactions`: {:,}."\ .format(len(sku_stat.sku_id.unique()))) print("Сумма транзакций товаров в `transactions-for_submission`: {:,}."\ .format(sku_stat_subm.sell_count.sum())) print("Cумма sku_id товаров в `transactions-for_submission`: {:,}."\ .format(len(sku_stat_subm.sku_id.unique()))) print("Количество товаров присуствующих и в `transactions`\ и в `transactions-for_submission`: ", len(item_trans_intersect)) print("Количество товаров в `transactions-for_submission` не включенных \ в`transactions`: ", len(item_subm_diff)) # - # Данные из `transactions` более статистически значимые чем в `transactions-for_submission` поэтому за основу рейтинга будут приниматься данные из `transactions` которые дополнятся недостающими данными из `transactions-for_submission`. # # Сводим все данные о рейтингах в один файл и ищем лучший estimator # + # Добавляем к недостающим рейтингам в transactions рейтинги из # transactions-for_submission` item_rating = pd.concat([ item_trans_rating[item_trans_rating.sku_id.isin(item_trans_intersect)], item_subm_rating[item_subm_rating.sku_id.isin(item_subm_diff)] ]) # Функция для оценки оптимального алгоритма для рекомендательной системы def bestestimator(input_data): estimator_list = [] # Estimate all algoritms for algorithm in [SVD(), SVDpp(), SlopeOne(), NMF(), NormalPredictor(), KNNBaseline(), KNNBasic(), KNNWithMeans(), KNNWithZScore(), BaselineOnly(), CoClustering()]: # Perform cross validation results = cross_validate(algorithm, input_data, cv=5, verbose=False) # Get results & append algorithm name tmp = pd.DataFrame.from_dict(results).mean(axis=0) tmp = tmp.append(pd.Series([str(algorithm).split(' ')[0].\ split('.')[-1]], index=['Algorithm'])) estimator_list.append(tmp) estimator_df = pd.DataFrame(estimator_list).set_index('Algorithm').\ sort_values('test_mae') return estimator_df # Выбираем лучший метод решения reader = Reader(rating_scale=(1, 20)) item_rating = item_rating[["sku_id", "item_id", "rating"]].copy() item_rating.reset_index(drop=True, inplace = True) item_rating_data = Dataset.load_from_df(item_rating, reader) item_rating_bench = bestestimator(item_rating_data) # - item_rating_bench # Еще раз перепроверяем: # + # Оставляем в итоге для дальнейших расчетов user_clean_rating и подбираем # оптимальные параметры для KNNWithMean, KNNWitZScore, KNNBasic algo = [KNNWithMeans, KNNWithZScore, KNNBasic] cols = ["algo", "best_rmse", "best_k_rmse", "best_min_k_rmse", "best_mae", "best_k_mae", "best_min_k_mae"] algos = [str(val).split(".")[-1].split("'>")[0] for val in algo] best_rmse =[] best_rmse_k = [] best_rmse_min_k = [] best_mae = [] best_mae_k =[] best_mae_min_k =[] param_grid = {'k': [1, 100], 'min_k': [1, 20]} for alg in algo: gs = GridSearchCV(alg, param_grid, measures=['rmse', 'mae'], cv=5); gs.fit(item_rating_data) best_rmse.append(gs.best_score["rmse"]) best_rmse_k.append(gs.best_params["rmse"]["k"]) best_rmse_min_k.append(gs.best_params["rmse"]["min_k"]) best_mae.append(gs.best_score["mae"]) best_mae_k.append(gs.best_params["mae"]["k"]) best_mae_min_k.append(gs.best_params["mae"]["min_k"]) gs_data = [algos, best_rmse, best_rmse_k, best_rmse_min_k, best_mae, best_mae_k, best_mae_min_k] item_rating_best_params = pd.DataFrame() for i, cols_name in enumerate(cols): item_rating_best_params[cols_name] = gs_data[i] item_rating_best_params = item_rating_best_params.sort_values("best_mae", ascending = True) # - item_rating_best_params # Проверим еще раз algo_1 = gs.best_estimator['rmse'] algo_1.fit(item_rating_data.build_full_trainset()) algo_2 = gs.best_estimator['mae'] algo_2.fit(item_rating_data.build_full_trainset()) # Как мы видим, разница в значениях `mae` и `rmse` ничтожна, поиск гиперпарамтеров ничего не дал, поэтому оставляем KNNBasic в качестве основного estimator с значениями по умолчанию. # Полученные значения `mae` и `rmse` на мой взгляд не очень плохи при разбросе рейтинга от 1 до 20. # # ## 2. Построение списка рекомендаций для каждого `sku_id` # + # Определяем функцию для 20 рекомендуюмых товарв def get_top_n(predictions, n=20): """Return the top-N recommendation for each user from a set of predictions. Args: predictions(list of Prediction objects): The list of predictions, as returned by the test method of an algorithm. n(int): The number of recommendation to output for each user. Default is 10. Returns: A dict where keys are user (raw) ids and values are lists of tuples: [(raw item id, rating estimation), ...] of size n. """ # First map the predictions to each user. top_n = defaultdict(list) for uid, iid, true_r, est, _ in predictions: top_n[uid].append((iid, est)) # Then sort the predictions for each user and retrieve the k highest ones. for uid, user_ratings in top_n.items(): user_ratings.sort(key=lambda x: x[1], reverse=True) top_n[uid] = user_ratings[:n] return top_n # Формируем словарь для будущего dataframe # Predect rating algo = KNNBasic() item_predict_scale = [int(val) * 100 for val in range(int(item_rating.shape[0]/100)+1)] # собираем предсказанные данные в predictions predictions = [] for i, val in enumerate(item_predict_scale): if val < max(item_predict_scale): idxs_predict = [i for i in range(val,item_predict_scale[i+1]+1)] #test.append(idxs_predict) else: idxs_predict = [i for i in range(max(item_predict_scale), item_rating.shape[0])] #test.append(idxs_predict) for_pred_set = set(idxs_predict) idxs_train_test = list(set(item_rating.index).difference(for_pred_set)) item_rating_train_test = item_rating.iloc[idxs_train_test,:] train_test_set = Dataset.load_from_df(item_rating_train_test, reader) for_pred_item = item_rating.iloc[list(for_pred_set),:] trainset, testset = train_test_split(train_test_set, test_size=0.2) algo = KNNBasic() algo.fit(trainset) testset = trainset.build_anti_testset() pred= algo.test(testset) predictions.append(pred) # Than predict ratings for all pairs (u, i) that are NOT in the training set. tops_n = {} for prediction in predictions: top_n = get_top_n(prediction, n=20) for key, value in top_n.items(): if key not in tops_n.keys(): tops_n[key] = value # собираем данные в шаблон df item_pred_tmpl = {} for key in tops_n.keys(): temp_1 = [] temp_2 = tops_n[key] for val in temp_2: temp_1.append(int(val[0])) item_pred_tmpl[key] = temp_1 # Из за недостатка времени некогда было сделать красиво итоговый df item_predict = pd.DataFrame(item_pred_tmpl).T item_predict.reset_index(inplace = True) item_predict_new_cols = {'index':"sku", 0:"sku_1", 1:"sku_2", 2:"sku_3", 3:"sku_4", 4:"sku_5", 5:"sku_6", 6:"sku_7", 7:"sku_8", 8:"sku_9", 9:"sku_10", 10:"sku_11", 11:"sku_12", 12:"sku_13", 13:"sku_14", 14:"sku_15", 15:"sku_16", 16:"sku_17", 17:"sku_18", 18:"sku_19", 19:"sku_20"} item_predict.rename(columns = item_predict_new_cols, inplace = True) # - item_predict.head() # Сохраняем результат в файл `trans_submission_final.gzip` - к каждому sku_id будет добавлен лист из 20 рекомендованных товаров # + # Объединяем итоговые таблицы для импорта в паркет и сохраняем результат trans_subm = trans_subm.merge(item_rating[["sku_id", "rating"]], how="inner", left_on = "sku_id", right_on = "sku_id") trans_subm = trans_subm.merge(item_predict, how="inner", left_on = "sku_id", right_on = "sku") trans_subm.to_parquet("trans_submission_final.gzip", compression = "gzip") # - # Рассчитываем и печатаем метрику precision@k and recall@k # + # compute precision@k and recall@k def precision_recall_at_k(predictions, k=40, threshold=3.5): """Return precision and recall at k metrics for each user""" # First map the predictions to each user. user_est_true = defaultdict(list) for uid, _, true_r, est, _ in predictions: user_est_true[uid].append((est, true_r)) precisions = dict() recalls = dict() for uid, user_ratings in user_est_true.items(): # Sort user ratings by estimated value user_ratings.sort(key=lambda x: x[0], reverse=True) # Number of relevant items n_rel = sum((true_r >= threshold) for (_, true_r) in user_ratings) # Number of recommended items in top k n_rec_k = sum((est >= threshold) for (est, _) in user_ratings[:k]) # Number of relevant and recommended items in top k n_rel_and_rec_k = sum(((true_r >= threshold) and (est >= threshold)) for (est, true_r) in user_ratings[:k]) # Precision@K: Proportion of recommended items that are relevant # When n_rec_k is 0, Precision is undefined. We here set it to 0. precisions[uid] = n_rel_and_rec_k / n_rec_k if n_rec_k != 0 else 0 # Recall@K: Proportion of relevant items that are recommended # When n_rel is 0, Recall is undefined. We here set it to 0. recalls[uid] = n_rel_and_rec_k / n_rel if n_rel != 0 else 0 return precisions, recalls kf = KFold(n_splits=5) algo = KNNBasic() for trainset, testset in kf.split(item_rating_data): algo.fit(trainset) predictions = algo.test(testset) precisions, recalls = precision_recall_at_k(predictions, k=5, threshold=4) # Precision and recall can then be averaged over all users print(sum(prec for prec in precisions.values()) / len(precisions)) print(sum(rec for rec in recalls.values()) / len(recalls)) # - # ## 3. Выводы # 1. Точность предсказания имеет вполне приемлемые границы, что подтверждает и распечатка метрики precision@k and recall@k # 2. Имеющиеся наборы данных — а именно почти половина отсутсвующих client_id и невозможность их восстановления средствами Pytnon не оставляют другого выбора как делить sku_id на sku_id numeric и item_id = str(sku_id), но как мне кажется по такому принципу построены все рекомендательные системы, которые не имея доступа к истории покупок от пользователя начинают рекомендовать другие товары по подобию рейтингов выбранного товара. # # Справочная литература - Recommender Systems: An Introduction ISBN-13: 978-0521493369 # # # @author: <NAME>, использованы некоторые идеи с публичных Internet ресурсов. # # © 3-clause BSD License # # Software environment: Debian 11, Python 3.8.12
05_Recommender_system_with_Surprise/Recommender_system_with_surpise.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Generalized Linear Regression # ## Import and Prepare the Data # ### Pandas provides excellent data reading and querying module,dataframe, which allows you to import structured data and perform SQL-like queries. # # ### Here we imported some house price records from Trulia. For more about extracting data from Trulia, please check my previous tutorial. # # ### We used the house prices as the dependent variable and the lot size, house area, the number of bedrooms and the number of bathrooms as the independent variables. # + import sklearn from sklearn.model_selection import train_test_split from matplotlib import pyplot as plt # %matplotlib inline import pandas import numpy as np df = pandas.read_excel('house_price.xlsx') # combine multipl columns into a 2D array X = np.column_stack((df.lot_size,df.area,df.bedroom,df.bathroom)) y = df.price print (X[:10]) #split data for training and testing X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.3 , random_state=3) # - # ## Ordinary Least Squares # ### We used a multiple linear regression model to learn the data and test the R squares on the training data and the test data. from sklearn.linear_model import LinearRegression lr = LinearRegression().fit(X_train, y_train) print("lr.coef_: {}".format(lr.coef_)) print("lr.intercept_: {}".format(lr.intercept_)) print("Training R Square: {:.2f}".format(lr.score(X_train, y_train))) print("Test R Square: {:.2f}".format(lr.score(X_test, y_test))) # ### The model reported the coefficients of all features, and the R square on the training data is good. However, the R square of the testing data is much lower, indicating an overfitting situation. # ## Ridge Regression # ### Ridge Regression reduces the complexity of linear models by imposing a penalty on the size of coefficients to push all coefficients close to 0. # + from sklearn.linear_model import Ridge ridge = Ridge().fit(X_train, y_train) print("Training R Square: {:.2f}".format(ridge.score(X_train, y_train))) print("Test R Square: {:.2f}".format(ridge.score(X_test, y_test))) # - # ### We can increase the alpha to push all coefficients closer to 0. ridge10 = Ridge(alpha=10).fit(X_train, y_train) # set different aphpa print("Training R Square: {:.2f}".format(ridge10.score(X_train, y_train))) print("Test R Square: {:.2f}".format(ridge10.score(X_test, y_test))) ridge1000 = Ridge(alpha=1000).fit(X_train, y_train) print("Training R Square: {:.2f}".format(ridge1000.score(X_train, y_train))) print("Test R Square: {:.2f}".format(ridge1000.score(X_test, y_test))) # ### We can visually compare the coefficients from the Ridge Regression models with different alpha. plt.plot(ridge.coef_, 's', label="Ridge alpha=1") plt.plot(ridge10.coef_, '^', label="Ridge alpha=10") plt.plot(ridge1000.coef_, 'v', label="Ridge alpha=1000") plt.plot(lr.coef_, 'o', label="LinearRegression") plt.xlabel("Coefficient index") plt.ylabel("Coefficient magnitude") plt.hlines(0, 0, len(lr.coef_)) plt.legend() # ## Lasso Regression # ### Lasso is another model that estimates sparse coefficients by push some coefficients to 0, i.e., reduce the number of coefficients. # + from sklearn.linear_model import Lasso lasso = Lasso().fit(X_train, y_train) print("Training set score: {:.2f}".format(lasso.score(X_train, y_train))) print("Test set score: {:.2f}".format(lasso.score(X_test, y_test))) # here we also report the number of coefficients print("Number of features used: {}".format(np.sum(lasso.coef_ != 0))) # - # ### We can also adjust the alpha to push some coefficients closer to 0. lasso10 = Lasso(alpha=10).fit(X_train, y_train) #set different alpha print("Training R Square: {:.2f}".format(lasso10.score(X_train, y_train))) print("Test R Square: {:.2f}".format(lasso10.score(X_test, y_test))) print("Number of features used: {}".format(np.sum(lasso10.coef_ != 0))) lasso10000 = Lasso(alpha=10000, ).fit(X_train, y_train) print("Training R Square: {:.2f}".format(lasso10000.score(X_train, y_train))) print("Test R Square: {:.2f}".format(lasso10000.score(X_test, y_test))) print("Number of features used: {}".format(np.sum(lasso10000.coef_ != 0))) # ### We can also check the coefficients from the Lasso Regression models with different alpha. plt.plot(lasso.coef_, 's', label="Lasso alpha=1") plt.plot(lasso10.coef_, '^', label="Lasso alpha=10") plt.plot(lasso10000.coef_, 'v', label="Lasso alpha=10000") plt.plot(lr.coef_, 'o', label="LinearRegression") plt.legend(ncol=2, loc=(0, 1.05)) plt.xlabel("Coefficient index") plt.ylabel("Coefficient magnitude")
Lab_4.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/meesalamanikanta/18cse011/blob/main/Assignment1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="MNho2Gym7wU8" import numpy from scipy import stats # + id="PqDJFmW977Z5" weight=[56,60,62,65,70] # + id="xCjV8Srs8A1E" x=numpy.mean(weight) y=numpy.median(weight) z=stats.mode(weight) s=numpy.std(weight) v=numpy.var(weight) # + colab={"base_uri": "https://localhost:8080/"} id="GF4MPPQ78FBF" outputId="0d3bb4e1-9957-4fba-97c0-a83c148be991" print("mean is :",x) print("median is :",y) print("mode is :",z) print("standard deviation is :",s) print("varience is :",v) # + [markdown] id="5PloinNJ6-r2" # **Q2. Write a python code for calculating variance and standard deviation for the set of elements.** # + id="n1D4qZ906CWY" s = numpy.std(age) # + id="O7_mIWgc6F8D" v = numpy.var(age) # + id="Z-BIWFQL6V0h" colab={"base_uri": "https://localhost:8080/"} outputId="ae647c2a-7dec-4d8a-f7ab-95fd422fc652" print('Standard Deviation = ',s) # + id="74rkqJ4p6as_" colab={"base_uri": "https://localhost:8080/"} outputId="26a22701-26b1-4247-baa2-9460c1993e08" print('Variacnce = ',v) # + [markdown] id="mm7vPkAT77B0" # **Practice some basic python programs** # + id="LXbaZZte8CpN" colab={"base_uri": "https://localhost:8080/"} outputId="c247d806-4e30-4c11-d2fa-ddc3f823ce18" # This program prints Hello, world! print('Hello, world!') # + id="a2SXyU608YWS" colab={"base_uri": "https://localhost:8080/"} outputId="a534a751-fe16-4a57-9c1d-2c0c09206d52" # This program adds two numbers num1 = 1.5 num2 = 6.3 # Add two numbers sum = num1 + num2 # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) # + id="mVDfAFG-8dPP" colab={"base_uri": "https://localhost:8080/"} outputId="4dd7631f-a458-49b0-f4a2-5cee776dfb3b" # Python Program to calculate the square root num = 8 num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) # + id="vFr9zZy88oTN" colab={"base_uri": "https://localhost:8080/"} outputId="607385a8-38a0-487d-d2bf-ff63765077d1" # Solve the quadratic equation ax**2 + bx + c = 0 # import complex math module import cmath a = 1 b = 5 c = 6 # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(sol1,sol2)) # + id="UJm_a8g781cP" colab={"base_uri": "https://localhost:8080/"} outputId="a8fc2487-f8c9-42ee-f624-e4891e2438ce" # Python program to swap two variables x = 5 y = 10 # create a temporary variable and swap the values temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) # + id="FggZVKQc9ANq" colab={"base_uri": "https://localhost:8080/"} outputId="ae9f51fc-0440-4075-b472-d478e561aaec" # Program to generate a random number between 0 and 9. # importing the random module. import random print(random.randint(0,9))
Assignment1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Detecção por Inteligência Artificial de Barras Quebradas em Rotores de Motores de Indução Trifásicos. # # Objetivo do projeto - Baseado em conceitos de Data Science e IA desenvolver uma ferramenta de Manutenção Preditiva dedicada a diagnosticar barras quebradas em rotores de motores de indução trifásicos. # Link para o dataset: https://ieee-dataport.org/open-access/experimental-database-detecting-and-diagnosing-rotor-broken-bar-three-phase-induction # # Introdução: # # O conjunto de dados contém sinais elétricos e mecânicos de experimentos em motores de indução trifásicos. Os ensaios experimentais foram realizados para diferentes cargas mecânicas no eixo do motor de indução e diferentes severidades de defeitos de barra quebrada no rotor do motor, incluindo dados referentes ao rotor sem defeitos. Dez repetições foram realizadas para cada condição experimental. # # A bancada experimental consiste em um motor de indução trifásico acoplado a uma máquina de corrente contínua, que funciona como um gerador simulando o torque de carga, conectado por um eixo contendo uma chave de torque rotativa. # # Motor de Indução: 1cv, 220V/380V, 3.02A/1.75A, 4 pólos, 60 Hz, com o torque nominal de 4.1 Nm e uma velocidade nominal de 1715 rpm. O rotor é do tipo gaiola de esquilo composto por 34 barras. # # Torque de carga: é ajustado variando a tensão do enrolamento de campo do gerador de corrente contínua. Um variador de tensão monofásico com um retificador de ponte completa filtrado é usado para esse propósito. Um motor de indução foi testado em 12,5, 25, 37,5, 50, 62,5, 75, 87,5 e 100% da carga total. # # Barra do rotor quebrada: para simular a falha no rotor do motor de indução trifásico, foi necessário perfurar o rotor. As barras de rotor de ruptura são geralmente adjacentes à primeira barra de rotor, 4 rotores foram testados, o primeiro com uma barra de quebra, o segundo com duas barras quebradas adjacentes e assim por diante o rotor contendo quatro barras quebradas adjacentes. # # Condição de monitoramento: # # Todos os sinais foram amostrados ao mesmo tempo por 18 segundos para cada condição de carregamento e dez repetições foram realizadas do transiente para o estado estacionário do motor de indução. # # Sinais mecânicos: foram utilizados cinco acelerômetros axiais simultaneamente, com sensibilidade de 10 mV/mm/s, faixa de frequência de 5 a 2.000 Hz e caixa de aço inoxidável, permitindo medições de vibração tanto na extremidade motriz (DE) quanto na extremidade não motriz (NDE) laterais do motor, axial ou radialmente, nas direções horizontal ou vertical. # # Sinais elétricos: as correntes foram medidas por sondas de corrente alternada, que correspondem a medidores de precisão, com capacidade de até 50ARMS, com tensão de saída de 10 mV/A, correspondente ao modelo Yokogawa 96033. As tensões foram medidas diretamente nos terminais de indução usando pontos de tensão do osciloscópio e do fabricante Yokogawa. # # Visão geral do dataset: # # Tensão trifásica # # Corrente trifásica # # Cinco sinais de vibração # # Referências: # # O banco de dados foi adquirido no Laboratório de Automação Inteligente de Processos e Sistemas e no Laboratório de Controle Inteligente de Máquinas Elétricas da Escola de Engenharia de São Carlos da Universidade de São Paulo (USP), Brasil. # # <NAME>, <NAME>, <NAME>, <NAME>, September 15, 2020, "Experimental database for detecting and diagnosing rotor broken bar in a three-phase induction motor.", IEEE Dataport, doi: https://dx.doi.org/10.21227/fmnm-bn95. # ## Continuando os Estudos sobre a FFT # + [markdown] id="cboi_hUzSaIZ" # #### **ESTUDO DE MANIPULAÇÃO DE DADOS POR TRANSFORMADA RÁPIDA DE FOURIER (FFT) POR JANELAS DESLIZANTES** # # DE ACORDO COM https://pythontic.com/visualization/signals/fouriertransform_fft: # # - Fourier transform is one of the most applied concepts in the world of Science and Digital Signal Processing. # - Fourier transform provides the frequency domain representation of the original signal. # - For example, given a sinusoidal signal which is in time domain the Fourier Transform provides the constituent signal frequencies. # - Using Fourier transform both periodic and non-periodic signals can be transformed from time domain to frequency domain. # # # O ARTIGO APRESENTANDO EM (https://towardsdatascience.com/fast-fourier-transform-937926e591cb): # - MOSTRA A MATEMÁTICA PARA O DESENVOLVIMENTO A TRANSFORMADA RÁPIDA NO DOMÍNIO DE TEMPO DISCRETO. UMA IMPORTANTE CONCLUSAO DESTE ARTIGO É A POSSIBILIADE DA IMPLEMENTAÇÃO DA FUNÇÃO POR ESCRITA DIRETA EM PYTHON, USAR A FUNÇÃO DO NUMPY OU USAR A FUNÇÃO O SCIPY. A PARTIR DO ARTIGO PODE-SE PERCEBER QUE A FUNÇÃO CRIADA EM SCIPY CONSISTE NA FUNÇÃO DE MELHOR DESEMPENHO E PORTANTO A ESCOLHA PARA ESTE TRABALHO. # # TUTORIAL UTILIZADO PARA A IMPLEMENTAÇÃO EM CÓDIGO: # # https://realpython.com/python-scipy-fft/ # # EBOOK PARA REFERÊNCIA TEÓRICA (CAP. 24): # # https://pythonnumericalmethods.berkeley.edu/notebooks/Index.html # # CAPÍTULO PARA REFERÊNCIA TEÓRICA: # # https://www.oreilly.com/library/view/elegant-scipy/9781491922927/ch04.html # # CONCEITOS ESSENCIAIS: # # - TAXA DE AMOSTRAGEM https://pt.wikipedia.org/wiki/Taxa_de_amostragem # - TEOREMA DE NYQUIST https://pt.wikipedia.org/wiki/Teorema_da_amostragem_de_Nyquist%E2%80%93Shannon # - JANELAMENTO FFT # -- https://www.youtube.com/watch?v=T9x2rvdhaIE # -- https://en.wikipedia.org/wiki/Window_function # # IMPLEMENTAÇÃO DA TÉCNICA DE JANELAMENTO DA FFT: https://flothesof.github.io/FFT-window-properties-frequency-analysis.html # + id="_xZSsfAgxslI" # Python example - Fourier transform using numpy.fft method import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.fft import rfft, rfftfreq # + [markdown] id="KoDYEbtnWjbR" # ### CÓDIGO EXEMPLO # + [markdown] id="tsBZj7HzXRpU" # Passo 1. Criando sinal senoidal para análise a partir da soma de duas ondas senoidais com amplitude e frequencias diferentes: # + id="KbPMf6bQXPJp" # How many time points are needed per seconds i,e., Sampling Frequency samplingFrequency = 100; # At what intervals time points are sampled samplingInterval = 1 / samplingFrequency; # Begin time period of the signals beginTime = 0; # End time period of the signals endTime = 10; # Frequency of the signals signal1Frequency = 4; signal2Frequency = 20; # Time points time = np.arange(beginTime, endTime, samplingInterval); # Create two sine waves amplitude1 = np.sin(2*np.pi*signal1Frequency*time) amplitude2 = 0.5*np.sin(2*np.pi*signal2Frequency*time) # Add the sine waves amplitude = amplitude1 + amplitude2 # + [markdown] id="A99aAsfoYcnC" # Passo 2. Definindo os gráficos para componente, forma de onda a ser transformada e resultado apresentando pela FFT: # + colab={"base_uri": "https://localhost:8080/", "height": 621} id="tnv066UNXej2" outputId="a6f52738-09fc-466f-832a-52d9d3667d12" # Create subplot figure, axis = plt.subplots(4, 1,figsize=(15,10)) plt.subplots_adjust(hspace=1) # Time domain representation for sine wave 1 axis[0].set_title('Sine wave with a frequency of 4 Hz') axis[0].plot(time, amplitude1) axis[0].set_xlabel('Time') axis[0].set_ylabel('Amplitude') # Time domain representation for sine wave 2 axis[1].set_title('Sine wave with a frequency of 7 Hz') axis[1].plot(time, amplitude2) axis[1].set_xlabel('Time') axis[1].set_ylabel('Amplitude') # Time domain representation of the resultant sine wave axis[2].set_title('Sine wave with multiple frequencies') axis[2].plot(time, amplitude) axis[2].set_xlabel('Time') axis[2].set_ylabel('Amplitude') # Frequency domain representation fourierTransform = np.fft.fft(amplitude)/len(amplitude) # Normalize amplitude fourierTransform = fourierTransform[range(int(len(amplitude)/2))] # Exclude sampling frequency tpCount = len(amplitude) values = np.arange(int(tpCount/2)) timePeriod = tpCount/samplingFrequency frequencies = values/timePeriod # Frequency domain representation axis[3].set_title('Fourier transform depicting the frequency components') axis[3].plot(frequencies, abs(fourierTransform)) axis[3].set_xlabel('Frequency') axis[3].set_ylabel('Amplitude') plt.show() # + [markdown] id="bdRQpVNzZC2t" # A implementação anterior utiliza-se do numpy para a transformação. A utilização das bibliotecas numpy e scipy são bastante similares como apresentado abaixo, com a diferença que a função em Scipy é mais eficiente. Um ponto importante na definição a FFT é a taxa de amostragem que corresponde a quantas amostras por segundo foram realizadas para formar o sinal de onda em análise. # + colab={"base_uri": "https://localhost:8080/", "height": 320} id="jZtJnuv1xvOb" outputId="d705903d-5a70-4434-8f7b-8ec0eb5d3328" normalized_tone = amplitude SAMPLE_RATE = samplingFrequency DURATION = endTime # Number of samples in normalized_tone N = SAMPLE_RATE * DURATION # Note the extra 'r' at the front yf = rfft(normalized_tone) xf = rfftfreq(N, 1 / SAMPLE_RATE) plt.figure(figsize=(10,5)) plt.plot(xf, np.abs(yf)) plt.show() # + [markdown] id="zbQxE2BGZsFE" # Implementando um filtro simples na FFT: # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="I5WG2vfAz0HW" outputId="c6b21d3e-e5cf-49d5-c889-a1c75e140479" # The maximum frequency is half the sample rate points_per_freq = len(xf) / (SAMPLE_RATE / 2) # Our target frequency is 15 Hz target_idx = int(points_per_freq * 20) yf[target_idx - 1 : target_idx + 2] = 0 plt.plot(xf, np.abs(yf)) plt.show() # + [markdown] id="5o8JbBSELl8G" # Breve estudo sobre o método de janelamento. # # Para sinais curtos, os efeitos de borda podem distorcer significativamente o espectro de potência dos sinais, uma vez que estamos assumindo que nosso sinal é periódico. O uso de janelas afiladas nas bordas pode eliminar esses artefatos de borda e também pode ser usado para eliminar o deslocamento em um sinal. # # https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.windows.hann.html # + colab={"base_uri": "https://localhost:8080/", "height": 313} id="scZvj8qV_w8r" outputId="5e5bf2a9-23e0-4a03-b9bf-85dbaf2c9d84" from scipy import signal from scipy.fft import fft, fftshift window = signal.windows.hamming(101) plt.plot(window) plt.title("hamming window") plt.ylabel("Amplitude") plt.xlabel("Sample") # + colab={"base_uri": "https://localhost:8080/", "height": 313} id="pRGFWy4dLtSM" outputId="3be7bcbe-7697-498e-8917-fa4ae6e18daf" plt.figure() A = fft(window, 2048) / (len(window)/2.0) freq = np.linspace(-0.5, 0.5, len(A)) response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) plt.plot(freq, response) plt.axis([-0.5, 0.5, -120, 0]) plt.title("Frequency response of the Hamming window") plt.ylabel("Normalized magnitude [dB]") plt.xlabel("Normalized frequency [cycles per sample]") # + [markdown] id="hZl2vRJWRATM" # Sobre o uso de janelas no processamento digital de sinais # # https://flothesof.github.io/FFT-window-properties-frequency-analysis.html # # Uma única senóide # # Como uma primeira etapa, veremos o efeito de diferentes janelas na transformada de Fourier de uma única senoide. Vamos gerar nossos dados de amostra e examiná-los. # + id="i-yb_VKTQ7pA" from scipy.signal import get_window # + colab={"base_uri": "https://localhost:8080/", "height": 299} id="cqujQOt0MBxI" outputId="4b8b462d-8e8a-4eed-abde-0a6c85eede76" t = np.arange(0, 2, step=1/500) m = t.size s = np.sin(2 * np.pi * 10.1 * t) + np.sin(2 * np.pi * 25 * t)+ 0.1*np.sin(2 * np.pi * 30 * t) plt.plot(t, s) plt.title("sinusoid, {} samples, sampling rate {} Hz".format(m, 1/(t[1] - t[0]))) # + colab={"base_uri": "https://localhost:8080/", "height": 287} id="Koryyi46Q7mH" outputId="c1df23bd-1bf1-42e9-cf2e-d0f719ccbaa4" for window in ['boxcar', 'hamming', 'blackman']: n = 4096 w = np.fft.rfft(s * get_window(window, m), n=n) freqs = np.fft.rfftfreq(n, d=t[1] - t[0]) plt.plot(freqs, 20*np.log10(np.abs(w)), label=window) plt.ylim(-60, 60) plt.xlim(5, 50) plt.legend() # + [markdown] id="Mzp3P7YoUZGF" # Para continuar veja o jupyter 4_FFT... #
3_SFFT.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import matplotlib.pyplot as plt import numpy as np import pymc3 as pm from sklearn.cross_validation import train_test_split from sklearn.preprocessing import scale from theano import shared import theano.tensor as T from pymc3 import * import warnings warnings.filterwarnings('ignore') # + #Importing dataset df = pd.read_csv('breast-cancer-wisconsin.csv') df.drop(['id'],1,inplace=True) # Convert '?' to NaN df[df == '?'] = np.nan # Drop missing values and print shape of new DataFrame df = df.dropna() X = scale(np.array(df.drop(['class'],1))) y = np.array(df['class'])/2-1 #Split Data X_tr, X_te, y_tr, y_te = train_test_split(X,y,test_size=0.2, random_state=42) #Sharedvariable model_input = shared(X_tr) model_output= shared(y_tr) # - #Generate Model logistic_model = pm.Model() with logistic_model: # Priors for unknown model parameters alpha = pm.Normal("alpha", mu=0,sd=1) betas = pm.Normal("betas", mu=0, sd=1, shape=X.shape[1]) # Expected value of outcome p = pm.invlogit(alpha + T.dot(model_input,betas)) # Likelihood (sampling distribution of observations) y = pm.Bernoulli('y', p, observed=model_output) #infering parameters with logistic_model: advi=pm.ADVI() approx = advi.fit(n=10000,more_replacements={ model_input:pm.Minibatch(X_tr), model_output:pm.Minibatch(y_tr) } ) # + with logistic_model: advi=pm.ADVI() advi.approx.mean.eval() advi.approx.std.eval() tracker = pm.callbacks.Tracker( mean=advi.approx.mean.eval, # callable that returns mean std=advi.approx.std.eval # callable that returns std ) approx = advi.fit(10000, callbacks=[tracker]) fig = plt.figure(figsize=(16, 9)) mu_ax = fig.add_subplot(221) std_ax = fig.add_subplot(222) hist_ax = fig.add_subplot(212) mu_ax.plot(tracker['mean']) mu_ax.set_title('Mean track') std_ax.plot(tracker['std']) std_ax.set_title('Std track') hist_ax.plot(advi.hist) hist_ax.set_title('Negative ELBO track'); # - #for RV in logistic_model.basic_RVs: #print(RV.name, RV.logp(logistic_model.test_point)) #print(p.tag.test_value) # + #Intrepreting parameters trace = approx.sample(draws=10000) print(pm.summary(trace)) pm.plots.traceplot(trace) plt.show() # + #Replace shared variable with testing set model_input.set_value(X_te) model_output.set_value(y_te) # Creater posterior predictive samples ppc = pm.sample_ppc(trace,model=logistic_model,samples=1000) pred = ppc['y'].mean(axis=0) > 0.5 # + print(y_tr.shape) print(X_te.shape) print(y_te.shape) print(pred.shape) print('Accuracy = {}%'.format((y_te == pred).mean() * 100)) # -
Classification/Breastcancer/Debugger.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.9 (''.venv'': venv)' # language: python # name: python3 # --- # # Introduction # ### 1. Importing data using pandas # To use pandas, first import pandas using the alias pd. To import a CSV file, you can use the ```read_csv()``` function and pass the name of the file you want to import. # + # Import pandas into the environment import pandas as pd # Import marketing.csv marketing = pd.read_csv('../data/marketing1.csv') # - # ### 2. Inspecting data # Once you've imported your data, it is a good practice to examine its contents using the ```head()``` method. This will return the first five rows of the DataFrame. # Print the first five rows of the DataFrame print(marketing.head()) # ### 3. Summary statistics # Use the ```describe()``` method to print the statistics of all columns in your dataset. You can inspect the output to find some obvious errors. For example, if you see negative values in a date column, this might indicate an error. In addition, pay careful attention to the minimum and maximum values. If the maximum is much larger than the median, it might be an outlier and merit further investigation. # Print the statistics of all columns print(marketing.describe()) # ### 4. Missing values & data types # Finally, you can identify the data types and the number of non-missing values in your DataFrame using the ```info()``` method. The result includes all columns and their data types. # Check column data types and non-missing values print(marketing.info()) # ### 5. Common data types # Each column in a pandas DataFrame has a specific data type. Some of the common data types are strings (which are represented as objects), numbers, boolean values (which are True/False) and dates. You can use the ```dtype``` attribute if you are interested in knowing the data type of a single column. # Check the data type of is_retained print(marketing['is_retained'].dtype) # ### 6. Changing the data type of a column # To change the data type of a column, you can use the ```astype()``` method. For example, you saw on the earlier slide that the converted column is stored as an object. It contains True and False values, so it's more appropriate to store it as a boolean. You can use the ```astype()``` method along with the argument 'bool' as shown here to change its data type. If you check the data type of the 'converted' column again, you will see that it's now 'bool'. # + # Convert is_retained to a boolean marketing['is_retained'] = marketing['is_retained'].astype('bool') # Check the data type of is_retained, again print(marketing['is_retained'].dtype) # - # ### 7. Mapping values to existing columns # Due to the way pandas stores data, in a large dataset, it can be computationally inefficient to store columns of strings. In such cases, it can speed things up to instead store these values as numbers. To create a column with channel codes, build a dictionary that maps the channels to numerical codes. Then, use the ```map()``` method on the channel column along with this dictionary, as shown here. # + # Mapping for channels channel_dict = {"House Ads": 1, "Instagram": 2, "Facebook": 3, "Email": 4, "Push": 5} # Map the channel to a channel code marketing['channel_code'] = marketing['subscribing_channel'].map(channel_dict) # - # ### 8. Creating new boolean columns # The marketing_channel column captures the channel a user saw a marketing asset on. Say you want to have a column that identifies if a particular marketing asset was a house ad or not. You can use numpy's ```where()``` function to create a new boolean column to establish this. The first argument is an expression that checks whether the value in the marketing_channel column is 'House Ads', the second argument is the value you want to assign if the expression is true, and the third argument is the value you want to assign if the expression is false. # + # Mapping for channels channel_dict = {"House Ads": 1, "Instagram": 2, "Facebook": 3, "Email": 4, "Push": 5} # Map the channel to a channel code marketing['channel_code'] = marketing['subscribing_channel'].map(channel_dict) # Import numpy import numpy as np # Add the new column is_correct_lang marketing['is_correct_lang'] = np.where( marketing['language_preferred'] == marketing['language_displayed'], 'Yes', 'No' ) # - # ### 9. Date columns # Often, you will have date columns that are improperly read as objects by pandas. However, as you will see in the following lessons, having date columns properly imported as the datetime datatype has several advantages. You have two options to ensure that certain columns are treated as dates. First, when importing the dataset using the ```read_csv()``` function, you can pass a list of column names to the ```parse_dates``` argument to ensure that these columns are correctly interpreted as date columns. # + # Import marketing.csv with date columns marketing = pd.read_csv('../data/marketing1.csv', parse_dates = ['date_served', 'date_subscribed', 'date_canceled']) # Add a DoW column marketing['DoW'] = marketing['date_subscribed'].dt.dayofweek # - # ## Explotary Data Analysis # ### 1. How many users see marketing assets? # To begin, let's get a sense of how many unique users see our marketing assets each day. We can use the ```groupby()``` method on the marketing DataFrame. To group by date, we pass 'date_served' as the argument to ```groupby()```. Next, we select the user_id column outside of the ```groupby()``` and use ```nunique()``` method to count the number of unique users each day. Looks like about 300 users each day see our ads. # + # Group by date_served and count number of unique user_id's daily_users = marketing.groupby(['date_served'])['user_id'].nunique() # Print head of daily_users print(daily_users.head()) # - # ### 2. Visualizing results # As you saw on the previous slide, it's not easy to interpret results when they're printed in a table. It's much easier to notice fluctuations in our metrics when we plot them. We first ```import matplotlib.pyplot as plt```. Then, we plot the series daily_users. It's good practice to always add title and labels to your plot in order to clearly convey what information the chart contains. You can add a title using ```plt.title()```, and add x and y labels using ```plt.xlabel() and ```plt.ylabel()``` functions, respectively. We also rotate the ```xticks```, in this case, the date labels, by 45 degrees to increase legibility. Finally, don't forget to include a call to ```plt.show()``` to display the plot. # + import matplotlib.pyplot as plt # Plot daily_subscribers daily_users.plot() # Include a title and y-axis label plt.title('Daily users') plt.ylabel('Number of users') # Rotate the x-axis labels by 45 degrees plt.xticks(rotation=45) # Display the plot plt.show() # - # As you can see, while the first half of the month sticks around 300 users per day, there's a huge spike in the middle of the month. This may be because we sent out a big marketing email, which reached many users who are not daily visitors of the site. These are the kinds of fluctuations we want to be aware of before diving in and calculating metrics.
01-analyzing-marketing-campaigns-with-pd/notebooks/1.1-gk-initial.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="YE7IncjaKMKq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 289} outputId="58201e49-4a93-4350-d91e-364ad70075a3" executionInfo={"status": "ok", "timestamp": 1581691513929, "user_tz": -60, "elapsed": 7035, "user": {"displayName": "Miros\u0142<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} # !pip install eli5 # + id="jRRGzVINKO62" colab_type="code" colab={} import pandas as pd import numpy as np from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import cross_val_score import eli5 from eli5.sklearn import PermutationImportance from ast import literal_eval from tqdm import tqdm_notebook # + id="dX582kxGLTxm" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="203047d9-b9ce-4dba-8cc7-ad2ca23335dd" executionInfo={"status": "ok", "timestamp": 1581691847608, "user_tz": -60, "elapsed": 857, "user": {"displayName": "Miros\u014<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} # cd '/content/drive/My Drive/Colab Notebooks/dw_matrix' # + id="Sd-ttUFoLd7E" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="519645d2-e33f-4fcc-a8d5-fd5d0c1ce5f9" executionInfo={"status": "ok", "timestamp": 1581691850338, "user_tz": -60, "elapsed": 1800, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} # ls # + id="pBaZNOHsLf0Q" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="79b67b3d-4ff3-492d-84ba-0d8eb466eda5" executionInfo={"status": "ok", "timestamp": 1581691868732, "user_tz": -60, "elapsed": 1686, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} # ls data # + id="B2Fgg5kuLo7e" colab_type="code" colab={} df = pd.read_csv('data/men_shoes.csv', low_memory=False) # + id="dzOA83OzL6nM" colab_type="code" colab={} def run_model(feats, model = DecisionTreeRegressor(max_depth=5)): X = df[feats].values y = df['prices_amountmin'].values scores = cross_val_score(model, X, y, scoring='neg_mean_absolute_error') return np.mean(scores), np.std(scores) # + id="m8yODSd_Mw4R" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="d3c03f9b-705a-420c-da87-b2c41700a8de" executionInfo={"status": "ok", "timestamp": 1581693206689, "user_tz": -60, "elapsed": 564, "user": {"displayName": "Miros\u01<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} df[ 'brand_cat' ] = df[ 'brand' ].map(lambda x: str(x).lower()).factorize()[0] run_model(['brand_cat']) # + id="Xg_6288kNWf5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="6e7f29ea-1cfc-4279-c04d-b3f8d9f4aef4" executionInfo={"status": "ok", "timestamp": 1581693231214, "user_tz": -60, "elapsed": 3747, "user": {"displayName": "Miros\u<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} model = RandomForestRegressor(max_depth=5, n_estimators=100, random_state=0) run_model(['brand_cat'], model) # + id="rJa-bvEZPy7N" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 138} outputId="40635c4c-5a04-46b3-9501-b0f5b511ea60" executionInfo={"status": "ok", "timestamp": 1581693322187, "user_tz": -60, "elapsed": 562, "user": {"displayName": "Miros\u01<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} df.features.head().values # + id="qgz5kUymQcX1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="2c520874-43ff-4f64-aae8-18baa80f41ab" executionInfo={"status": "ok", "timestamp": 1581693589635, "user_tz": -60, "elapsed": 533, "user": {"displayName": "Miros\u<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} str_dict = '[{"key":"Gender","value":["Men"]},{"key":"Shoe Size","value":["M"]},{"key":"Shoe Category","value":["Men\'s Shoes"]},{"key":"Color","value":["Multicolor"]},{"key":"Manufacturer Part Number","value":["8190-W-NAVY-7.5"]},{"key":"Brand","value":["Josmo"]}]' literal_eval(str_dict)[0]['value'][0] # + id="eYbzfTF-R0zu" colab_type="code" colab={} def parse_features(x): output_dict = {} if str(x) == 'nan' : return output_dict features = literal_eval(x.replace('\\"', '"')) for item in features: key = item['key'].lower().strip() value = item['value'][0].lower().strip() output_dict[key] = value return output_dict df['features_parsed'] = df['features'].map(parse_features) # + id="Z2JV4qhXTJf7" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="32308e98-e2ab-4093-e1a0-aa37123576aa" executionInfo={"status": "ok", "timestamp": 1581694476854, "user_tz": -60, "elapsed": 539, "user": {"displayName": "Miros\u014<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} keys = set() df['features_parsed'].map(lambda x: keys.update(x.keys())) len(keys) # + id="kACqhowYWIQf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 138} outputId="af1a6ac0-5169-4fb2-f9d4-0f8fc1bd8496" executionInfo={"status": "ok", "timestamp": 1581694640516, "user_tz": -60, "elapsed": 567, "user": {"displayName": "Miros\u01<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} df.features_parsed.head().values # + id="yF12zePQTixV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 66, "referenced_widgets": ["477dd0d1b3d3419fa70423a75c3ec950", "44a76b07f5634faa9a9ecd1a3026dc1f", "841ec169a4be451d84360c1aee10a416", "28aecbe4ac2f449f804355effabcca53", "42ed600d05804b498e76c5b117d6e1b9", "65ce60a4833341ec9ad70c5145a52b27", "9c8c33bea7794a2580e2bea601302460", "4d41c7e906894296a0e7cf2b6429a35b"]} outputId="2b1ffd13-28d3-4b94-a4cd-8b40688b8989" executionInfo={"status": "ok", "timestamp": 1581694997442, "user_tz": -60, "elapsed": 5539, "user": {"displayName": "Miros\u01<NAME>00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} def get_name_feat(key): return 'feat_' + key for key in tqdm_notebook(keys): df[get_name_feat(key)] = df.features_parsed.map(lambda feats: feats[key] if key in feats else np.nan) # + id="bw0LC-J7WoZr" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 151} outputId="c434be1e-ef5b-4a04-c2dd-5fa75137aa19" executionInfo={"status": "ok", "timestamp": 1581695066836, "user_tz": -60, "elapsed": 589, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} df.columns # + id="bHV7MhUrX1_o" colab_type="code" colab={} keys_stat = {} for key in keys: keys_stat[key] = df[ False == df[get_name_feat(key)].isnull()].shape[0] / df.shape[0] * 100 # + id="Y3NXRjHTYD7_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 101} outputId="fe047450-2f8b-410b-97cd-666824c2fdc5" executionInfo={"status": "ok", "timestamp": 1581695761296, "user_tz": -60, "elapsed": 564, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} {k:v for k,v in keys_stat.items() if v > 30} # + id="-ZCz_kTaaKRS" colab_type="code" colab={} df[ 'feat_brand_cat' ] = df[ 'feat_brand' ].factorize()[0] df[ 'feat_color_cat' ] = df[ 'feat_color' ].factorize()[0] df[ 'feat_gender_cat' ] = df[ 'feat_gender' ].factorize()[0] df[ 'feat_manufacturer part number_cat' ] = df[ 'feat_manufacturer part number' ].factorize()[0] df[ 'feat_material_cat' ] = df[ 'feat_material' ].factorize()[0] df[ 'feat_sport_cat' ] = df[ 'feat_sport' ].factorize()[0] df[ 'feat_style_cat' ] = df[ 'feat_style' ].factorize()[0] for key in keys: df[ get_name_feat(key) + '_cat' ] = df[get_name_feat(key)].factorize()[0] # + id="FZPv-uTybidf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f14eef12-3399-49b0-a620-00702d970cd1" executionInfo={"status": "ok", "timestamp": 1581696441097, "user_tz": -60, "elapsed": 600, "user": {"displayName": "Miros\u01<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} df['brand'] = df['brand'].map(lambda x: str(x).lower()) df[ df.brand == df.feat_brand ].shape # + id="h2UjHZYadLCB" colab_type="code" colab={} feats = [''] # + id="g_07Reo3awuw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="28706ff8-217a-4d1c-f4fc-48ca2843e706" executionInfo={"status": "ok", "timestamp": 1581696515337, "user_tz": -60, "elapsed": 3795, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} model = RandomForestRegressor(max_depth=5, n_estimators=100) run_model(['brand_cat'], model) # + id="A54BM-Wfh9a2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="e8afd6e6-e2b4-45a5-a9a3-06807f2cac02" executionInfo={"status": "ok", "timestamp": 1581697778638, "user_tz": -60, "elapsed": 546, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} feats_cat = [x for x in df.columns if 'cat' in x] feats_cat # + id="JWQQdyvDdV7o" colab_type="code" colab={} model = RandomForestRegressor(max_depth=5, n_estimators=100) feats = ['brand_cat', 'feat_metal type_cat', 'feat_shape_cat', 'feat_brand_cat', 'feat_gender_cat', 'feat_material_cat', 'feat_style_cat', 'feat_sport_cat'] # feats += feats_cat # feats = list(set(feats)) result = run_model(feats, model) # + id="Pw1XiAQ3dvM3" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 185} outputId="eaf5abe8-43c4-44cd-f539-02cce3f1f637" executionInfo={"status": "ok", "timestamp": 1581698568118, "user_tz": -60, "elapsed": 4487, "user": {"displayName": "Miros\u014<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} X = df[feats].values y = df['prices_amountmin'].values m = RandomForestRegressor(max_depth=5, n_estimators=100, random_state=0) m.fit(X, y) print(result) perm = PermutationImportance(m, random_state=1).fit(X, y) eli5.show_weights(perm, feature_names=feats) # + id="SSmFLtexespn" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 218} outputId="4512e497-d6c6-4a42-c7da-d1919573b5fb" executionInfo={"status": "ok", "timestamp": 1581697025363, "user_tz": -60, "elapsed": 577, "user": {"displayName": "Miros\u<NAME>\u00f3zefiak", "photoUrl": "", "userId": "00550314913693754411"}} df['brand'].value_counts(normalize=True) # + id="k8JBOCOTfOIE" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 121} outputId="a9b87e42-0041-42a6-f3c4-a0ab1aeb631b" executionInfo={"status": "ok", "timestamp": 1581697418573, "user_tz": -60, "elapsed": 565, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} df[ df['brand'] == 'nike'].features_parsed.sample(5).values # + id="InKa8r5-fdXV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 286} outputId="950e7640-6057-443a-8b33-c4b98d74cba9" executionInfo={"status": "ok", "timestamp": 1581697508910, "user_tz": -60, "elapsed": 385, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} df[ 'feat_age group'].value_counts() # + id="346sYcuAhKQ4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 319} outputId="9acb4e20-0d20-4bfc-c92a-11dc84397054" executionInfo={"status": "ok", "timestamp": 1581698637202, "user_tz": -60, "elapsed": 2039, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00550314913693754411"}} # !git status # + id="TpdZf_VSlVW4" colab_type="code" colab={} # !git add da
day5.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python (py27_pyro) # language: python # name: py27 # --- # + # %matplotlib inline import matplotlib.pyplot as plt import numpy as np import torch from matplotlib import animation, rc from IPython.display import HTML x_gen = np.random.randn(100)*0.2 + 0.5 plt.scatter(x_gen, x_gen*0) # + x_gen_ad = torch.tensor(x_gen, requires_grad=False) theta = torch.tensor([0.0, 1.0], dtype=x_gen_ad.dtype, requires_grad=True) losses = [] thetas = [] for k in range(100): p = torch.distributions.Normal(theta[0], theta[1]) loss = torch.mean(p.log_prob(x_gen_ad)) loss.backward() losses.append(loss.item()) thetas.append(theta.detach().numpy().copy()) with torch.no_grad(): theta += 0.01 * theta.grad theta.grad.zero_() fig = plt.figure() ax = plt.gca() def gaussian(x, mu, sig): return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))) def animate(i): ax.clear() ax.scatter(x_gen, x_gen*0 + 0.5) ax.plot(np.linspace(-1., 2.0, 100), gaussian(np.linspace(0.0, 1.0, 100),thetas[i][0], thetas[i][1]), "r--") plt.xlim(-0.5, 1.5) plt.ylim(0., 1.) plt.title("Mean=%02.2f, var=%02.2f" % (thetas[i][0], thetas[i][1])) return ax anim = animation.FuncAnimation(fig, animate, frames=len(losses), interval=100, repeat=True) HTML(anim.to_html5_video()) # + x_gen = np.random.randn(100)*0.2 + 0.5 x_gen_ad = torch.tensor(x_gen, requires_grad=False) theta = torch.tensor([0.0, 1.0], dtype=x_gen_ad.dtype, requires_grad=True) for k in range(100): p = torch.distributions.Normal(theta[0], theta[1]) loss = torch.mean(p.log_prob(x_gen_ad)) loss.backward() with torch.no_grad(): theta += 0.01 * theta.grad theta.grad.zero_() # + # Set up a dist theta = torch.tensor([0.0, 1.0], requires_grad=True) p = torch.distributions.Normal(theta[0], theta[1]) print(theta, p) theta.grad = None err = p.log_prob(0.1) err.backward(retain_graph=True) print(theta.grad) theta.grad = None err = p.log_prob(0.1) err.backward(retain_graph=True) print(theta.grad)
notebooks/20190301_quick_max_evidence_opt_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import tensorflow as tf import numpy as np from tensorflow.keras import backend as K from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten # ### Binary Classification with sigmoid activation function # # Suppose we are training a model for a binary classification problem with a sigmoid activation function. # # Given a training example with input $x^{(i)}$, the model will output a float between 0 and 1. Based on whether this float is less than or greater than our "threshold" (which by default is set at 0.5), we round the float to get the predicted classification $y_{pred}$ from the model. # # The accuracy metric compares the value of $y_{pred}$ on each training example with the true output, the one-hot coded vector $y_{true}^{(i)}$ from our training data. # # Let $$\delta(y_{pred}^{(i)},y_{true}^{(i)}) = \begin{cases} 1 & y_{pred}=y_{true}\\ # 0 & y_{pred}\neq y_{true} \end{cases}$$ # # The accuracy metric computes the mean of $\delta(y_{pred}^{(i)},y_{true}^{(i)})$ over all training examples. # # $$ accuracy = \frac{1}{N} \sum_{i=1}^N \delta(y_{pred}^{(i)},y_{true}^{(i)}) $$ # # This is implemented in the backend of Keras as follows. # # + y_true = tf.constant([0.0, 1.0, 1.0]) y_pred = tf.constant([0.4, 0.7, 0.3]) accuracy = K.mean(K.equal(y_true, K.round(y_pred))) accuracy # - # ### Categorical Classification # # Now suppose we are training a model for a classification problem which should sort data into $m>2$ different classes using a softmax activation function in the last layer. # # Given a training example with input $x^{(i)}$, the model will output a tensor of probabilities $p_1, p_2, \dots p_m$, giving the likelihood (according to the model) that $x^{(i)}$ falls into each class. # # The accuracy metric works by determining the largest argument in the $y_{pred}^{(i)}$ tensor, and compares its index to the index of the maximum value of $y_{true}^{(i)}$ to determine $\delta(y_{pred}^{(i)},y_{true}^{(i)})$. It then computes the accuracy in the same way as for the binary classification case. # # $$ accuracy = \frac{1}{N} \sum_{i=1}^N \delta(y_{pred}^{(i)},y_{true}^{(i)}) $$ # # In the backend of Keras, the accuracy metric is implemented slightly differently depending on whether we have a binary classification problem ($m=2$) or a categorical classifcation problem. Note that the accuracy for binary classification problems is the same, no matter if we use a sigmoid or softmax activation function to obtain the output. # # + # Binary classification with softmax y_true = tf.constant([[0.0,1.0],[1.0,0.0],[1.0,0.0],[0.0,1.0]]) y_pred = tf.constant([[0.4,0.6], [0.3,0.7], [0.05,0.95],[0.33,0.67]]) accuracy = K.mean(K.equal(y_true, K.round(y_pred))) accuracy # Categorical classification with m>2 y_true = tf.constant([[0.0,1.0,0.0,0.0],[1.0,0.0,0.0,0.0],[0.0,0.0,1.0,0.0]]) y_pred = tf.constant([[0.4,0.6,0.0,0.0], [0.3,0.2,0.1,0.4], [0.05,0.35,0.5,0.1]]) accuracy = K.mean(K.equal(K.argmax(y_true, axis=-1), K.argmax(y_pred, axis=-1))) accuracy # - # ### Implementing Activation Functions with Numpy: # # #### Sigmoid Activation Function: # # Using a mathematical definition, the sigmoid function takes any range real number and returns the output value which falls in the range of 0 to 1. Based on the convention, the output value is expected to be in the range of -1 to 1. The sigmoid function produces an “S” shaped curve. Mathematically, sigmoid is represented as: # # $$ f (x) = \frac{\mathrm{1} }{\mathrm{1} + e^- x } $$ # # # <p align="center"> # <img src=assets/sigmoid.png/> # </p> # # ##### Properties of the Sigmoid Function: # # - The sigmoid function takes in real numbers in any range and returns a real-valued output. # - The first derivative of the sigmoid function will be non-negative (greater than or equal to zero) or non-positive (less than or equal to Zero). # - It appears in the output layers of the Deep Learning architectures, and is used for predicting probability based outputs and has been successfully implemented in binary classification problems, logistic regression tasks as well as other neural network applications. class Sigmoid(): def __call__(self, x): return (1/ 1+np.exp(-x)) def gradient(self, x): return self.__call__(x) * (1 - self.__call__(x)) # + x = np.arange(-10, 10, 0.2) y = Sigmoid() y(x) # - # #### Softmax Activation Function: # # The Softmax function is used for prediction in multi-class models where it returns probabilities of each class in a group of different classes, with the target class having the highest probability. The calculated probabilities are then helpful in determining the target class for the given inputs. Mathematically, softmax is represented as: # # $$ softmax(x)_i = \frac{exp(x_i)}{\sum_{j}^{ }exp(x_j))} $$ # # ##### What does the Softmax function look like? # # Assume that you have values from $x_1, x_2, \ldots, x_k$. The Softmax function for these values would be: # # $\ln{\sum_{i=1}^k e^{x_i}}$ # # ##### What is the Softmax function doing? # # *It is approximating the max function*. Can you see why? Let us call the largest $x_i$ value $x_{max}.$ Now, we are taking exponential so $e^{x_{max}}$ will be much larger than any $e^{x_i}$. # # $\ln{\sum_{i=0}^k e^{x_i}} \approx \ln e^{x_{max}}$ # $\ln{\sum_{i=0}^k e^{x_i}} \approx x_{max}$ # # Look at the below graph for a comparison between max(0, x)(red) and softmax(0, x)(blue). # # <p align="center"> # <img src=assets/softmax.png/ height="600px" width="600px"> # </p> # # ##### Why is it called Softmax? # # * It is an approximation of Max. # * It is a *soft/smooth* approximation of max. Notice how it approximates the sharp corner at 0 using a smooth curve. # # ##### What is the purpose of Softmax? # # Softmax gives us the [differentiable](https://en.wikipedia.org/wiki/Differentiable_function) approximation of a [non-differentiable](https://math.stackexchange.com/questions/1329252/is-max0-x-a-differentiable-function) function max. Why is that important? **For optimizing models, including machine learning models, it is required that functions describing the model be differentiable. So if we want to optimize a model which uses the max function then we can do that by replacing the max with softmax.** # # # ##### But, What about the Softmax Activation Function name? # # Here are my guesses on why the Softmax Activation function has the word “Softmax” in it: # # * Softmax Activation function looks very similar to the Softmax function. Notice the denominator. $f(x_i)=\frac{e^{x_i}}{\sum_{i=0}^k e^{x_i}}$ # # * Softmax Activation function highlights the largest input and suppresses all the significantly [smaller ones](https://en.wikipedia.org/wiki/Softmax_function#Example) in certain conditions. In this way, it behaves similar to the softmax function. # # ##### Properties of the Softmax Function: # # - The Softmax function produces an output which is a range of values between 0 and 1, with the sum of the probabilities been equal to 1. # - The main difference between the Sigmoid and Softmax functions is that Sigmoid is used in binary classification while the Softmax is used for multi-class tasks. # # # [REFERENCES](https://medium.com/data-science-bootcamp/softmax-function-beyond-the-basics-51f09ce11154) # + class Softmax(): def __call__(self, x): return np.exp(x)/np.sum(np.exp(x), axis = 1, keepdims=True) def gradient(self, x): p = self.__call__(x) return p * (1-p) # Taking care of numerical stability """ def softmax(x): # Compute softmax values for each sets of scores in x. e_x = np.exp(x - np.max(x)) return e_x / e_x.sum() """ # - x = np.array([0.3, 0.7, 0.9]) x2 = np.array([[1, 2, 3, 6], # sample 1 [2, 4, 5, 6], # sample 2 [1, 2, 3, 6]]) # sample 1 again(!) y = Softmax() y(x2) # #### ReLu Activation Function: # # The Rectified linear unit (ReLu) activation function has been the most widely used activation function for deep learning applications with state-of-the-art results. It usually achieves better performance and generalization in deep learning compared to the sigmoid activation function. # # $$ f (x) = max(x, 0) $$ # # <p align="center"> # <img src=assets/relu.png/ height="600px" width="600px"> # </p> # # **Nature** :- Non-linear, which means we can easily backpropagate the errors and have multiple layers of neurons being activated by the ReLU function. # # **Uses** :- ReLu is less computationally expensive than tanh and sigmoid because it involves simpler mathematical operations. At a time only a few neurons are activated making the network sparse making it efficient and easy for computation. # # **It avoids and rectifies vanishing gradient problem.** Almost all deep learning Models use ReLu nowadays. # But its limitation is that it should only be used within Hidden layers of a Neural Network Model. # # Another problem with ReLu is that **ReLU units can be fragile during training and can "die".** For example, a large gradient flowing through a ReLU neuron could cause the weights to update in such a way that the neuron will never activate on any datapoint again. If this happens, then the gradient flowing through the unit will forever be zero from that point on. That is, the ReLU units can irreversibly die during training since they can get knocked off the data manifold. For example, you may find that as much as 40% of your network can be "dead" (i.e. neurons that never activate across the entire training dataset) if the learning rate is set too high. With a proper setting of the learning rate this is less frequently an issue. # # To fix this problem another modification was introduced called **Leaky ReLu** to fix the problem of dying neurons. It introduces a small slope to keep the updates alive. # # The leak helps to increase the range of the ReLU function. Usually, the value of alpha is 0.01 or so. # # **When a is not 0.01 then it is called Randomized ReLU.** # # Therefore the range of the Leaky ReLU is (-infinity to infinity). # # Both Leaky and Randomized ReLU functions are monotonic(A function which is either entirely non-increasing or non-decreasing.) in nature. Also, their derivatives also monotonic in nature. # # <p align="center"> # <img src=assets/lrelu.png/ height="600px" width="600px"> # </p> class ReLu: def __call__(self, x): return np.where(x>=0, x, 0) def gradient(self, x): return np.where(x>=0, 1, 0) # + z = np.random.uniform(-1, 1, (3,3)) relu = ReLu() relu(z) # - class Leaky_ReLu: def __init__(self, alpha = 0.01): self.alpha = alpha def __call__(self, x): return np.where(x>=0, x, self.alpha*x) def gradient(self, x): return np.where(x>=0, 1, self.alpha) # + z = np.random.uniform(-1, 1, (3,3)) lrelu = Leaky_ReLu() lrelu(z) # - # #### Tanh Activation Function: # # tanh is also like logistic sigmoid but better. The range of the tanh function is from (-1 to 1). tanh is also sigmoidal (s - shaped). # # # <p align="center"> # <img src=assets/tanh_formula.jpg/> # </p> # # ### Tanh also suffers from Vanishing Gradient Problem # <p align="center"> # <img src=assets/tanh.jpg/> # </p> # # <p align="center"> # <img src=assets/tanh_and_gradient.jpg/> # </p> # class TanH(): def __call__(self, x): return 2 / (1 + np.exp(-2*x)) - 1 def gradient(self, x): return 1 - np.power(self.__call__(x), 2) # + z = np.random.uniform(-1, 1, (3,3)) tanh = TanH() tanh(z) # - # ### Other Metrics # # #### Crossentropy Loss: # # <p align="center"> # <img src=assets/CE_loss.png/ height="600px" width="600px"> # </p> # # # **NOTE** : # - Also see [Kullback-Leibler Divergence](https://www.countbayesie.com/blog/2017/5/9/kullback-leibler-divergence-explained) [Very often in Probability and Statistics we'll replace observed data or a complex distributions with a simpler, approximating distribution. KL Divergence helps us to measure just how much information we lose when we choose an approximation.] (which explains how the formula for CE originated) # - [Cross-Entropy explained qualitatively](https://stats.stackexchange.com/questions/80967/qualitively-what-is-cross-entropy) # - [Shannon's entropy](https://stats.stackexchange.com/questions/87182/what-is-the-role-of-the-logarithm-in-shannons-entropy/87194#87194) # - [Bayesian Surprise and Maximum Entropy Distribution](https://stats.stackexchange.com/questions/66186/statistical-interpretation-of-maximum-entropy-distribution/245198#245198) # - [Intuition on the Kullback-Leibler (KL) Divergence](https://stats.stackexchange.com/questions/188903/intuition-on-the-kullback-leibler-kl-divergence/189758#189758) # # ##### Multi-Class Classification: # # One-of-many classification. Each sample can belong to ONE of $ C $ classes. The CNN will have $C$ output neurons that can be gathered in a vector $s$ (Scores). The target (ground truth) vector $t$ will be a one-hot vector with a positive class and $C - 1$ negative classes. # This task is treated as a single classification problem of samples in one of $C$ classes. # # ##### Multi-Label Classification: # # Each sample can belong to more than one class. The CNN will have as well $C$ output neurons. The target vector $t$ can have more than a positive class, so it will be a vector of 0s and 1s with $C$ dimensionality. # This task is treated as $C$ different binary (C’ = 2, t’ = 0) or (t’ = 1) and independent classification problems, where each output neuron decides if a sample belongs to a class or not. # # <p align="center"> # <img src=assets/multiclass_multilabel.png height="600px" width="600px"> # </p> # # The Cross-Entropy Loss can be defined as: # # $$ CE = -\sum_{i}^{C}t_{i} log (s_{i}) $$ # # Where $t_i$ and $s_i$ are the groundtruth and the CNN score for each class _i_ in $C$. As **usually an activation function (Sigmoid / Softmax) is applied to the scores before the CE Loss computation**, we write $f(s_i)$ to refer to the activations. # # In a **binary classification problem**, where C’ = 2, the Cross Entropy Loss can be defined also as: # # $$CE = -\sum_{i=1}^{C'=2}t_{i} log (s_{i}) = -t_{1} log(s_{1}) - (1 - t_{1}) log(1 - s_{1})$$ # # where it’s assumed that there are two classes: $C_1$ and $C_2$. $t_1$ [0,1] and $s_1$ are the groundtruth and the score for $C_1$, and $t_2 = 1 - t_1$ and $s_2 = 1 - s_1$ are the groundtruth and the score for $C_2$. That is the case when we split a Multi-Label classification problem in $C$ binary classification problems. See next Binary Cross-Entropy Loss section for more details. # # # **Logistic Loss** and **Multinomial Logistic Loss** are other names for **Cross-Entropy loss**. # # ### Categorical Cross-Entropy Loss: # # <p align="center"> # <img src=assets/softmax_CE_pipeline.png height="600px" width="600px"> # </p> # # Also called **Softmax Loss**. It is a **Softmax activation** plus a **Cross-Entropy loss**. If we use this loss, we will train a CNN to output a probability over the $C$ classes for each image. It is used for multi-class classification. # # In the specific (and usual) case of Multi-Class classification the labels are one-hot, so only the positive class $C_p$ keeps its term in the loss. There is only one element of the Target vector $t$ which is not zero $t_i = t_p$. So discarding the elements of the summation which are zero due to target labels, we can write: # # $$ CE = -log\left ( \frac{e^{s_{p}}}{\sum_{j}^{C} e^{s_{j}}}\right ) $$ # # where **Sp** is the CNN score for the positive class. # # ### Binary Cross-Entropy Loss: # # Also called **Sigmoid Cross-Entropy loss**. It is a **Sigmoid activation** plus a **Cross-Entropy loss**. Unlike **Softmax loss** it is independent for each vector component (class), meaning that the loss computed for every CNN output vector component is not affected by other component values. That’s why it is used for **multi-label classification**, were the insight of an element belonging to a certain class should not influence the decision for another class. # # <p align="center"> # <img src=assets/sigmoid_CE_pipeline.png height="600px" width="600px"> # </p> # # # It’s called **Binary Cross-Entropy Loss** because it sets up a binary classification problem between C’=2 classes for every class in $C$, as explained above. So when using this Loss, the formulation of **Cross Entropy Loss** for binary problems is often used: # # $$CE = -\sum_{i=1}^{C'=2}t_{i} log (f(s_{i})) = -t_{1} log(f(s_{1})) - (1 - t_{1}) log(1 - f(s_{1}))$$ # # This would be the pipeline for each one of the $C$ clases. We set $C$ independent binary classification problems C'=2. Then we sum up the loss over the different binary problems: We sum up the gradients of every binary problem to backpropagate, and the losses to monitor the global loss. $s_1$ and $t_1$ are the score and the gorundtruth label for the class $C_1$, which is also the class $C_i$ in $C$. $s_2 = 1 - s_1$ and $t_2 = 1 - t_1$ are the score and the groundtruth label of the class $C_2$, which is not a “class” in our original problem with $C$ classes, but a class we create to set up the binary problem with $C_1 = C_i$. We can understand it as a background class. # # The loss can be expressed as: # # $$CE = \left\{\begin{matrix} & - log(f(s_{1})) & & if & t_{1} = 1 \\ & - log(1 - f(s_{1})) & & if & t_{1} = 0 \end{matrix}\right.$$ # # where $t_1 = 1$ means that the class $C_1 = C_i$ is positive for this sample. # # + def binary_cross_entropy_loss(outputs, targets, epsilon=1e-12): """ The outputs should be in range [0,1] """ # Prevents overflow outputs = np.clip(outputs, epsilon, 1-epsilon) return np.mean(-np.sum(targets * np.log(outputs) + (1-targets) * np.log(1-outputs)), axis=1) def softmax_categorical_cross_entropy_loss(outputs, targets, epsilon=1e-12): """ The outputs should be in range [0,1] """ # Prevents overflow outputs = np.clip(outputs, epsilon, 1-epsilon) return np.mean(-np.sum(targets * np.log(outputs)), axis=1) # - # ### Sparse categorical accuracy # # This is a very similar metric to categorical accuracy with one major difference - the label $y_{true}$ of each # training example is not expected to be a one-hot encoded vector, but to be a tensor consisting of a single integer. # This integer is then compared to the index of the maximum argument of # $y_{pred}$ to determine $\delta(y_{pred}^{(i)},y_{true}^{(i)})$. # + #Two examples of compiling a model with a sparse categorical accuracy metric. # Build the model model = Sequential([ Flatten(input_shape=(28,28)), Dense(32, activation='relu'), Dense(32, activation='tanh'), Dense(10, activation='softmax'), ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=["sparse_categorical_accuracy"]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) # - # ### (Sparse) Top $k$-categorical accuracy: # # In top $k$-categorical accuracy, instead of computing how often the model correctly predicts the label of a training example, the metric computes how often the model has $y_{true}$ in the top $k$ of its predictions. By default, $k=5$. # # As before, the main difference between top $k$-categorical accuracy and its sparse version is that the former assumes $y_{true}$ is a one-hot encoded vector, whereas the sparse version assumes $y_{true}$ is an integer. # + # Compile a model with a top-k categorical accuracy metric with default k (=5) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=["top_k_categorical_accuracy"]) # + # Specify k instead with the sparse top-k categorical accuracy model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=[tf.keras.metrics.SparseTopKCategoricalAccuracy(k=3)]) # -
ML-practice/Metrics in Keras/Metrics_tf2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Load Data and visualization import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable from torchvision import transforms import h5py import copy import time # print(torch.__version__) file_name = "../data/CIFAR10.hdf5" data = h5py.File(file_name, "r") # get metadata for data: [n for n in data.keys()] x_train = np.float32(data["X_train"][:]).reshape(-1, 3, 32, 32) y_train = np.int32(np.array(data["Y_train"])) x_test = np.float32(data["X_test"][:]).reshape(-1, 3, 32, 32) y_test = np.int32(np.array(data["Y_test"])) data.close() x_train.shape, y_train.shape, x_test.shape, y_test.shape import matplotlib.pyplot as plt classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] samples_per_class = 5 for y, cls in enumerate(classes): idxs = np.flatnonzero(y_train == y) idxs = np.random.choice(idxs, samples_per_class, replace=False) for i, idx in enumerate(idxs): plt_idx = i * len(classes) + y + 1 plt.subplot(samples_per_class, len(classes), plt_idx) plt.imshow(x_train[idx].transpose(1,2,0)) plt.axis('off') if i == 0: plt.title(cls) plt.show() # ## Data Agumentation - vertical / horizontal flip def random_flip(x_train,y_train,portion=0.5, direction=2): """ portion: portion of sample in x_train get flipped direction: 2 - horizontal 1 - vertical """ all_index = x_train.shape[0] idx = np.random.choice(all_index, np.int(portion*all_index), replace=False) new = copy.deepcopy(x_train) new[idx,[0],:,:] = np.flip(new[idx,[0],:,:],direction) new[idx,[1],:,:] = np.flip(new[idx,[1],:,:],direction) new[idx,[2],:,:] = np.flip(new[idx,[2],:,:],direction) #new = torch.from_numpy(new) return y_train, new label, new = random_flip(x_train[[0]],y_train[0],portion=1, direction = 1) plt.imshow(new[0].transpose(1,2,0)) plt.show() # ## Model Architecture class CNN_torch(nn.Module): def __init__(self): super(CNN_torch, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=4, stride=1, padding=2, bias=True) self.batch_norm1 = nn.BatchNorm2d(num_features=64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) self.conv2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4, stride=1, padding=2, bias=True) self.conv3 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4, stride=1, padding=2, bias=True) self.batch_norm2 = nn.BatchNorm2d(num_features=64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) self.conv4 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4, stride=1, padding=2, bias=True) self.conv5 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4, stride=1, padding=2, bias=True) self.batch_norm3 = nn.BatchNorm2d(num_features=64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) self.conv6 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=0, bias=True) self.conv7 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=0, bias=True) self.batch_norm4 = nn.BatchNorm2d(num_features=64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) self.conv8 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=0, bias=True) self.batch_norm5 = nn.BatchNorm2d(num_features=64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) self.fc1 = nn.Linear(64 * 4 * 4, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): #print("con0: x shape{}".format(x.shape)) x = F.relu(self.conv1(x)) #print("con1: x shape{}".format(x.shape)) x = self.batch_norm1(x) x = F.relu(self.conv2(x)) #print("con2: x shape{}".format(x.shape)) x = F.dropout2d(F.max_pool2d(x, kernel_size=2, stride=2), p=0.25) #print("maxpool1: x shape{}".format(x.shape)) x = F.relu(self.conv3(x)) #print("con3: x shape{}".format(x.shape)) x = self.batch_norm2(x) x = F.relu(self.conv4(x)) #print("con4: x shape{}".format(x.shape)) x = F.dropout2d(F.max_pool2d(x, kernel_size=2, stride=2), p=0.25) #print("maxpool2: x shape{}".format(x.shape)) x = F.relu(self.conv5(x)) #print("con5: x shape{}".format(x.shape)) x = self.batch_norm3(x) x = F.relu(self.conv6(x)) #print("con6: x shape{}".format(x.shape)) x = F.dropout2d(x, p=0.25) x = F.relu(self.conv7(x)) #print("con7: x shape{}".format(x.shape)) x = self.batch_norm4(x) x = F.relu(self.conv8(x)) #print("con8: x shape{}".format(x.shape)) x = self.batch_norm5(x) x = F.dropout2d(x, p=0.25) #print("final: x shape{}".format(x.shape)) x = x.view(-1, self.fc1.in_features) #print("flatten: x shape{}".format(x.shape)) x = self.fc1(x) x = self.fc2(x) return F.log_softmax(x, dim=1) model = CNN_torch() use_cuda = torch.cuda.is_available() if use_cuda: model.cuda() model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count())) cudnn.benchmark = True criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters()) batch_size = 100 num_epoch = 10 train_loss = []; train_accuracy_epcoh = [] # + # x_train = x_train[0:1000] # y_train = y_train[0:1000] # L_Y_train = len(y_train) # for epoch in range(num_epoch): # index_permutation = np.random.permutation(L_Y_train) # x_train = x_train[index_permutation, :] # y_train = y_train[index_permutation] # if np.random.uniform(0,1) < 0.5: # y_train_aug, x_train_aug = random_flip(x_train, y_train, portion=0.6, direction=np.random.randint(1,3)) # else: # y_train_aug, x_train_aug = y_train, x_train # x_train_aug = torch.from_numpy(x_train_aug) # train_accuracy = [] # for i in range(0, L_Y_train, batch_size): # x_train_batch = torch.FloatTensor(x_train_aug[i:i+batch_size, :]) # y_train_batch = torch.LongTensor(y_train_aug[i:i+batch_size]) # data, target = Variable(x_train_batch), Variable(y_train_batch) # optimizer.zero_grad() # output = model(data) # loss = F.nll_loss(output, target) # loss.backward() # if torch.__version__ == '0.4.1': # train_loss.append(loss.item())#loss.data[0] version conflict # else: # train_loss.append(loss.data[0]) # # update parameters # optimizer.step() # prediction = output.data.max(1)[1] # accuracy = (float(prediction.eq(target.data).sum()) / float(batch_size)) # train_accuracy.append(accuracy) # accuracy_epcoh = np.mean(train_accuracy) # print(epoch+1, accuracy_epcoh) # # 1 0.225 # # 2 0.3 # # 3 0.377 # # 4 0.44499999999999995 # # 5 0.49000000000000005 # # 6 0.41899999999999993 # # 7 0.44000000000000006 # # 8 0.535 # # 9 0.654 # # 10 0.648 # - x_train = x_train[0:1000] y_train = y_train[0:1000] x_test = x_test[0:100] y_test = y_test[0:100] L_Y_train = len(y_train) L_Y_test = len(y_test) model.train() for epoch in range(num_epoch): index_permutation = np.random.permutation(L_Y_train) x_train = x_train[index_permutation, :] y_train = y_train[index_permutation] if np.random.uniform(0,1) < 0.5: y_train_aug, x_train_aug = random_flip(x_train, y_train, portion=0.6, direction=np.random.randint(1,3)) else: y_train_aug, x_train_aug = y_train, x_train x_train_aug = torch.from_numpy(x_train_aug) train_accuracy = [] for i in range(0, L_Y_train, batch_size): x_train_batch = torch.FloatTensor(x_train_aug[i:i+batch_size, :]) y_train_batch = torch.LongTensor(y_train_aug[i:i+batch_size]) if use_cuda: data, target = Variable(x_train_batch).cuda(), Variable(y_train_batch).cuda() else: data, target = Variable(x_train_batch), Variable(y_train_batch) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() if torch.__version__ == '0.4.1': train_loss.append(loss.item()) else: train_loss.append(loss.data[0]) # update parameters optimizer.step() prediction = output.data.max(1)[1] accuracy = (float(prediction.eq(target.data).sum()) / float(batch_size)) train_accuracy.append(accuracy) train_accuracy_epcoh.append(np.mean(train_accuracy)) print("Epoch: {} | Loss: {} | Accuracy::{}".format(epoch+1, train_loss[-1], train_accuracy_epcoh[-1])) model.eval() test_accuracy = [] for i in range(0, L_Y_test, batch_size): x_test_batch = torch.FloatTensor(x_test[i:i+batch_size, :]) y_test_batch = torch.LongTensor(y_test[i:i+batch_size]) if use_cuda: data, target = Variable(x_test_batch).cuda(), Variable(y_test_batch).cuda() else: data, target = Variable(x_test_batch), Variable(y_test_batch) output = model(data) loss = F.nll_loss(output, target) prediction = output.data.max(1)[1] accuracy = (float(prediction.eq(target.data).sum()) / float(batch_size)) test_accuracy.append(accuracy) accuracy_test = np.mean(test_accuracy) print("trained on [{}] epoch, with test accuracy [{}]".format(num_epoch, accuracy_test)) plt.plot(train_loss) plt.show() plt.plot(train_accuracy_epcoh) plt.show() torch.save(model, 'saved_model_state.pt')
Python_IE534/hw3/.ipynb_checkpoints/hw3-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Sex-related differences in the human microbiome using curatedMetagenomicData 3 and the python 3 language # <NAME>, (<EMAIL>) # This notebook contains the instructions to run a meta-analysis of sex-related contrasts in the human gut microbiome, using `curatedMetagenomicDataTerminal` and a set of freely-available python programs. If not running in docker, see the [installation instructions](installation.ipynb). # As described here, we are now going to # # 1. create a folder called `species_abundances_from_cMD3Terminal` # 2. go in that directory # 3. download all the taxonomic profiles using `curatedMetagenomicDataTerminal` # # Step 3 may take some time. # + language="bash" # # mkdir $HOME/species_abundances_from_cMD3Terminal # cd $HOME/species_abundances_from_cMD3Terminal # curatedMetagenomicData -m "*relative_abundance" # cd $HOME # - # The flag "-m" will attach the per-sample metadata available in curatedMetagenomicData 3 to their taxonomic profiles. # We now switch to a python 3 set of instructions that can be used to perform the main analysis of Figure 2, panel a, of the paper "***". # # The following instructions are meant as an example and also to clarify some aspect of the inner-code: the whole analysis is avaiable, as explained, via command-line programs at [https://github.com/waldronlab/curatedMetagenomicAnalyses/tree/main/python_tools] and can be all completed from the shell. # # ## Imports section # # So we must first import the basic modules to work with cMDTerminal in a meta-analytical way. Note: If your `python_modules` and `python_tools` directories are in a different location, correct the paths below. # + import os import sys sys.path.append(os.path.join(os.environ["HOME"], "curatedMetagenomicAnalyses/python_modules")) sys.path.append(os.path.join(os.environ["HOME"], "curatedMetagenomicAnalyses/python_tools")) import pandas as pd import numpy as np ## The following two modules handle either ## a meta-analysis based on a std. linear model ## OR a std. differential abundance analysis. ## This is useful as some biological questions are ## commonly explorable just in one dataset. from meta_analysis_runner import meta_analysis_with_linear_model from meta_analysis_runner import analysis_with_linear_model # - # ## Construction of the dataset # # Run the following code to see its help page. # + language="bash" # # python3 $HOME/curatedMetagenomicAnalyses/python_tools/meta_analysis_data.py -h # + ## The function `select` builds a dataset according to the requirements/constraints passed by the user. ## Now, the `select` function can be imported as a module and used: ## To to this, it is enough to pass it a dictionary of the parameters, ## as follows: from meta_analysis_data import select ## Following from the "Help" page, we next try to build ## a dataset to study the Sex-contrast in the healthy, human, gut microbiome: params = { 'input_folder': os.path.join(os.environ["HOME"], "species_abundances_from_cMD3Terminal"), "output_dataset": os.path.join(os.environ["HOME"], "a_dataset_for_the_sex_contrast_in_gut_species.tsv"), "min": ["age:16"], "max": [], "cat": ["study_condition:control", "body_site:stool"], "multiple": -1, "min_perc": ["gender:25"], "cfd":["BMI"], "iqr": [], "minmin": "gender:40", "study_identifier": "study_name", "verbose": False, "debug": False, "binary": [], "search": [], "exclude": [] } # - # These are the parameters that are needed to narrow this dataset. Normally, these are inserted via command-line, # but python is flexible on this. # # Now we write a dataset table: a dataset-table is meant here as a table with Samples as columns-ID, and metadata + features as index (row-names). Features are then distingushed from metadata based on the "feat-id" keyword. select(params) # Now, you should have saved a file named `a_dataset_for_the_sex_contrast_in_gut_species.tsv`. # # At June, 2021, this dataset should store 4007 sample-IDs (columns) + 1 column index. # The current dataset is not yet usable to perform a meta-analysis as the compositional # data returned by MetaPhlAn3 software are not recommended for work with most statistical methods. # # Among the transformation more often applied, there are the *Centered-Log-Ratio* (CLR) and the *arcsin-square-root* of # the relative-abundance-corresponding proportions. This last method is widely applied in meta-analyses on # microbiome-related questions as it considers equally all the zeros independent from the dataset. # # We thus will apply the arcsin-square root, but a utility script is currently available to apply both. Run the following code to read its help page. # + language="bash" # # python3 $HOME/curatedMetagenomicAnalyses/python_tools/apply_a_transform.py -h # + ## The general procedure to transform only the **features** ## in a dataset-merged-table is quite simple. ## We must first read the table we have created: sex_contrast_dataset = pd.read_csv(os.path.join(os.environ["HOME"], "a_dataset_for_the_sex_contrast_in_gut_species.tsv"), sep="\t", \ header=0, index_col=0, low_memory=False, engine="c").fillna("NA") ## We then identify it's features feats = [j for j in sex_contrast_dataset.index.tolist() if ("s__" in j)] ## We transform the data for sample in sex_contrast_dataset.columns.tolist(): sex_contrast_dataset.loc[feats, sample] = sex_contrast_dataset.loc[feats, sample].values.astype(float) sex_contrast_dataset.loc[feats, sample] /= np.sum(sex_contrast_dataset.loc[feats, sample].values) sex_contrast_dataset.loc[feats, sample] = np.arcsin(np.sqrt(\ sex_contrast_dataset.loc[feats, sample].values.astype(float))) ## Now that we have transformed the data we can save a table which is suitable for the analyses: sex_contrast_dataset.index.name = "sample_id" sex_contrast_dataset.to_csv(os.path.join(os.environ["HOME"], "a_dataset_for_the_sex_contrast_in_gut_species_arcsin.tsv"), sep="\t", \ header=True, index=True) # - # It's now time to use the dataset we have created to perform a meta-analysis. # The meta-analysis we'll perform is a standard meta-analysis (e.g. a weighted-average of several # effect-sizes, computed over several, independent populations). # # The effect-size will be in the class of the differences of means (Cohen's d) and will characterize # the difference between males and females (men and women). # # The only difference, with respect to a canonical paradigm of meta-analysis, is that we will extract, # each time, **the Cohen'd effect size from the sex-relative coefficient of an ordinary least squares (OLS) # model**. Beside being averaged over 15 populations, these effect-sizes will be so adjusted by age and by BMI # in addition. # # Now, the program allowing you to run directly the meta-analysis is called `metaanalyze.py`, and # asks for a short set of parameters in order to understand how to perform the desired meta-analysis. # # We will now run, **manually**, the basic steps of this program, in order to show them explicitly: # + ## First, we reproduce part of the program's import section from meta_analyses import paule_mandel_tau from meta_analyses import RE_meta_binary from meta_analyses import RE_meta ## we specify the important parameters outfile = "sex_4007_individuals_meta_analysis" heterogeneity = "PM" ## this corresponds to the default of the program study_id = "study_name" ## this is needed in order to segregate the populations type_of_analysis = "CLS" ## CLASSIFY (SEE AFTER) # - # We also need to specifiy a `formula` for the **model** that will be optimized before to compute the effect-size. # The model will be applied to all the features in `feats`. Given this, we don't have to specify the Y, but only the **X(s)**. # # The first X will be the main predictor, and the effect-sizes will be computed on that. # The following X will be used to adjuste the model. # # NOTE THAT: # 1) Though this is not needed for the main one, **categorical** covariates must be explicitly indicated via **C(name of c.)**. # # 2) Though the first variable is automatically detected as categorical (if `type_of_analysis == "CLS"`), we must # specify the **positive** and the **negative** direction of the analysis we are going to perform. formula = "gender + age + BMI" control_side, case_side = "female", "male" # We now can run the meta-analysis main module, `metaanalyze.py`. # The module can be run from command-line with a minimum parameters, provided that a suitable dataset has # been built. # # Run the following to view the help page for `metaanalyze.py`. # + language="bash" # # python3 $HOME/curatedMetagenomicAnalyses/python_tools/metaanalyze.py -h # - ma = meta_analysis_with_linear_model(\ sex_contrast_dataset, formula, \ study_id, \ feats, \ outfile + ".tsv", \ type_of_analysis, \ heterogeneity, \ pos=case_side, \ neg=control_side ) ma.random_effect_regression_model() # Now that we have computed a meta-analysis, we want to plot it. Meta-analyses and Metagenomics are both dealing # each with a problem of multidimensionality of the results, so coupling them requires to do our best to fit the # different layers of results in one figure. # # In particular, we can plot many forest-plots in a single figure with the script: `draw_figure_with_ma.py`. # Run the following to see its help page. # + language="bash" # # python3 $HOME/curatedMetagenomicAnalyses/python_tools/draw_figure_with_ma.py -h # - # In order to call the program from python, we have to prepare a dictionary, faking its command-line arguments. # Also, the program is able to plot several meta-analysis in the same set of axes, though we will for now # limit ourselves to the **basic usage**. # + figure_params = { "metaanalysis": [os.path.join(os.environ["HOME"], "sex_4007_individuals_meta_analysis.tsv")], "narrowed": True, "boxes": True, "relative_abundances": [os.path.join(os.environ["HOME"], "a_dataset_for_the_sex_contrast_in_gut_species.tsv")], "imp": 30, "how": "first", "positive_direction": "sex: male", "negative_direction": "sex: female", "x_axis": "standardized mean difference", "y_axis": "", "title": "meta-analysis of sex-related microbial species", "e_suff": ["_Effect"], "q_suff": ["_Qvalue"], "prevalence": [""], "min_prevalence": [0.01], "min_ab": [0.000], "min_studies": [4], "markers": False, "outfile": None, "random_effect": ["RE_Effect"], "confint": ["RE_conf_int"], "random_effect_q": ["RE_Effect_Qvalue"], "color_red": ["goldenrod"], "color_blue": ["dodgerblue"], "color_black": ["black"], "diam_marker": ["D"], "important_lines": [0.20], "a_single": 0.2, "a_random": 0.05, "dotsize": 9, "diamsize": 17, "neg_max_rho": 0.8, "pos_max_rho": 0.8, "legloc": "best" } ## We then import the main function from draw_figure_with_ma import draw_figure ## We run it draw_figure(figure_params, show=True)
vignettes/sexContrastMicrobiomeAnalysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from pds4_tools import pds4_read # to read and inspect the data and metadata import matplotlib.pyplot as plt # for plotting import matplotlib import numpy as np from PIL import Image # for plotting in Jupyter notebooks # %matplotlib notebook from skimage import exposure from skimage import data, img_as_float import colour from colour.plotting import * import glob from colour_demosaicing import ( demosaicing_CFA_Bayer_bilinear, demosaicing_CFA_Bayer_Malvar2004, demosaicing_CFA_Bayer_Menon2007, mosaicing_CFA_Bayer) cctf_encoding = colour.cctf_encoding colour.utilities.filter_warnings() # colour.utilities.describe_environment(); def read_pds(path): data = pds4_read(path, quiet=True) img = np.array(data[0].data) img = img_as_float(img) return img def debayer_img(img, CFA='RGGB'): # Menon2007 yields better edges than bilinear debayered = cctf_encoding(demosaicing_CFA_Bayer_Menon2007(img, CFA)) return debayered def stretch_img(img): p2, p98 = np.percentile(img, (2, 98)) img = exposure.rescale_intensity(img, in_range=(p2, p98)) return img def export_img(name, img): pil_img = Image.fromarray(np.uint8(img*255)) pil_img.save(name) # - from tqdm import tqdm # from p_tqdm import p_map # doesn't work well for p in tqdm(glob.glob('PCAM/*.*L')): try: img = read_pds(p) if img.shape == (1728, 2352): img = debayer_img(img) elif img.shape != (864, 1176): print(f'{p} has an unexpected dim') img = stretch_img(img) export_img(f"{p}.png", img) except: print(p) for p in tqdm(glob.glob('TCAM/*.*L')): try: img = read_pds(p) export_img(f"{p}.png", img) except: print(p) # + import os def extract_file_info(p): cam,_,ser = p.split('-') # CE4_GRAS_TCAM I 002_SCI_N_20190106033401_20190106033401_0004_A.2CL.png no,_,_,ts,te,ob,ver = ser.split('_') # 002 N N 20190106033401 20190106033401 0004 A.2CL.png ver = ver.split('.')[0] # A.2CL.png -> A cam = cam.split('_')[2] # TCAM return cam,no,ts,te,ob,ver def make_dir_if_n_exist(d): if not os.path.exists(d): os.makedirs(d) return d def make_new_name(no, ts, cam): return f"{no}-{ts}-{cam}.png" # + observations = {} CAM_DIR = 'TCAM' for p in glob.glob(f'{CAM_DIR}/*.png'): cam,no,ts,te,ob,ver = extract_file_info(p) if ob in observations: observations[ob].append(p) else: observations[ob] = [p] for k in observations.keys(): d = f"{CAM_DIR}/{k}" make_dir_if_n_exist(d) for p in observations[k]: cam,no,ts,te,ob,ver = extract_file_info(p) name = make_new_name(no, ts, cam) os.symlink(os.path.abspath(p), f"{d}/{name}") # + observations = {} CAM_DIR = 'PCAM' for p in glob.glob(f'{CAM_DIR}/*.png'): cam,no,ts,te,ob,ver = extract_file_info(p) if ob in observations: observations[ob].append(p) else: observations[ob] = [p] for k in observations.keys(): d = f"{CAM_DIR}/{k}" make_dir_if_n_exist(d) l_dir = make_dir_if_n_exist(f'{d}/PCAML') r_dir = make_dir_if_n_exist(f'{d}/PCAMR') for p in observations[k]: cam,no,ts,te,ob,ver = extract_file_info(p) name = make_new_name(no, ts, cam) os.symlink(f"../../{p}", f"{d}/{name}") if "PCAML" in p: os.symlink(os.path.abspath(p), f"{l_dir}/{name}") else: os.symlink(os.path.abspath(p), f"{r_dir}/{name}") # - # print observation time for k in observations.keys(): p = observations[k][0] cam,no,ts,te,ob,ver = extract_file_info(p) ob_date = datetime.strptime(ts, '%Y%m%d%H%M%S').strftime('%Y-%m-%d') print(f'{k} {ob_date}') os.rename(f'{CAM_DIR}/{k}', f'{CAM_DIR}/{k}_{ob_date}')
export.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Tutorial 1. Understanding Configuration File # + # Document Author: Dr. <NAME> # Author email: <EMAIL> # License: MIT # This tutorial is applicable for NAnPack version 1.0.0-alpha4 # - # For installation instructions, see [Installation](https://github.com/vxsharma-14/project-NAnPack/blob/main/docs/INSTALLATION.md) page. # The very first step to start using this package is to get familiar with the configuration file "config.ini". It is expected that the package users are familiar with the general terms, model equations etc. used in engineering simulations. # # The configuration file is used as a tool to set-up the scenario that is to be solved numerically. The file accepts several inputs that are required in the pre-processing and post-processing steps of the simulation. Although users may choose to define the inputs in the scripts that they will develop without having to use the config file, however, it is highly recommended to set-up the numerical experiments using this configuration file. By doing so, users, particularly the starters in CFD, will get an idea about what information they will require beforehand in their experimentation as well as they will be able to make the best use of this package. # # The structure of the config file includes the section name in square paranthesis [SECTION-NAME] and each section consists of key-value pairs in the format KEY = VALUE. The keys must not be changed by the user unless specified and user defined inputs must be specified in the value fields. # ### Section - [SETUP] # # **Provide the various experiment related description as inputs in this section.** # [SETUP] # # EXPID = xxxxxxxx-xx # UNITS_SYSTEM= BRITISH or SI # DESCRIPTION = enter short description # STATE = TRANSIENT or STEADY-STATE # MODEL = FO_WAVE # SCHEME = RUNGE-KUTTA # DIMENSION = 1D # ***'EXPID'***: Experiment ID- a unique ID that you can assign to your experiments. # # *I always prefer to include an ID for my records so that I can distinguish my experiment outputs from one another and for any changes I make in experiment set-up, I increment this ID number. Typically, an ID may be of the format MMDDYYYY-Serial No. There may be several usages of this id, such as users may make a folder using this ID and save the output with the associated configuration file in this folder and repeat this process for each experiment. Adopting a Unique ID assigning strategy in the experiments help in efficient record management which is very important when publishing data or for reproducibility.* # # ***'UNITS_SYSTEM'***: Mention the system of units used in the simulation. This field helps in keeping track of the unit and to stay consistent with the system. It is also wise to save the unit system for the records. # # ***'DESCRIPTION'***: Enter a short case description such as STEADY STATE HEAT CONDUCTION SIMULATION. Datatype = *string*. # # ***'STATE'***: Allowed inputs are STEADY-STATE or TRANSIENT. The field represents the state at which the results are desired. Depending on the case, a value must be entered. This is a required field to calculate several simulation parameters by the program setup. # # ***'MODEL'***: Classification of model equation. Allowed inputs are DIFFUSION, WAVE, FO_WAVE, VISC_BURGERS, INV_BURGERS. This field is required by the program setup. Please note that these model equations require only one dependent variable to be solved along X or along X and Y at each iteration level. # # ***'SCHEME'***: User may choose to specify the numerical method they will be using in the simulation. This field is optional in the current version. # # ***'DIMENSION'***: Allowed input 1D or 2D, depending on the simulation domain. This is required by the program setup. # ### Section - [DOMAIN] # # **The domain specification is entered in this section depending on 1D or 2D simulation.** # [DOMAIN] # # LENGTH = 400.0 # HEIGHT = 0.0 # ***'LENGTH'***: Length of the domain (along X axis). Value required. Datatype = *float*. # # ***'HEIGHT'***: Height of the domain (along Y axis). If DIMENSION = 2D, value required. Datatype = *float*. # ### Section - [MESH] # # **Provide the details for meshing in this section.** # [MESH] # # GRID_FROM_FILE? = NO # GRID_FNAME = none # GRID_AUTO_CALC? = YES # dX = 5.0 # dY = 0.05 # iMax = 0 # jMax = 0 # ***'GRID_FROM_FILE?'***: Read grid data from input file? This version does not support grid input through file, therefore keep the value as NO. # # ***'GRID_FNAME'***: Grid input file name. This field is used to enter the file name for the grid input. Since, we have specified GRID_FROM_FILE as NO, leave it as 'none'. # # ***'GRID_AUTO_CALC?'***: Auto-calculate grid points? Enter YES or NO. If mentioned YES, grid step size- (dX) or (dX, dY) must be entered and the program will auto-compute the grid points in the mesh. If mentioned NO, maximum grid points in the mesh- (iMax) or (iMax, jMAx) must be specified. For beginners, enter YES and specify dX, dY values. # # Datatype for dX, dY = *float*. # Datatype for iMax, jMax = *integer*. # # *Please note that the current version supports only uniform, finite difference grid in the simulation which is good for applications with rectangular, simply connected domain. Advanced techniques will be introduced in subsequent versions.* # ### Section - [IC] # # **Provide the option for the starting point (initial conditions) of the simulation.** # [IC] # # START_OPT = COLD-START # RESTART_FILE = none # ***'START_OPT'***: Starting option. Allowed inputs are COLD-START or RESTART. In the present version, only COLD-START feature is available which allows the user to start the simulation from zero initial values or using user developed subroutine for initial conditions. # # *RESTART conditions are useful when it is desired to start the simulation from the previously stored solution, for example, consider a scenario where your simulation ran for 24 hours or thousands of iterations without converging and your application crashed or reached a maximum limit of iterations, will it be efficient to run the simulation again from the beginning or by using previously stored solution as the starting point? Another scenario- starting a simulation from a converged solution to test something new will help in faster convergence.* # # ***'RESTART_FILE'***: Restart file name. File name for the program to read the stored solution. If START_OPT = COLD_START, leave it as none, otherwise specify the file name. # ### Section - [BC] # # **Provide the information whether to read the boundary conditions from a configuration file.** # [BC] # # BC_FROM_FILE? = NO # BC_FILE_NAME = none # ***'BC_FROM_FILE?'***: Read boundary conditions from file? Allowed inputs are YES or NO. First time users- enter NO. # # *There is a "bc.ini" file included in this package download, however, it is recommended to write a function to assign boundary conditions. There will be a separate tutorial on the boundary condition specification through "bc.ini" file.* # # ***'BC_FILE_NAME'***: Boundary condition input file name. If BC_FROM_FILE? = YES, the program will read the stored boundary conditions from file. If BC_FROM_FILE = NO, leave it as none. # ### Section - [CONST] # # **Provide the information to specify the constants in the model equations.** # [CONST] # # CFL = 1.0 # CONV = 250.0 # DIFF = 0.0 # *The program uses these constants to calculate coefficients in the finite difference approximations.* # # ***'CFL'***: In nanpack we use the term CFL to represents the constant coefficient in the finite difference formulation. (This is not a true definition of CFL though). # For a diffusion model, the program will treat the CFL as diffusion number to obtain time step size and in a wave equation or convection models, in general, the program will treat the CFL as the Courant number. The CFL must satisfy the corresponding stability requirement, otherwise, the solution will not converge or will fail when late time solutions are required. This is a required field. Datatype = *float*. # # ***'CONV'***: Convection coefficient. This is a required field for convection models such as WAVE equation. Datatype = *float*. # # ***'DIFF'***: Diffusion coefficient. This is a required field for diffusion models such as DIFFUSION equation. Datatype = *float*. # ### Section - [STOP] # # **Provide the information about stopping simulation.** # [STOP] # # SIM_TIME = 0.45 # CONV_CRIT = 0.01 # nMAX = 3000 # *It is always helpful to restrict the simulation time or iterations to terminate the program without crashing it. Consider a scenario when the solution has converged but it continues to solve the equations because the user did not set a break point and thus, the simulation has to be stopped somehow. Consider another scenario when you desire time-dependent solution but you have to do hand computations to calculate the required time-steps. Such scenarios can be avoided by specifying values in this section and let the program handle the termination process. # # ***'SIM_TIME'***: Simulation time, required field for time-dependent solution. Datatype = *float*. # # ***'CONV_CRIT'***: Convergence criteria, required field for steady-state solution. Datatype = *float*. # # ***'nMax'***: Maximum iterations/time levels to terminate the program if solution didn't converge. This is a required field. Datatype = *integer*. # ### Section - [OUTPUT] # # **Provide information about saving output or monitoring convergence.** # [OUTPUT] # # HIST_FILE_NAME = ./output/HISTfct1D.dat # RESTART_FNAME = none # RESULT_FNAME = ./output/fct1D.dat # WRITE_EVERY = 10 # DISPLAY_EVERY = 10 # SAVE_FOR_ANIM? = NO # SAVE_EVERY = 10 # SAVE_1D_OUTPUT? = YES # X = 0.2,0.4,0.6,0.8,1.0 # SAVE1D_FILENAME = ./output/fo-up1Dx.dat # ***'HIST_FILE_NAME'***: Convergence history file name. The convergence history will be stored in this file. This is required if the user wants to store convergence data. # # ***'RESTART_FNAME'***: File to create a restart point. This file may be used later when the user wants to restart the solution from the stored solution. This feature is not supported in the present version. # # ***'RESULT_FNAME'***: Output file name. The solution of the dependent variable will be stored in this file at each grid point locations within the domain. This is a required field. # # ***'WRITE_EVERY'***: Write solution file after every how many iterations? Datatype = *integer*. # # *For example, value = 10 means that the solution will be saved to files after every 10 iteration steps. This is a required field. To optimize the computational processing, use larger values depending on the problem.* # # ***'DISPLAY_EVERY'***: Write and display convergence history after every how many iterations? Datatype = *integer*. # # ***'SAVE_FOR_ANIM?'***: Save intermediate solutions in separate files for animation? Allowed inputs are YES or NO. This feature is not available in the current version, thus enter NO. # # ***'SAVE_EVERY'***: Save files for animation after every how many iterations? Datatype = *integer*. This field is required if SAVE_FOR_ANIM = YES. # # ***'SAVE_1D_OUTPUT'***: Save output in 1D format along X or Y in 2D simulation? Allowed inputs are YES or NO. # # *While validating numerical methods, it is important to plot line graphs to compare the output with the known analytical solution to benchmark the method. In such cases, plotting the colorful contour plots does not help and thus solution of the dependent variable along an axis is required, for example u(x=0.2, y) can be plotted to perform a detailed analysis. It is recommended to use this feature for 2D simulations.* # # ***'X'*** or ***'Y'***: This key must be changed based on direction of the nodes at which the 1D solution is desired to be saved. The values to the key are the X or Y locations. Datatype = *float*. # # *Example: If the user wants to save the solution for u at x = 0.2, 0.4, 0.6 locations such that u(x=0.2, y), u(x=0.4, y), u(x=0.6, y), type the key as X and the values as 0.2, 0.4, 0.6 (separated by ','). # Vice-versa, to save u(x, y=0.3), u(x,y=0.6), u(x, y=0.9), type the key as 'Y' and the values as 0.3, 0.6, 0.9.* # # ***'SAVE1D_FILENAME'***: 1D output file name. The solution of the dependent variable along the specified axis and locations will be stored in this file. This is required if SAVE_1D_OUTPUT = YES.
docs/build/html/examples/tutorial-01-understanding-config-file.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Tutorial on how to analyse Parcels output # This tutorial covers the format of the trajectory output exported by Parcels. **Parcels does not include advanced analysis or plotting functionality**, which users are suggested to write themselves to suit their research goals. Here we provide some starting points to explore the parcels output files yourself. # # * [**Reading the output file**](#Reading-the-output-file) # * [**Trajectory data structure**](#Trajectory-data-structure) # * [**Analysis**](#Analysis) # * [**Plotting**](#Plotting) # * [**Animations**](#Animations) # # First we need to create some parcels output to analyse. We simulate a set of particles using the setup described in the [Delay start tutorial](https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_delaystart.ipynb). from parcels import FieldSet, ParticleSet, JITParticle from parcels import AdvectionRK4 import numpy as np from datetime import timedelta as delta # + fieldset = FieldSet.from_parcels("Peninsula_data/peninsula", allow_time_extrapolation=True) npart = 10 # number of particles to be released lon = 3e3 * np.ones(npart) lat = np.linspace(3e3 , 45e3, npart, dtype=np.float32) time = np.arange(0, npart) * delta(hours=2).total_seconds() # release every particle two hours later pset = ParticleSet(fieldset=fieldset, pclass=JITParticle, lon=lon, lat=lat, time=time) output_file = pset.ParticleFile(name="Output.nc", outputdt=delta(hours=2)) pset.execute(AdvectionRK4, runtime=delta(hours=24), dt=delta(minutes=5), output_file=output_file) output_file.close() # export the trajectory data to a netcdf file # - # ## Reading the output file # ### Using the netCDF4 package # The [`parcels.particlefile.ParticleFile`](https://oceanparcels.org/gh-pages/html/#parcels.particlefile.ParticleFile) class creates a netCDF file to store the particle trajectories. It uses the [**`netCDF4` package**](https://unidata.github.io/netcdf4-python/netCDF4/index.html), which is also suitable to open and read the files for analysis. The [`Dataset` class](https://unidata.github.io/netcdf4-python/netCDF4/index.html#netCDF4.Dataset) opens a netCDF file in reading mode by default. Data can be accessed with the `Dataset.variables` dictionary which can return (masked) numpy arrays. # + import netCDF4 data_netcdf4 = netCDF4.Dataset('Output.nc') print(data_netcdf4) # - trajectory_netcdf4 = data_netcdf4.variables['trajectory'][:] time_netcdf4 = data_netcdf4.variables['time'][:] lon_netcdf4 = data_netcdf4.variables['lon'][:] lat_netcdf4 = data_netcdf4.variables['lat'][:] print(trajectory_netcdf4) # ### Using the xarray package # An often-used alternative to netCDF4, which also comes with the parcels installation, is [**xarray**](http://xarray.pydata.org/en/stable/index.html). Its labelled arrays allow for intuitive and accessible handling of data stored in the netCDF format. # + import xarray as xr data_xarray = xr.open_dataset('Output.nc') print(data_xarray) # - print(data_xarray['trajectory']) # ## Trajectory data structure # The data in the netCDF file are organised according to the [CF-conventions](http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#discrete-sampling-geometries) implemented with the [NCEI trajectory template](http://www.nodc.noaa.gov/data/formats/netcdf/v2.0/trajectoryIncomplete.cdl). The data is stored in a **two-dimensional array** with the dimensions **`traj`** and **`obs`**. Each particle trajectory is essentially stored as a time series where the coordinate data (**`lon`**, **`lat`**, **`time`**) are a function of the observation (`obs`). # # The output dataset used here contains **10 particles** and **13 observations**. Not every particle has 13 observations however; since we released particles at different times some particle trajectories are shorter than others. # + np.set_printoptions(linewidth=160) ns_per_hour = np.timedelta64(1, 'h') # nanoseconds in an hour print(data_xarray['time'].data/ns_per_hour) # time is stored in nanoseconds # - # Note how the first observation occurs at a different time for each trajectory. **`obs` != `time`** # ## Analysis # Sometimes, trajectories are analysed as they are stored: as individual time series. If we want to study the distance travelled as a function of time, the time we are interested in is the time relative to the start of the each particular trajectory: the array operations are simple since each trajectory is analysed as a function of **`obs`**. The time variable is only needed to express the results in the correct units. # + import matplotlib.pyplot as plt x = data_xarray['lon'].values y = data_xarray['lat'].values distance = np.cumsum(np.sqrt(np.square(np.diff(x))+np.square(np.diff(y))),axis=1) # d = (dx^2 + dy^2)^(1/2) real_time = data_xarray['time']/ns_per_hour # convert time to hours time_since_release = (real_time.values.transpose() - real_time.values[:,0]) # substract the initial time from each timeseries # + fig,(ax1,ax2) = plt.subplots(1,2,figsize=(10,4),constrained_layout=True) ax1.set_ylabel('Distance travelled [m]') ax1.set_xlabel('observation',weight='bold') d_plot = ax1.plot(distance.transpose()) ax2.set_ylabel('Distance travelled [m]') ax2.set_xlabel('time since release [hours]',weight='bold') d_plot_t = ax2.plot(time_since_release[1:],distance.transpose()) plt.show() # - # The two figures above show the same graph. Time is not needed to create the first figure. The time variable minus the first value of each trajectory gives the x-axis the correct units in the second figure. # # We can also plot the distance travelled as a function of the absolute time easily, since the `time` variable matches up with the data for each individual trajectory. plt.figure() ax= plt.axes() ax.set_ylabel('Distance travelled [m]') ax.set_xlabel('time [hours]',weight='bold') d_plot_t = ax.plot(real_time.T[1:],distance.transpose()) # ### Conditional selection # In other cases, the processing of the data itself however depends on the absolute time at which the observations are made, e.g. studying seasonal phenomena. In that case the array structure is not as simple: the data must be selected by their `time` value. Here we show how the mean location of the particles evolves through time. This also requires the trajectory data to be aligned in time. The data are selected using [`xr.DataArray.where()`](http://xarray.pydata.org/en/stable/generated/xarray.DataArray.where.html#xarray.DataArray.where) which compares the time variable to a specific time. This type of selecting data with a condition (`data_xarray['time']==time`) is a powerful tool to analyze trajectory data. # + # Using xarray mean_lon_x = [] mean_lat_x = [] timerange = np.arange(np.nanmin(data_xarray['time'].values), np.nanmax(data_xarray['time'].values)+np.timedelta64(delta(hours=2)), delta(hours=2)) # timerange in nanoseconds for time in timerange: if np.all(np.any(data_xarray['time']==time,axis=1)): # if all trajectories share an observation at time mean_lon_x += [np.nanmean(data_xarray['lon'].where(data_xarray['time']==time).values)] # find the data that share the time mean_lat_x += [np.nanmean(data_xarray['lat'].where(data_xarray['time']==time).values)] # find the data that share the time # - # Conditional selection is even easier in numpy arrays without the xarray formatting since it accepts the 2D boolean array that results from `time_netcdf4 == time` as a mask that you can use to directly select the data. # + # Using netCDF4 mean_lon_n = [] mean_lat_n = [] timerange = np.arange(np.nanmin(time_netcdf4), np.nanmax(time_netcdf4)+delta(hours=2).total_seconds(), delta(hours=2).total_seconds()) for time in timerange: if np.all(np.any(time_netcdf4 == time, axis=1)): # if all trajectories share an observation at time mean_lon_n += [np.mean(lon_netcdf4[time_netcdf4 == time])] # find the data that share the time mean_lat_n += [np.mean(lat_netcdf4[time_netcdf4 == time])] # find the data that share the time # - plt.figure() ax = plt.axes() ax.set_ylabel('Meridional distance [m]') ax.set_xlabel('Zonal distance [m]') ax.grid() ax.scatter(mean_lon_x,mean_lat_x,marker='^',label='xarray',s = 80) ax.scatter(mean_lon_n,mean_lat_n,marker='o',label='netcdf') plt.legend() plt.show() # ## Plotting # Parcels output consists of particle trajectories through time and space. An important way to explore patterns in this information is to draw the trajectories in space. Parcels provides the [`ParticleSet.show()`](https://oceanparcels.org/gh-pages/html/#parcels.particleset.ParticleSet.show) method and the [`plotTrajectoryFile`](https://oceanparcels.org/gh-pages/html/#module-scripts.plottrajectoriesfile) script to quickly plot at results, but users are encouraged to create their own figures, for example by using the comprehensive [**matplotlib**](https://matplotlib.org/) library. Here we show a basic setup on how to process the parcels output into trajectory plots and animations. # # Some other packages to help you make beautiful figures are: # * [**cartopy**](https://scitools.org.uk/cartopy/docs/latest/), a map-drawing tool especially compatible with matplotlib # * [**cmocean**](https://matplotlib.org/cmocean/), a set of beautiful colormaps # To draw the trajectory data in space usually it is informative to draw points at the observed coordinates to see the resolution of the output and draw a line through them to separate the different trajectories. The coordinates to draw are in `lon` and `lat` and can be passed to either `matplotlib.pyplot.plot` or `matplotlib.pyplot.scatter`. Note however, that the default way matplotlib plots 2D arrays is to plot a separate set for each column. In the parcels 2D output, the columns correspond to the `obs` dimension, so to separate the different trajectories we need to transpose the 2D array using `.T`. # + fig, (ax1,ax2,ax3,ax4) = plt.subplots(1,4,figsize=(16,3.5),constrained_layout=True) ###-Points-### ax1.set_title('Points') ax1.scatter(data_xarray['lon'].T,data_xarray['lat'].T) ###-Lines-### ax2.set_title('Lines') ax2.plot(data_xarray['lon'].T,data_xarray['lat'].T) ###-Points + Lines-### ax3.set_title('Points + Lines') ax3.plot(data_xarray['lon'].T,data_xarray['lat'].T,marker='o') ###-Not Transposed-### ax4.set_title('Not transposed') ax4.plot(data_xarray['lon'],data_xarray['lat'],marker='o') plt.show() # - # ### Animations # Trajectory plots like the ones above can become very cluttered for large sets of particles. To better see patterns, it's a good idea to create an animation in time and space. To do this, matplotlib offers an [animation package](https://matplotlib.org/3.3.2/api/animation_api.html). Here we show how to use the [`FuncAnimation`](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.animation.FuncAnimation.html#matplotlib.animation.FuncAnimation) class to animate parcels trajectory data. # # To correctly reveal the patterns in time we must remember that [the `obs` dimension does not necessarily correspond to the `time` variable](#Trajectory-data-structure). In the animation of the particles, we usually want to draw the points at each consecutive moment in time, not necessarily at each moment since the start of the trajectory. To do this we must [select the correct data](#Conditional-selection) in each rendering. # + from matplotlib.animation import FuncAnimation from IPython.display import HTML outputdt = delta(hours=2) timerange = np.arange(np.nanmin(data_xarray['time'].values), np.nanmax(data_xarray['time'].values)+np.timedelta64(outputdt), outputdt) # timerange in nanoseconds # + # %%capture fig = plt.figure(figsize=(5,5),constrained_layout=True) ax = fig.add_subplot() ax.set_ylabel('Meridional distance [m]') ax.set_xlabel('Zonal distance [m]') ax.set_xlim(0, 90000) ax.set_ylim(0, 50000) plt.xticks(rotation=45) time_id = np.where(data_xarray['time'] == timerange[0]) # Indices of the data where time = 0 scatter = ax.scatter(data_xarray['lon'].values[time_id], data_xarray['lat'].values[time_id]) t = str(timerange[0].astype('timedelta64[h]')) title = ax.set_title('Particles at t = '+t) def animate(i): t = str(timerange[i].astype('timedelta64[h]')) title.set_text('Particles at t = '+t) time_id = np.where(data_xarray['time'] == timerange[i]) scatter.set_offsets(np.c_[data_xarray['lon'].values[time_id], data_xarray['lat'].values[time_id]]) anim = FuncAnimation(fig, animate, frames = len(timerange), interval=500) # - HTML(anim.to_jshtml())
parcels/examples/tutorial_output.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- #Part1 -Arithmetic progression -the highest point of ball(probe) up #target area: x=211..232, y=-124..-69 sum_ar=123*(123+1)/2 print(sum_ar) # + #target area: x=211..232, y=-124..-69 #TEST: target area: x=20..30, y=-10..-5 target_area=[] canvas={} start=(0,0) xmin =20 xmax =30 ymax=-10 ymin=-5 for x in range(xmin,xmax+1): for y in range(ymax,ymin+1): target_area.append((x,y)) print(target_area) # + possible_V=[] for Vx in range(1,xmax+1): for Vy in range(ymax, -ymax): possible_V.append((Vx,Vy)) #print(possible_V) velocity_good=set() for vel in possible_V: x=0 y=0 Vx=vel[0] Vy=vel[1] while x<xmax and y>-10: # print(x,y,'step before') x=Vx+x y=Vy+y # print('Vx:', Vx, "Vy:", Vy, 'x,y:', (x,y)) if Vx>0: Vx-=1 elif Vx<0: Vx+=1 elif Vx==0: Vx=0 Vy-=1 if (x,y) in target_area: #print('IN TARGET: ',x,y) velocity_good.add((vel[0],vel[1])) break # - print(len(velocity_good)) print((velocity_good)) all_v={(23,-10),(25,-9),(27,-5),(29,-6),(22,-6),(21,-7),(9,0),(27,-7),(24,-5),(25,-7),(26,-6),(25,-5),(6,8),(11,-2),(20,-5),(29,-10),(6,3),(28,-7),(8,0),(30,-6),(29,-8),(20,-10),(6,7),(6,4),(6,1),(14,-4),(21,-6),(26,-10),(7,-1),(7,7),(8,-1), (21,-9),(6,2), (20,-7),(30,-10),(14,-3),(20,-8),(13,-2),(7,3),(28,-8),(29,-9),(15,-3),(22,-5),(26,-8),(25,-8),(25,-6),(15,-4),(9,-2),(15,-2),(12,-2),(28,-9),(12,-3),(24,-6),(23,-7),(25,-10),(7,8),(11,-3),(26,-7),(7,1),(23,-9),(6,0),(22,-10),(27,-6),(8,1),(22,-8),(13,-4),(7,6),(28,-6),(11,-4),(12,-4),(26,-9),(7,4),(24,-10),(23,-8),(30,-8),(7,0),(9,-1),(10,-1),(26,-5),(22,-9),(6,5),(7,5),(23,-6),(28,-10),(10,-2),(11,-1),(20,-9),(14,-2),(29,-7),(13,-3),(23,-5),(24,-8),(27,-9),(30,-7),(28,-5),(21,-10),(7,9),(6,6),(21,-5),(27,-10),(7,2),(30,-9),(21,-8),(22,-7),(24,-9),(20,-6),(6,9),(29,-5),(8,-2),(27,-8),(30,-5),(24,-7)} print((all_v-velocity_good)) print(len(all_v-velocity_good)) print(velocity_good-all_v) print(len(velocity_good-all_v)) # + #My part 2 #target area: x=211..232, y=-124..-69 #TEST: target area: x=20..30, y=-10..-5 target_area=[] canvas={} start=(0,0) xmin =211 xmax =232 ymax=-124 ymin=-69 for x in range(xmin,xmax+1): for y in range(ymax,ymin+1): target_area.append((x,y)) #print(target_area) possible_V=[] for Vx in range(1,xmax+1): for Vy in range(ymax, -ymax): possible_V.append((Vx,Vy)) #print(possible_V) velocity_good=set() for vel in possible_V: x=0 y=0 Vx=vel[0] Vy=vel[1] while x<xmax and y>ymax: #print(x,y,'step before') x=Vx+x y=Vy+y #print('Vx:', Vx, "Vy:", Vy, 'x,y:', (x,y)) if Vx>0: Vx-=1 elif Vx<0: Vx+=1 elif Vx==0: Vx=0 Vy-=1 if (x,y) in target_area: #print('IN TARGET: ',x,y) velocity_good.add((vel[0],vel[1])) break print(len(velocity_good)) # -
Day 17 - ball play trajectory, arithmetic progression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # ReadMe - Il giro del mondo in 80 giorni (di Cardinale, Manili, Viganò) # Step 1 - Data Cleaning # Rimozione NaN, check di duplicati. # Creazione di un ID identificabile univoco concatenando "city" e "iso2". # Step 2 - Creazione della matrice di distanze # Step 3 - Popolare la matrice con i seguenti criteri: # # - DA FARE - Popolare solo se la long della città di arrivo è più grande della città di partenza. (Tenere presente la linea di cambio di data). Per colonna prendere le 3 distanze più piccole (2 - 4 - 8) # - 0 e tutto il resto "no go" # Step 4 - Popolare la matrice utilizzando la matrice oridinaria. # # - +2 se la città è in un altro stato # - +2 se la città ha più di 200,000 abitanti # # Step 5 - Algoritmo di Dijkstra
.ipynb_checkpoints/Cosa ho fatto - cosa c'è da fare - cosa va corretto-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np from scipy.optimize import curve_fit from scipy.stats import binned_statistic import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import seaborn as sns # %load_ext autoreload # %autoreload 2 from latentrees import * def param_freezer(func, *args, **kwargs): def wrapper(x): return func(x, *args, **kwargs) return wrapper def nbinom(node, param): if node < 1: return None alpha = param m = node + 2 n = m * m/ (m**alpha - m) p = (float(m)**(1-alpha)) return rng.negative_binomial(n,p) # + tags=[] runtime = analyses() params = [1.5, 2, 2.1, 2.2, 2.3] #for param in params: #runtime.append_model(L=15, nl=4, distribution = param_freezer(lambda node, param: np.clip(rng.integers(node-1-np.sqrt(3)*np.power(abs(node),param), node+1+np.sqrt(3)*np.power(abs(node),param)), -1e10, 1e10), param), name="{:.2f}".format(param)) #runtime.append_model(L=15, nl=3, distribution = param_freezer(lambda node, param: np.clip(round(rng.normal(node, np.power(abs(node),param/2))), -1e10, 1e10), param), name="{:.2f}".format(param)) #runtime.append_model(nl=param, L=50, name="negative_binom_{:d}".format(param)) #runtime.append_model(nl=3, L=50, distribution = param_freezer(lambda node, param: rng.integers(node-1-param*np.sqrt(3)*abs(node), node+1+param*np.sqrt(3)*abs(node)), param), name="{:.2f}".format(param)) #runtime.append_model(L=25, distribution = param_freezer(lambda node, param: nbinom(node, param), param), name="negative_binom_{:.2f}".format(param)) runtime.append_model(L=25, name="negative_binom_{:d}".format(1)) #runtime.append_model(L=50, distribution = lambda node: np.clip(rng.normal(node, abs(node)), -1e15, 1e15), name="gaus_scaling") print(runtime) runtime.run() # + moi_index = "negative_binom_1" #model of interest #moi_index = "2.00" #model of interest if moi_index not in runtime: raise ValueError(f"{moi_index} not available") layers = runtime[moi_index].layers L = runtime[moi_index].L nl = runtime[moi_index].nl # + fig = plt.figure(figsize=(18,15)) for model in runtime: layers = model.layers L = model.L nl = model.nl cnts = layers[-1].sorted_nodes #cnts = np.abs(cnts) cnts = cnts[np.abs(cnts)<1e10] #freqs = np.unique(cnts, return_counts=True)[1] freqs = cnts freqs = freqs / np.sum(freqs) x = np.linspace(1, len(freqs), len(freqs)) plt.plot(x, np.sort(freqs)[::-1], marker="o", ms=10, lw=1, alpha=0.5, label=model.name) plt.plot(x, 1e0*x**-1., color="gray", lw=10, ls="--") #plt.ylim(1e-5,1e-1) plt.legend(fontsize=35) plt.xscale("log") plt.yscale("log") plt.xlabel("Rank, $i$", fontsize=35) plt.ylabel("Frequency, Fi", fontsize=35) plt.tick_params(labelsize=30) fig.show() #fig.savefig("rank_plot_norm.pdf") # + fig = plt.figure() for l in range(1, L+1, round(L/4)): cnts = layers[l].sorted_nodes cnts = cnts[cnts>0] #freqs = np.unique(cnts, return_counts=True)[1] #freqs = freqs / np.sum(freqs) freqs = cnts x = np.linspace(1, len(freqs), len(freqs)) plt.plot(x, np.sort(freqs)[::-1]/np.sum(freqs), marker="o", ms=20, lw=10, alpha=0.2, label=l) plt.plot(x, x**-1, color="gray", lw=10, ls="--") plt.legend() plt.xscale("log") plt.yscale("log") plt.xlabel("i") plt.ylabel("fi") fig.show() # + layer_of_interest = runtime[moi_index].layers[10] cnts = layer_of_interest.sorted_nodes #cnts = np.abs(cnts) #cnts = cnts[cnts<1e15] freqs = np.unique(cnts, return_counts=True)[1] freqs = freqs / np.sum(freqs) cnts = cnts/cnts.sum() cnts = np.sort(cnts)[::-1] x = np.linspace(1, len(cnts), len(cnts)) xf = np.linspace(1, len(freqs), len(freqs)) fig = go.Figure() fig.add_trace(go.Scatter(x=x, y=cnts, marker=dict(symbol="0", size=20, color="blue"), mode="markers+lines", line_width=10, name="", showlegend=False)) #fig.add_trace(go.Scatter(x=xf, y=freqs, marker=dict(symbol="0", size=20, color="green"), mode="markers+lines", line_width=10, name="", showlegend=False)) fig.add_trace(go.Scatter(x=x, y=1/x, line_width=10, line_dash="dash",name="x^-1")) fit_func = lambda x, C, gamma: C * np.power(x, - gamma) popt, pcov = curve_fit(fit_func, x[20:15000], cnts[20:15000]) fig.add_trace(go.Scatter(x=x, y=fit_func(x, *popt), line_width=10, line_dash="longdash", name=f"C*x^-{round(popt[1],3)}")) popt, pcov = curve_fit(fit_func, xf[1:], freqs[1:]) #fig.add_trace(go.Scatter(x=xf, y=fit_func(xf, *popt), line_width=10, line_dash="longdash", name=f"C*x^-{round(popt[1],3)}")) #dd = np.diff(np.diff(cnts)) #mask = np.argwhere((dd[1:]*dd[:-1]<0)).ravel() #fig.add_trace(go.Scatter(x=x[mask],y=cnts[mask], name=f"flexes", mode="markers")) fig.update_xaxes(type="log", title="rank") fig.update_yaxes(type="log", exponentformat="e", title="leaf count", range=[np.log10(1e-5),np.log10(0.9)]) fig.update_layout(title=moi_index, titlefont_size=20) fig.show() #fig.write_image("zipf_norm_leaf.pdf", engine="kaleido") # + layer_of_interest = runtime[moi_index].layers[-1] cnts = layer_of_interest.sorted_nodes freqs = np.unique(cnts, return_counts=True)[1] freqs = freqs/freqs.sum() freqs = np.sort(freqs)[::-1] x = np.linspace(1, len(freqs), len(freqs)) fig = go.Figure() fig.add_trace(go.Scatter(x=x, y=freqs, marker=dict(symbol="0", size=20, color="blue"), line_width=10, name="", showlegend=False)) fig.add_trace(go.Scatter(x=x, y=1/x, line_width=10, line_dash="dash",name="x^-1")) fit_func = lambda x, C, gamma: C * np.power(x, - gamma) popt, pcov = curve_fit(fit_func, x[20:15000], freqs[20:15000]) fig.add_trace(go.Scatter(x=x, y=fit_func(x, *popt), line_width=10, line_dash="longdash", name=f"C*x^-{round(popt[1],3)}")) #dd = np.diff(np.diff(cnts)) #mask = np.argwhere((dd[1:]*dd[:-1]<0)).ravel() #fig.add_trace(go.Scatter(x=x[mask],y=cnts[mask], name=f"flexes", mode="markers")) fig.update_xaxes(type="log", title="rank", titlefont_size=30, tickfont_size=25) fig.update_yaxes(type="log", exponentformat="e", title="f", titlefont_size=30, tickfont_size=25) fig.update_layout(title=moi_index, titlefont_size=20) fig.show() #fig.write_image("zipf_norm_f.pdf", engine="kaleido") # - # # Last Layer # + fig = go.Figure() leaves = np.array(runtime[moi_index].layers[-1].nodes) leaves = leaves[abs(leaves) < 1e15] fig.add_trace(go.Histogram(x=leaves, nbinsx=100)) layout=dict( xaxis=dict(title="leaves", title_font_size=35, tickfont_size=25), yaxis=dict(tickfont_size=25) ) fig.update_layout(layout) # - # ## Histogram of distances # + import multiprocessing as mp import gc def append_error(err): print(err) def append_dist(d): global distances distances.append(d) def measure_func(leaf_A): return list(map(lambda leaf_B: abs(leaf_A[1]-leaf_B[1]) if leaf_A[0] < leaf_B[0] else np.nan, enumerate(leaves))) # - data = dict() for model in runtime: loi = model.layers[-1] N = 500 if len(loi)>N: leaves = np.random.choice(loi.nodes,size=N,replace=False) else: leaves = loi.nodes norm_leaves = max(loi.nodes) #print(norm_leaves) distances = [] pool = mp.Pool(4) res = pool.map_async(measure_func, enumerate(leaves), callback=append_dist, error_callback=append_error) pool.close() pool.join() distances = np.ravel(distances) #distances = np.ravel(list(map(lambda leaf: abs((leaf-avg_leaves)/norm_leave),enumerate(leaves)))) #distances=distances/max([np.nanmax(distances),abs(np.nanmin(distances))]) distances = distances[~np.isnan(distances)] #distances = distances[distances>=0] data[model.name]=distances loi = None gc.collect() # ### distance vs param # + scale_distances = False fig = go.Figure() n_leaves = len(leaves) for param,distances in data.items(): try: if scale_distances: distances=distances/max([np.quantile(distances, 0.99),abs(np.nanmin(distances))]) bins=np.linspace(0,np.quantile(distances, 0.99),15) else: bins=np.logspace(np.log10(distances[distances>1e-10].min()),np.log10(distances.max()), 10) bins, edges = np.histogram(distances, bins=bins, density=True) esges = (edges[1:]+edges[:1])/2 fig.add_trace(go.Scatter(x=edges,y=bins, marker=dict(size=20), line=dict(width=10), name=param)) except: pass fig.update_layout(xaxis=dict(title="distances", titlefont_size=35, tickfont_size=35, nticks= 5), yaxis=dict(title="pdf", titlefont_size=35,tickfont_size=35, type="log", exponentformat="e", showexponent='all', nticks=4), legend=dict(x=1.01,y=1,borderwidth=0.5,font_size=15,orientation="v")) if not scale_distances: fig.update_xaxes(type="log") fig.show() filename = "images/pdf_distances_nbinom_scaling" if scale_distances: filename+="_scaled" #fig.write_image(f"{filename}.pdf") #fig.write_html(f"{filename}.html") # - # ### Distance vs layer # + fig = go.Figure() for loi in runtime[-1].layers[::10]: N = 500 if len(loi)>N: leaves = np.random.choice(loi.nodes,size=N,replace=False) else: leaves = loi.nodes avg_leaves = loi.median distances = [] pool = mp.Pool(2) res = pool.map_async(measure_func, enumerate(leaves), callback=append_dist, error_callback=append_error) pool.close() pool.join() distances = np.ravel(distances) distances = distances[~np.isnan(distances)] n_leaves = len(leaves) bins=np.logspace(np.log10(distances[distances>0].min()),np.log10(distances.max()), 15) #bins=np.linspace(distances.min(),distances.max(),20) bins, edges = np.histogram(distances, bins=bins, density=True) esges = (edges[1:]+edges[:1])/2 fig.add_trace(go.Scatter(x=edges,y=bins, marker=dict(size=20), line=dict(width=10), name=loi.__repr__().split(",")[0])) gc.collect() fig.update_layout(xaxis=dict(title="distances", titlefont_size=35, tickfont_size=35, exponentformat="e", type="log", nticks= 4), yaxis=dict(title="pdf", titlefont_size=35,tickfont_size=35, type="log", exponentformat="e", showexponent='all', nticks=4), legend=dict(x=1.01,y=1,borderwidth=0.5,font_size=15,orientation="v")) fig.show() filename = "images/distance_pdf_layers_nbinom" fig.write_image(f"{filename}.pdf") fig.write_html(f"{filename}.html") # - # # Hyperparameters # ## gamma def get_exp(layer, x_limits = (0,-1))->float: try: layer_of_interest = layer cnts = layer_of_interest.sorted_nodes #cnts = np.abs(cnts) #cnts = cnts[np.abs(cnts)<1e15] #cnts = cnts/cnts.sum() #cnts = np.sort(cnts)[::-1] freqs = np.unique(cnts, return_counts=True)[1] freqs = freqs/freqs.sum() freqs = np.sort(freqs)[::-1] x = np.linspace(1, len(freqs), len(freqs)) popt, pcov = curve_fit(lambda x, C, gamma: C * np.power(x, - gamma), x[x_limits[0]:x_limits[1]], freqs[x_limits[0]:x_limits[1]]) return popt[1] except: return np.nan exps = list(map(lambda m: get_exp(m.layers[-1]), runtime)) exps_first = list(map(lambda m: get_exp(m.layers[-1], x_limits=(0,100)), runtime)) exps_second = list(map(lambda m: get_exp(m.layers[-1], x_limits=(100,1000)), runtime)) exps_third = list(map(lambda m: get_exp(m.layers[-1], x_limits=(1000,5000)), runtime)) # + x, xlabel = params, "scaling" #x, xlabel = np.linspace(1,len(exps),len(exps)), "Layer" fig = go.Figure() #fig.add_scatter(x = x, y=exps, error_y=dict(type="data", array=exps_errors, visible=True, width=8, thickness=3), name="exponents", mode="lines", marker=dict(size=10), line=dict(width=10, color="gray")) fig.add_scatter(x = x, y=exps, name="exponents", mode="lines", marker=dict(size=10), line=dict(width=10, color="gray")) fig.add_trace(go.Scatter(y=[1,1], x=[min(x)*0.9,max(x)*1.1], name="1", mode="lines", line=dict(width=10, color="blue", dash="dash"))) #for exp, name in zip([exps_first, exps_second, exps_third],["first", "second", "third"]): # fig.add_scatter(x = x, y=exp, name=name, mode="lines", marker=dict(size=10), line=dict(width=10)) fig.update_traces(marker_size=20) fig.update_layout(xaxis=dict(title=xlabel, exponentformat = 'e', tickfont=dict(size=20), title_font_size=35), yaxis_title="gamma", yaxis=dict(tickfont=dict(size=20), title_font=dict(size=35)), legend=dict(font_size=30, orientation="v", x=0.9, y=1)) fig.show() filename = "images/exp_scaling_unif_regimes" #fig.write_image("{}.pdf".format(filename)) #fig.write_html("{}.html".format(filename)) # - import gc gc.collect()
latentrees.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import torch from pathlib import Path from rona.data import RonaData from torchvision import transforms from torch.utils.data import ( Dataset, DataLoader, random_split ) # - # !ls /Users/ygx/data/utkml/utkML_projects/covid_ct_scans/ct_data dataroot = Path("/Users/ygx/data/utkml/utkML_projects/covid_ct_scans/ct_data") data_transforms = transforms.Compose([ transforms.Resize((100, 100)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]) dataset = RonaData(dataroot, data_transforms) # + num_train = len(dataset) // (1/(3/4)) num_valid = len(dataset) - num_train train_data, valid_data = random_split( dataset, [int(num_train), int(num_valid)] ) # - data_loader = DataLoader(train_data, batch_size=5) for idx, (data, target) in enumerate(data_loader): print(f"data: {data.shape}, target: {target.shape}") if idx == 4: break # + stds = [] means = [] for img, _ in dataset: means.append(torch.mean(img)) stds.append(torch.std(img)) mean = torch.mean(torch.tensor(means)) std = torch.mean(torch.tensor(stds)) # - mean std
examples/notebooks/data.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import cvxpy as cp # Create two scalar optimization variables. x = cp.Variable() y = cp.Variable() x # Create two constraints. constraints = [x + y == 1, x - y >= 1] # + # Form objective. obj = cp.Minimize((x - y)**2) # - # Form and solve problem. prob = cp.Problem(obj, constraints) prob.solve() # Returns the optimal value. print("status:", prob.status) print("optimal value", prob.value) print("optimal var", x.value, y.value)
CVXPY tutorial/.ipynb_checkpoints/What is CVXPY..huh-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import sys from __future__ import division # + import numpy as np from phasor.utilities.ipynb.displays import * #from YALL.utilities.tabulate import tabulate import declarative from declarative.bunch import ( DeepBunch ) import phasor.math.dispatched as dmath #import phasor.math.dispatch_sympy # + import phasor.utilities.version as version print(version.foundations_version()) from phasor.utilities.np import logspaced from phasor import optics from phasor import base from phasor import signals from phasor import system from phasor import readouts # + sys = system.BGSystem( F_AC = logspaced(0.001, 100, 1000) ) sys.own.X1 = signals.SRationalFilter( poles_r = (-1, ), gain = 1, ) sys.own.R1 = readouts.ACReadout( portN = sys.X1.ps_Out.o, portD = sys.X1.ps_In.i, ) Fb = mplfigB(Nrows=2) readoutI = sys.R1 Fb.ax0.loglog(readoutI.F_Hz.val, abs(readoutI.AC_sensitivity)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(readoutI.AC_sensitivity, deg = True)) # + sys = system.BGSystem( F_AC = logspaced(0.001, 100, 1000) ) sys.own.X1 = signals.SRationalFilter( zeros_r = (-1, ), gain = 1, ) sys.own.R1 = readouts.ACReadout( portN = sys.X1.ps_Out.o, portD = sys.X1.ps_In.i, ) Fb = mplfigB(Nrows=2) readoutI = sys.R1 Fb.ax0.loglog(readoutI.F_Hz.val, abs(readoutI.AC_sensitivity)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(readoutI.AC_sensitivity, deg = True)) # + sys = system.BGSystem( F_AC = logspaced(0.001, 100, 1000) ) sys.own.X1 = signals.SRationalFilter( zeros_c = (-1 + 10j, ), gain = 1, ) sys.own.R1 = readouts.ACReadout( portN = sys.X1.ps_Out.o, portD = sys.X1.ps_In.i, ) Fb = mplfigB(Nrows=2) readoutI = sys.R1 Fb.ax0.loglog(readoutI.F_Hz.val, abs(readoutI.AC_sensitivity)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(readoutI.AC_sensitivity, deg = True)) # + sys = system.BGSystem( F_AC = logspaced(0.01, 1000, 1000) ) sys.own.X1 = signals.SRationalFilter( #poles_c = (-2 - 10j, ), zeros_r = (-10, -10), gain = 1, ) sys.own.R1 = readouts.ACReadout( portN = sys.X1.ps_Out.o, portD = sys.X1.ps_In.i, ) Fb = mplfigB(Nrows=2) readoutI = sys.R1 Fb.ax0.loglog(readoutI.F_Hz.val, abs(readoutI.AC_sensitivity)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(readoutI.AC_sensitivity, deg = True)) size = len(readoutI.F_Hz.val) relscale = .9 AC_data = readoutI.AC_sensitivity * (1 + np.random.normal(0, relscale, size) + 1j*np.random.normal(0, relscale, size)) Fb.ax0.loglog(readoutI.F_Hz.val, abs(AC_data)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(AC_data, deg = True)) sysO = sys print(sys.X1.ctree_as_yaml()) # + import phasor.fitting.casadi as FIT import phasor.fitting.casadi.transfer_functions as FIT_TF froot = FIT.FitterRoot() froot.own.sym = FIT.FitterSym() sys = system.BGSystem( F_AC = logspaced(0.01, 1000, 1000) ) sys.own.X1 = signals.SRationalFilter( #poles_c = (-2 - 10j, ), zeros_r = (-1, -100), gain = 1, ) sys.own.R1 = readouts.ACReadout( portN = sys.X1.ps_Out.o, portD = sys.X1.ps_In.i, ) froot.systems.xfer = sys froot.sym.parameter(sys.X1) froot.own.residual = FIT_TF.TransferACExpression( ACData = AC_data, ACReadout = sys.R1, SNR_weights = 1/relscale, ) minny = froot.residual.minimize_function() Fb = mplfigB(Nrows=2) readoutI = sys.R1 Fb.ax0.loglog(readoutI.F_Hz.val, abs(readoutI.AC_sensitivity)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(readoutI.AC_sensitivity, deg = True)) Fb.ax0.loglog(readoutI.F_Hz.val, abs(AC_data)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(AC_data, deg = True)) readoutI = minny.systems.xfer.R1 Fb.ax0.loglog(readoutI.F_Hz.val, abs(readoutI.AC_sensitivity)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(readoutI.AC_sensitivity, deg = True)) readoutI = sysO.R1 Fb.ax0.loglog(readoutI.F_Hz.val, abs(readoutI.AC_sensitivity)) Fb.ax1.semilogx(readoutI.F_Hz.val, np.angle(readoutI.AC_sensitivity, deg = True)) # - import casadi casadi.MX.ones(10) casadi.MX.ones(10).shape casadi.dot(casadi.MX.ones(10), casadi.MX.ones(10))
phasor/signals/test_playground.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] toc=true # <h1>Table of Contents<span class="tocSkip"></span></h1> # <div class="toc"><ul class="toc-item"><li><span><a href="#Process-Data" data-toc-modified-id="Process-Data-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Process Data</a></span></li><li><span><a href="#Pre-Process-Data-For-Deep-Learning" data-toc-modified-id="Pre-Process-Data-For-Deep-Learning-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Pre-Process Data For Deep Learning</a></span><ul class="toc-item"><li><ul class="toc-item"><li><ul class="toc-item"><li><span><a href="#Look-at-one-example-of-processed-issue-bodies" data-toc-modified-id="Look-at-one-example-of-processed-issue-bodies-2.0.0.1"><span class="toc-item-num">2.0.0.1&nbsp;&nbsp;</span>Look at one example of processed issue bodies</a></span></li><li><span><a href="#Look-at-one-example-of-processed-issue-titles" data-toc-modified-id="Look-at-one-example-of-processed-issue-titles-2.0.0.2"><span class="toc-item-num">2.0.0.2&nbsp;&nbsp;</span>Look at one example of processed issue titles</a></span></li></ul></li></ul></li></ul></li><li><span><a href="#Define-Model-Architecture" data-toc-modified-id="Define-Model-Architecture-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>Define Model Architecture</a></span><ul class="toc-item"><li><ul class="toc-item"><li><span><a href="#Load-the-data-from-disk-into-variables" data-toc-modified-id="Load-the-data-from-disk-into-variables-3.0.1"><span class="toc-item-num">3.0.1&nbsp;&nbsp;</span>Load the data from disk into variables</a></span></li><li><span><a href="#Define-Model-Architecture" data-toc-modified-id="Define-Model-Architecture-3.0.2"><span class="toc-item-num">3.0.2&nbsp;&nbsp;</span>Define Model Architecture</a></span></li></ul></li></ul></li><li><span><a href="#Train-Model" data-toc-modified-id="Train-Model-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>Train Model</a></span></li><li><span><a href="#See-Results-On-Holdout-Set" data-toc-modified-id="See-Results-On-Holdout-Set-5"><span class="toc-item-num">5&nbsp;&nbsp;</span>See Results On Holdout Set</a></span></li><li><span><a href="#Feature-Extraction-Demo" data-toc-modified-id="Feature-Extraction-Demo-6"><span class="toc-item-num">6&nbsp;&nbsp;</span>Feature Extraction Demo</a></span><ul class="toc-item"><li><ul class="toc-item"><li><span><a href="#Example-1:-Issues-Installing-Python-Packages" data-toc-modified-id="Example-1:-Issues-Installing-Python-Packages-6.0.1"><span class="toc-item-num">6.0.1&nbsp;&nbsp;</span>Example 1: Issues Installing Python Packages</a></span></li><li><span><a href="#Example-2:--Issues-asking-for-feature-improvements" data-toc-modified-id="Example-2:--Issues-asking-for-feature-improvements-6.0.2"><span class="toc-item-num">6.0.2&nbsp;&nbsp;</span>Example 2: Issues asking for feature improvements</a></span></li></ul></li></ul></li></ul></div> # - import pandas as pd import logging import glob from sklearn.model_selection import train_test_split pd.set_option('display.max_colwidth', 500) logger = logging.getLogger() logger.setLevel(logging.WARNING) # # Process Data # Look at filesystem to see files extracted from BigQuery (or Kaggle: https://www.kaggle.com/davidshinn/github-issues/) # !ls -lah | grep github_issues.csv # Split data into train and test set and preview data # + #read in data sample 2M rows (for speed of tutorial) traindf, testdf = train_test_split(pd.read_csv('github_issues.csv').sample(n=2000000), test_size=.10) #print out stats about shape of data print(f'Train: {traindf.shape[0]:,} rows {traindf.shape[1]:,} columns') print(f'Test: {testdf.shape[0]:,} rows {testdf.shape[1]:,} columns') # preview data traindf.head(3) # - # **Convert to lists in preparation for modeling** train_body_raw = traindf.body.tolist() train_title_raw = traindf.issue_title.tolist() #preview output of first element train_body_raw[0] # # Pre-Process Data For Deep Learning # # See [this repo](https://github.com/hamelsmu/ktext) for documentation on the ktext package # %reload_ext autoreload # %autoreload 2 from ktext.preprocess import processor # %%time # Clean, tokenize, and apply padding / truncating such that each document length = 70 # also, retain only the top 8,000 words in the vocabulary and set the remaining words # to 1 which will become common index for rare words body_pp = processor(keep_n=8000, padding_maxlen=70) train_body_vecs = body_pp.fit_transform(train_body_raw) # #### Look at one example of processed issue bodies print('\noriginal string:\n', train_body_raw[0], '\n') print('after pre-processing:\n', train_body_vecs[0], '\n') # + # Instantiate a text processor for the titles, with some different parameters # append_indicators = True appends the tokens '_start_' and '_end_' to each # document # padding = 'post' means that zero padding is appended to the end of the # of the document (as opposed to the default which is 'pre') title_pp = processor(append_indicators=True, keep_n=4500, padding_maxlen=12, padding ='post') # process the title data train_title_vecs = title_pp.fit_transform(train_title_raw) # - # #### Look at one example of processed issue titles print('\noriginal string:\n', train_title_raw[0]) print('after pre-processing:\n', train_title_vecs[0]) # Serialize all of this to disk for later use # + import dill as dpickle import numpy as np # Save the preprocessor with open('body_pp.dpkl', 'wb') as f: dpickle.dump(body_pp, f) with open('title_pp.dpkl', 'wb') as f: dpickle.dump(title_pp, f) # Save the processed data np.save('train_title_vecs.npy', train_title_vecs) np.save('train_body_vecs.npy', train_body_vecs) # - # # Define Model Architecture # ### Load the data from disk into variables from seq2seq_utils import load_decoder_inputs, load_encoder_inputs, load_text_processor encoder_input_data, doc_length = load_encoder_inputs('train_body_vecs.npy') decoder_input_data, decoder_target_data = load_decoder_inputs('train_title_vecs.npy') num_encoder_tokens, body_pp = load_text_processor('body_pp.dpkl') num_decoder_tokens, title_pp = load_text_processor('title_pp.dpkl') # ### Define Model Architecture # %matplotlib inline from keras.models import Model from keras.layers import Input, LSTM, GRU, Dense, Embedding, Bidirectional, BatchNormalization from keras import optimizers # + #arbitrarly set latent dimension for embedding and hidden units latent_dim = 300 ##### Define Model Architecture ###### ######################## #### Encoder Model #### encoder_inputs = Input(shape=(doc_length,), name='Encoder-Input') # Word embeding for encoder (ex: Issue Body) x = Embedding(num_encoder_tokens, latent_dim, name='Body-Word-Embedding', mask_zero=False)(encoder_inputs) x = BatchNormalization(name='Encoder-Batchnorm-1')(x) # Intermediate GRU layer (optional) #x = GRU(latent_dim, name='Encoder-Intermediate-GRU', return_sequences=True)(x) #x = BatchNormalization(name='Encoder-Batchnorm-2')(x) # We do not need the `encoder_output` just the hidden state. _, state_h = GRU(latent_dim, return_state=True, name='Encoder-Last-GRU')(x) # Encapsulate the encoder as a separate entity so we can just # encode without decoding if we want to. encoder_model = Model(inputs=encoder_inputs, outputs=state_h, name='Encoder-Model') seq2seq_encoder_out = encoder_model(encoder_inputs) ######################## #### Decoder Model #### decoder_inputs = Input(shape=(None,), name='Decoder-Input') # for teacher forcing # Word Embedding For Decoder (ex: Issue Titles) dec_emb = Embedding(num_decoder_tokens, latent_dim, name='Decoder-Word-Embedding', mask_zero=False)(decoder_inputs) dec_bn = BatchNormalization(name='Decoder-Batchnorm-1')(dec_emb) # Set up the decoder, using `decoder_state_input` as initial state. decoder_gru = GRU(latent_dim, return_state=True, return_sequences=True, name='Decoder-GRU') decoder_gru_output, _ = decoder_gru(dec_bn, initial_state=seq2seq_encoder_out) x = BatchNormalization(name='Decoder-Batchnorm-2')(decoder_gru_output) # Dense layer for prediction decoder_dense = Dense(num_decoder_tokens, activation='softmax', name='Final-Output-Dense') decoder_outputs = decoder_dense(x) ######################## #### Seq2Seq Model #### #seq2seq_decoder_out = decoder_model([decoder_inputs, seq2seq_encoder_out]) seq2seq_Model = Model([encoder_inputs, decoder_inputs], decoder_outputs) seq2seq_Model.compile(optimizer=optimizers.Nadam(lr=0.001), loss='sparse_categorical_crossentropy') # - # ** Examine Model Architecture Summary ** from seq2seq_utils import viz_model_architecture seq2seq_Model.summary() viz_model_architecture(seq2seq_Model) # # Train Model # + from keras.callbacks import CSVLogger, ModelCheckpoint script_name_base = 'tutorial_seq2seq' csv_logger = CSVLogger('{:}.log'.format(script_name_base)) model_checkpoint = ModelCheckpoint('{:}.epoch{{epoch:02d}}-val{{val_loss:.5f}}.hdf5'.format(script_name_base), save_best_only=True) batch_size = 1200 epochs = 7 history = seq2seq_Model.fit([encoder_input_data, decoder_input_data], np.expand_dims(decoder_target_data, -1), batch_size=batch_size, epochs=epochs, validation_split=0.12, callbacks=[csv_logger, model_checkpoint]) # - #save model seq2seq_Model.save('seq2seq_model_tutorial.h5') # # See Results On Holdout Set from seq2seq_utils import Seq2Seq_Inference seq2seq_inf = Seq2Seq_Inference(encoder_preprocessor=body_pp, decoder_preprocessor=title_pp, seq2seq_model=seq2seq_Model) # this method displays the predictions on random rows of the holdout set seq2seq_inf.demo_model_predictions(n=50, issue_df=testdf) # # Feature Extraction Demo # Read All 5M data points all_data_df = pd.read_csv('github_issues.csv') # Extract the bodies from this dataframe all_data_bodies = all_data_df['body'].tolist() # transform all of the data using the ktext processor all_data_vectorized = body_pp.transform_parallel(all_data_bodies) # save transformed data with open('all_data_vectorized.dpkl', 'wb') as f: dpickle.dump(all_data_vectorized, f) # %reload_ext autoreload # %autoreload 2 from seq2seq_utils import Seq2Seq_Inference seq2seq_inf_rec = Seq2Seq_Inference(encoder_preprocessor=body_pp, decoder_preprocessor=title_pp, seq2seq_model=seq2seq_Model) recsys_annoyobj = seq2seq_inf_rec.prepare_recommender(all_data_vectorized, all_data_df) # ### Example 1: Issues Installing Python Packages seq2seq_inf_rec.demo_model_predictions(n=1, issue_df=testdf, threshold=1) # ### Example 2: Issues asking for feature improvements seq2seq_inf_rec.demo_model_predictions(n=1, issue_df=testdf, threshold=1) # + # incase you need to reset the rec system # seq2seq_inf_rec.set_recsys_annoyobj(recsys_annoyobj) # seq2seq_inf_rec.set_recsys_data(all_data_df) # save object recsys_annoyobj.save('recsys_annoyobj.pkl') # -
notebooks/Tutorial.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- #hide # %load_ext autoreload # %autoreload 2 # + # default_exp rics # - # # RIC's # + #export import numpy as np import qutip as qt from scipy.stats import ortho_group from qbism.povm import * from qbism.random import * from qbism.kraus import * # - # One can also consider POVM's on real valued Hilbert spaces. RIC-POVM's (real informationally complete POVM's) will have $\frac{d(d+1)}{2}$ elements (unlike the complex case, where they would be $d^2$ elements). # # SIC-POVM's in real Hilbert spaces correspond to sets of *real* equiangular lines, and unlike in the complex case, they can be proved *not* to exist in certain dimensions. # # For purposes of testing out RIC's, let's define some useful functions: #export def real_rand_ket(d): r""" Generates a random ket in real Hilbert space of dimension $d$. """ return qt.Qobj(np.random.randn(d)).unit() #export def real_rand_dm(d): r""" Generates a random density matrix for a real Hilbert space of dimension $d$. """ return qt.Qobj(qt.rand_dm(d).full().real) #export def rand_symmetric(d): r""" Generates a random $d \times d$ symmetric matrix. These matrices correspond to observables in real quantum mechanics, being the real analogue of Hermitian matrices: $\hat{S} = \hat{S}^{T}$. """ M = qt.Qobj(np.random.randn(d,d)) return M*M.trans() + M.trans()*M #export def rand_orthogonal(d): r""" Generates a random $d \times d$ orthogonal matrix. These matrices correspond to time evolution in real quantum mechanics, being the real analogue of unitary matrices: $\hat{S}\hat{S}^{T} = \hat{I}$. """ return qt.Qobj(ortho_group.rvs(d)) # Let's generate a random RIC and check that it behaves like the more usual complex IC-POVM's we're used to. First, let's check that we can go back and forth between density matrices and probabilities: d = 3 povm = random_haar_povm(d, real=True) phi = povm_phi(povm) rho = real_rand_dm(d) p = dm_probs(rho, povm) assert np.allclose(rho, probs_dm(p, povm)) # Then let's compare classical and quantum probabilities for some observable represented by a symmetric matrix: # + S = rand_symmetric(d) vn = [v*v.dag() for v in S.eigenstates()[1]] R = conditional_probs(vn, povm) classical_probs = R @ p quantum_probs = R @ phi @ p post_povm_rho = sum([(e*rho).tr()*(e/e.tr()) for e in povm]) assert np.allclose(classical_probs, [(v*post_povm_rho).tr() for v in vn]) assert np.allclose(quantum_probs, [(v*rho).tr() for v in vn]) # - # And finally, let's check out time evolution under an othogonal matrix: O = rand_orthogonal(d) assert np.allclose(dm_probs(O*rho*O.trans(), povm), povm_map([O], povm) @ phi @ p) # As an example, let's consider the Petersen RIC in $d=4$ based on the [Petersen Graph](https://en.wikipedia.org/wiki/Petersen_graph) and the [Rectified 5-cell](http://eusebeia.dyndns.org/4d/rect5cell). # #export def petersen_povm(): petersen_vertices = ["u1", "u2", "u3", "u4", "u5", "v1", "v2", "v3", "v4", "v5"] petersen_graph = \ {"u1": ["v1", "u2", "u5"], "u2": ["u1", "v2", "u3"], "u3": ["u2", "v3", "u4"], "u4": ["u3", "v4", "u5"], "u5": ["u4", "v5", "u1"], "v1": ["u1", "v4", "v3"], "v2": ["u2", "v4", "v5"], "v3": ["v5", "v1", "u3"], "v4": ["u4", "v1", "v2"], "v5": ["u5", "v3", "v2"]} petersen_gram = np.array([[1 if a == b else (\ -2/3 if b in petersen_graph[a] else \ 1/6) for b in petersen_vertices]\ for a in petersen_vertices]) U, D, V = np.linalg.svd(petersen_gram) petersen_states = [qt.Qobj(state) for state in V[:4].T @ np.sqrt(np.diag(D[:4]))] return [(2/5)*v*v.dag() for v in petersen_states] # + petersen = petersen_povm() assert np.allclose(sum(petersen), qt.identity(4)) rho = real_rand_dm(4) assert np.allclose(rho, probs_dm(dm_probs(rho, petersen), petersen)) print("petersen gram:\n %s" % np.round(povm_gram(petersen, normalized=False), decimals=3)) print("quantumness: %f" % quantumness(petersen)) # - # In $d=3$, there's a real SIC based on the icosahedron! # + #export def circular_shifts(v): shifts = [v] for i in range(len(v)-1): u = shifts[-1][:] u.insert(0, u.pop()) shifts.append(u) return shifts def icosahedron_vertices(): phi = (1+np.sqrt(5))/2 return [np.array(v) for v in circular_shifts([0, 1, phi]) + \ circular_shifts([0, -1, -phi]) + \ circular_shifts([0, 1, -phi]) + \ circular_shifts([0, -1, phi])] def icosahedron_povm(): vertices = icosahedron_vertices() keep = [] for i, a in enumerate(vertices): for j, b in enumerate(vertices): if i != j and np.allclose(a, -b) and j not in keep: keep.append(i) vertices = [qt.Qobj(e).unit() for i, e in enumerate(vertices) if i in keep] return [(1/2)*v*v.dag() for v in vertices] # + icosahedron = icosahedron_povm() assert np.allclose(sum(icosahedron), qt.identity(3)) rho = real_rand_dm(3) assert np.allclose(rho, probs_dm(dm_probs(rho, icosahedron), icosahedron)) print("icosahedron gram:\n %s" % np.round(povm_gram(icosahedron, normalized=False), decimals=3)) print("quantumness: %f" % quantumness(icosahedron))
06rics.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Computation with Binned Data # # As described in [Binned Data](binned-data.ipynb) scipp can handle certain types of sparse or scattered data such as *event data*, i.e., data that cannot directly be represented as a multi-dimensional array. # This could, e.g., be used to store data from an array of sensors/detectors that are read out independently, with potentially widely varying frequency. # # Scipp supports two classes of operations with binned data. # # 1. [Bin-centric arithmetic](#Bin-centric-arithmetic) treats every bin as an element to, e.g., apply a different scale factor to every bin. # 2. [Event-centric arithmetic](#Event-centric-arithmetic) considers the individual events within bins. # This allows for operation without the precision loss that would ensue from simply histogramming data. # ## Overview and Quick Reference # # Before going into a detailed explanation below we provide a quick reference: # # - Unary operations such as `sin`, `cos`, or `sqrt` work as normal. # - Comparison operations such as `less` (`<`) are not supported. # - Binary operations such as `+` work in principle, but usually not if both operands represent event data. # In that case, see table below. # # Given two data arrays `a` and `b`, equivalent operations are: # # Dense data operation | Binned data equivalent | Comment # :--- |:--- |:--- # `a + b` | `a.bins.concatenate(b)` | if both `a` and `b` are event data # `a - b` | `a.bins.concatenate(-b)` | if both `a` and `b` are event data # `a += b` | `a.bins.concatenate(b, out=a)` | if both `a` and `b` are event data # `a -= b` | `a.bins.concatenate(-b, out=a)` | if both `a` and `b` are event data # `sc.sum(a, 'dim')` | `a.bins.concatenate('dim')` | # `sc.mean(a, 'dim')` | not available | `min`, `max`, and other similar reductions are also not available # `sc.rebin(a, dim, 'edges')` | `sc.bin(a, edges=[edges])` | # `groupby(...).sum('dim')` | `groupby(...).bins.concatenate('dim')` | `mean`, `max`, and other similar reductions are also available # ## Concepts # # Before assigning events to bins, we can initialize them as a single long list or table. # In the simplest case this table has just a single column, i.e., it is a scipp variable: # + import numpy as np import scipp as sc table = sc.array(dims=['event'], values=[0,1,3,1,1,1,42,1,1,1,1,1], dtype='float64') sc.table(table) # - # The events in the table can then be mapped into bins: begin = sc.array(dims=['x'], values=[0,6,6,8]) end = sc.array(dims=['x'], values=[6,6,8,12]) var = sc.bins(begin=begin, end=end, dim='event', data=table) sc.show(var) var # Each element of the resulting "bin variable" references a section of the underlying table: sc.table(var['x', 0].value) sc.table(var['x', 1].value) sc.table(var['x', 2].value) # ## Bin-centric arithmetic # # Elements of binned variables are views of slices of a variable or data array. # An operation such as multiplication of a binned variable with a dense array thus computes the product of the bin (a variable view or data array view) with a scalar element of the dense array. # In other words, operations between variables or data arrays broadcast dense data to the lists held in the bins: scale = sc.Variable(dims=['x'], values=np.arange(2.0, 6)) var *= scale var['x', 0].values var['x', 1].values var['x', 2].values # In practice scattered data requires more than one "column" of information. # Typically we need at least one coordinate such as an event time stamp in addition to weights. # If each scattered data point (event) corresponds to, e.g., a single detected neutron then the weight is 1. # As above, we start by creating a single table containing *all* events: # + times = sc.array(dims=['event'], unit='us', # micro second values=[0,1,3,1,1,1,4,1,1,2,1,1], dtype='float64') weights = sc.ones(dims=['event'], unit='counts', shape=[12], with_variances=True) table = sc.DataArray(data=weights, coords={'time':times}) sc.table(table) table # - # This table is then mapped into bins. # The resulting "bin variable" can, e.g., be used as the data in a data array, and can be combined with coordinates as usual: var = sc.bins(begin=begin, end=end, dim='event', data=table) a = sc.DataArray(data=var, coords={'x':sc.Variable(dims=['x'], values=np.arange(4.0))}) a # <div class="alert alert-info"> # # In practice we rarely use `sc.bins` (which requires `begin` and `end` indices for each bin and an appropriately sorted table) to create binned data. # For creating binned *variables* `sc.bins` is the only option, but for binning *data arrays* we typically bin based on the meta data of the individual data points, i.e., the coord columns in the table of scattered data. # Use `sc.bin` (not `sc.bins`) as described in [Binned Data](binned-data.ipynb). # # </div> # In the graphical representation of the data array we can see the dense coordinate (green), and the bins (yellow): sc.show(a) # As before, each bin references a section of the underlying table: sc.table(a['x', 0].value) sc.table(a['x', 1].value) sc.table(a['x', 2].value) # ## Event-centric arithmetic # # Complementary to the [bin-centric arithmetic](#Bin-centric-arithmetic) operations, which treat every bin as an element, we may need more fine-grained operations that treat events within bins individually. # Scipp provides a number of such operations, defined in a manner to produce a result equivalent to that of a corresponding operation for histogrammed data, but preserving events and thus keeping the options of, e.g., binning to a higher resolution or filtering by meta data later. # For example, addition of histogrammed data would correspond to concatenating event lists of individual bins. # # The following operations are supported: # # - "Addition" of data arrays containing event data in bins. # This is achieved by concatenating the underlying event lists. # - "Subtraction" of data arrays containing event data in bins. # This is performed by concatenating with a negative weight for the subtrahend. # - "Multiplication" of a data array containing event data in bins with a data array with dense, histogrammed data. # The weight of each event is scaled by the value of the corresponding bin in the histogram. # Note that in contrast to the bin-centric operations the histogram may have a different (higher) resolution than the bin size of the binned event data. # This operation does not match based on the coords of the *bin* but instead considers the more precise coord values of the individual events, i.e., the operation is performances based on the meta data column in the underlying table. # - "Division" of a data array containing event data in bins by a data array with dense, histogrammed data. # This is performed by scaling with the inverse of the denominator. # <div class="alert alert-warning"> # <b>WARNING:</b> # # It is important to note that these operations, in particular multiplication and division, are only interchangeable with histogramming if the variances of the "histogram" operand are negligible. # If these variances are not negligible the operation on the event data introduces correlations in the error bars of the individual events. # Scipp has no way of tracking such correlations and a subsequent `histogram` step propagates uncertainties under the assumption of uncorrelated error bars. # </div> # ### Addition sc.show(a['x',2].value) a.bins.concatenate(a, out=a) sc.show(a['x',2].value) a.bins.sum().plot() # ### Subtraction zero = a.copy() sc.show(zero['x',2].value) zero.bins.concatenate(-zero, out=zero) sc.show(zero['x',2].value) zero.bins.sum().plot() # ### Multiplication and division # # We prepare a histogram that will be used to scale the event weights: time_bins = sc.array(dims=['time'], unit=sc.units.us, values=[0.0, 3.0, 6.0]) weight = sc.array(dims=['time'], values=[10.0, 3.0], variances=[10.0, 3.0]) hist = sc.DataArray(data=weight, coords={'time':time_bins}) hist # The helper `sc.lookup` provides a wrapper for a discrete "function", given by a data array depending on a specified dimension. # The binary arithmetic operators on the `bins` property support this function-like object: a.bins /= sc.lookup(func=hist, dim='time') sc.histogram(a, bins=time_bins).plot()
docs/user-guide/binned-data/computation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + # Copyright 2021 Google LLC # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. # Notebook authors: <NAME> (<EMAIL>) # and <NAME> (<EMAIL>) # This notebook reproduces figures for chapter 11 from the book # "Probabilistic Machine Learning: An Introduction" # by <NAME> (MIT Press, 2021). # Book pdf is available from http://probml.ai # - # <a href="https://opensource.org/licenses/MIT" target="_parent"><img src="https://img.shields.io/github/license/probml/pyprobml"/></a> # <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/book1/figures/chapter11_linear_regression_figures.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # ## Figure 11.1:<a name='11.1'></a> <a name='linregPolyDegrees1and2'></a> # # Polynomial of degrees 1 and 2 fit to 21 datapoints. # Figure(s) generated by [linreg_poly_vs_degree.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_poly_vs_degree.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linreg_poly_vs_degree.py") # %run linreg_poly_vs_degree.py # ## Figure 11.2:<a name='11.2'></a> <a name='linregSurf'></a> # # (a) Contours of the RSS error surface for the example in \cref fig:linregPolyDegree1 . The blue cross represents the MLE. (b) Corresponding surface plot. # Figure(s) generated by [linreg_contours_sse_plot.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_contours_sse_plot.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linreg_contours_sse_plot.py") # %run linreg_contours_sse_plot.py # ## Figure 11.3:<a name='11.3'></a> <a name='leastSquaresGeom'></a> # # Graphical interpretation of least squares for $m=3$ equations and $n=2$ unknowns when solving the system $\mathbf A \mathbf x = \mathbf b $. $\mathbf a _1$ and $\mathbf a _2$ are the columns of $\mathbf A $, which define a 2d linear subspace embedded in $\mathbb R ^3$. The target vector $\mathbf b $ is a vector in $\mathbb R ^3$; its orthogonal projection onto the linear subspace is denoted $ \mathbf b $. The line from $\mathbf b $ to $ \mathbf b $ is the vector of residual errors, whose norm we want to minimize. #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') show_image("/pyprobml/book1/figures/images/Figure_11.3.png") # ## Figure 11.4:<a name='11.4'></a> <a name='linregOnline'></a> # # Regression coefficients over time for the 1d model in \cref fig:linregPoly2 (a). # Figure(s) generated by [linregOnlineDemo.py](https://github.com/probml/pyprobml/blob/master/scripts/linregOnlineDemo.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linregOnlineDemo.py") # %run linregOnlineDemo.py # ## Figure 11.5:<a name='11.5'></a> <a name='residualPlot'></a> # # Residual plot for polynomial regression of degree 1 and 2 for the functions in \cref fig:linregPoly2 (a-b). # Figure(s) generated by [linreg_poly_vs_degree.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_poly_vs_degree.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linreg_poly_vs_degree.py") # %run linreg_poly_vs_degree.py # ## Figure 11.6:<a name='11.6'></a> <a name='polyfitScatter'></a> # # Fit vs actual plots for polynomial regression of degree 1 and 2 for the functions in \cref fig:linregPoly2 (a-b). # Figure(s) generated by [linreg_poly_vs_degree.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_poly_vs_degree.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linreg_poly_vs_degree.py") # %run linreg_poly_vs_degree.py # ## Figure 11.7:<a name='11.7'></a> <a name='polyfitRidge2'></a> # # (a-c) Ridge regression applied to a degree 14 polynomial fit to 21 datapoints. (d) MSE vs strength of regularizer. The degree of regularization increases from left to right, so model complexity decreases from left to right. # Figure(s) generated by [linreg_poly_ridge.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_poly_ridge.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linreg_poly_ridge.py") # %run linreg_poly_ridge.py # ## Figure 11.8:<a name='11.8'></a> <a name='geomRidge'></a> # # Geometry of ridge regression. The likelihood is shown as an ellipse, and the prior is shown as a circle centered on the origin. Adapted from Figure 3.15 of <a href='#BishopBook'>[Bis06]</a> . # Figure(s) generated by [geom_ridge.py](https://github.com/probml/pyprobml/blob/master/scripts/geom_ridge.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./geom_ridge.py") # %run geom_ridge.py # ## Figure 11.9:<a name='11.9'></a> <a name='L2L1contours'></a> # # Illustration of $\ell _1$ (left) vs $\ell _2$ (right) regularization of a least squares problem. Adapted from Figure 3.12 of <a href='#Hastie01'>[HTF01]</a> . #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') show_image("/pyprobml/book1/figures/images/Figure_11.9.png") # ## Figure 11.10:<a name='11.10'></a> <a name='softThresholding'></a> # # Left: soft thresholding. Right: hard thresholding. In both cases, the horizontal axis is the residual error incurred by making predictions using all the coefficients except for $w_k$, and the vertical axis is the estimated coefficient $ w _k$ that minimizes this penalized residual. The flat region in the middle is the interval $[-\lambda ,+\lambda ]$. #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') show_image("/pyprobml/book1/figures/images/Figure_11.10_A.png") show_image("/pyprobml/book1/figures/images/Figure_11.10_B.png") # ## Figure 11.11:<a name='11.11'></a> <a name='lassoPathProstate'></a> # # (a) Profiles of ridge coefficients for the prostate cancer example vs bound $B$ on $\ell _2$ norm of $\mathbf w $, so small $B$ (large $\lambda $) is on the left. The vertical line is the value chosen by 5-fold CV using the 1 standard error rule. Adapted from Figure 3.8 of <a href='#HastieBook'>[HTF09]</a> . # Figure(s) generated by [ridgePathProstate.py](https://github.com/probml/pyprobml/blob/master/scripts/ridgePathProstate.py) [lassoPathProstate.py](https://github.com/probml/pyprobml/blob/master/scripts/lassoPathProstate.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./ridgePathProstate.py") # %run ridgePathProstate.py google.colab.files.view("./lassoPathProstate.py") # %run lassoPathProstate.py # ## Figure 11.12:<a name='11.12'></a> <a name='lassoPathCoef'></a> # # Values of the coefficients for linear regression model fit to prostate cancer dataset as we vary the strength of the $\ell _1$ regularizer. These numbers are plotted in \cref fig:lassoPathProstate (b). #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') # ## Figure 11.13:<a name='11.13'></a> <a name='tab:prostateCoef'></a> # # Results of different methods on the prostate cancer data, which has 8 features and 67 training cases. Methods are: OLS = ordinary least squares, Subset = best subset regression, Ridge, Lasso. Rows represent the coefficients; we see that subset regression and lasso give sparse solutions. Bottom row is the mean squared error on the test set (30 cases). Adapted from Table 3.3. of <a href='#HastieBook'>[HTF09]</a> . # Figure(s) generated by [prostateComparison.m](https://github.com/probml/pmtk3/blob/master/demos/prostateComparison.m) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') # ## Figure 11.14:<a name='11.14'></a> <a name='sparseSensingDemo'></a> # # (a) Boxplot displaying (absolute value of) prediction errors on the prostate cancer test set for different regression methods. # Figure(s) generated by [prostateComparison.m](https://github.com/probml/pmtk3/blob/master/demos/prostateComparison.m) [sparseSensingDemo.m](https://github.com/probml/pmtk3/blob/master/demos/sparseSensingDemo.m) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') show_image("/pyprobml/book1/figures/images/Figure_11.14.png") show_image("/pyprobml/book1/figures/images/Figure_11.14.png") #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') show_image("/pyprobml/book1/figures/images/Figure_11.14.png") show_image("/pyprobml/book1/figures/images/Figure_11.14.png") # ## Figure 11.15:<a name='11.15'></a> <a name='groupLassoGauss'></a> # # Illustration of group lasso where the original signal is piecewise Gaussian. (a) Original signal. (b) Vanilla lasso estimate. (c) Group lasso estimate using a $\ell _2$ norm on the blocks. (d) Group lasso estimate using an $\ell _ \infty $ norm on the blocks. Adapted from Figures 3-4 of <a href='#Wright09'>[WNF09]</a> . # Figure(s) generated by [groupLassoDemo.py](https://github.com/probml/pyprobml/blob/master/scripts/groupLassoDemo.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./groupLassoDemo.py") # %run groupLassoDemo.py # ## Figure 11.16:<a name='11.16'></a> <a name='groupLassoUnif'></a> # # Same as \cref fig:groupLassoGauss , except the original signal is piecewise constant. # Figure(s) generated by [groupLassoDemo.py](https://github.com/probml/pyprobml/blob/master/scripts/groupLassoDemo.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./groupLassoDemo.py") # %run groupLassoDemo.py # ## Figure 11.17:<a name='11.17'></a> <a name='splinesWeighted'></a> # # Illustration of B-splines of degree 0, 1 and 3. Top row: unweighted basis functions. Dots mark the locations of the 3 internal knots at $[0.25, 0.5, 0.75]$. Bottom row: weighted combination of basis functions using random weights. # Figure(s) generated by [splines_basis_weighted.py](https://github.com/probml/pyprobml/blob/master/scripts/splines_basis_weighted.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./splines_basis_weighted.py") # %run splines_basis_weighted.py # ## Figure 11.18:<a name='11.18'></a> <a name='splinesHeatmap'></a> # # Design matrix for B-splines of degree (a) 0, (b) 1 and (c) 3. We evaluate the splines on 20 inputs ranging from 0 to 1. # Figure(s) generated by [splines_basis_heatmap.py](https://github.com/probml/pyprobml/blob/master/scripts/splines_basis_heatmap.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./splines_basis_heatmap.py") # %run splines_basis_heatmap.py # ## Figure 11.19:<a name='11.19'></a> <a name='splinesCherry'></a> # # Fitting a cubic spline regression model with 15 knots to a 1d dataset. # Figure(s) generated by [splines_cherry_blossoms.py](https://github.com/probml/pyprobml/blob/master/scripts/splines_cherry_blossoms.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./splines_cherry_blossoms.py") # %run splines_cherry_blossoms.py # ## Figure 11.20:<a name='11.20'></a> <a name='linregRobust'></a> # # (a) Illustration of robust linear regression. # Figure(s) generated by [linregRobustDemoCombined.py](https://github.com/probml/pyprobml/blob/master/scripts/linregRobustDemoCombined.py) [huberLossPlot.py](https://github.com/probml/pyprobml/blob/master/scripts/huberLossPlot.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linregRobustDemoCombined.py") # %run linregRobustDemoCombined.py google.colab.files.view("./huberLossPlot.py") # %run huberLossPlot.py # ## Figure 11.21:<a name='11.21'></a> <a name='bayesLinRegPlot2d'></a> # # Sequential Bayesian inference of the parameters of a linear regression model $p(y|\mathbf x ) = \mathcal N (y | w_0 + w_1 x_1, \sigma ^2)$. Left column: likelihood function for current data point. Middle column: posterior given first $N$ data points, $p(w_0,w_1|\mathbf x _ 1:N ,y_ 1:N ,\sigma ^2)$. Right column: samples from the current posterior predictive distribution. Row 1: prior distribution ($N=0$). Row 2: after 1 data point. Row 3: after 2 data points. Row 4: after 100 data points. The white cross in columns 1 and 2 represents the true parameter value; we see that the mode of the posterior rapidly converges to this point. The blue circles in column 3 are the observed data points. Adapted from Figure 3.7 of <a href='#BishopBook'>[Bis06]</a> . # Figure(s) generated by [linreg_2d_bayes_demo.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_2d_bayes_demo.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linreg_2d_bayes_demo.py") # %run linreg_2d_bayes_demo.py # ## Figure 11.22:<a name='11.22'></a> <a name='bayesPostCentering'></a> # # Posterior samples of $p(w_0,w_1| \mathcal D )$ for 1d linear regression model $p(y|x,\boldsymbol \theta )=\mathcal N (y|w_0 + w_1 x, \sigma ^2)$ with a Gaussian prior. (a) Original data. (b) Centered data. # Figure(s) generated by [linreg_2d_bayes_centering_pymc3.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_2d_bayes_centering_pymc3.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linreg_2d_bayes_centering_pymc3.py") # %run linreg_2d_bayes_centering_pymc3.py # ## Figure 11.23:<a name='11.23'></a> <a name='linregDemoUncertaintyBars'></a> # # (a) Plugin approximation to predictive density (we plug in the MLE of the parameters) when fitting a second degree polynomial to some 1d data. (b) Posterior predictive density, obtained by integrating out the parameters. Black curve is posterior mean, error bars are 2 standard deviations of the posterior predictive density. (c) 10 samples from the plugin approximation to posterior predictive distribution. (d) 10 samples from the true posterior predictive distribution. # Figure(s) generated by [linreg_post_pred_plot.py](https://github.com/probml/pyprobml/blob/master/scripts/linreg_post_pred_plot.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') google.colab.files.view("./linreg_post_pred_plot.py") # %run linreg_post_pred_plot.py # ## Figure 11.24:<a name='11.24'></a> <a name='ARDsparsity'></a> # # Illustration of why ARD results in sparsity. The vector of inputs $\mathbf x $ does not point towards the vector of outputs $\mathbf y $, so the feature should be removed. (a) For finite $\alpha $, the probability density is spread in directions away from $\mathbf y $. (b) When $\alpha =\infty $, the probability density at $\mathbf y $ is maximized. Adapted from Figure 8 of <a href='#Tipping01'>[Tip01]</a> . #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts import pyprobml_utils as pml import colab_utils import os os.environ["PYPROBML"] = ".." # one above current scripts directory import google.colab from google.colab.patches import cv2_imshow # %reload_ext autoreload # %autoreload 2 def show_image(img_path,size=None,ratio=None): img = colab_utils.image_resize(img_path, size) cv2_imshow(img) print('finished!') show_image("/pyprobml/book1/figures/images/Figure_11.24_A.png") show_image("/pyprobml/book1/figures/images/Figure_11.24_B.png") # ## References: # <a name='BishopBook'>[Bis06]</a> C. Bishop "Pattern recognition and machine learning". (2006). # # <a name='Hastie01'>[HTF01]</a> <NAME>, <NAME> and <NAME>. "The Elements of Statistical Learning". (2001). # # <a name='HastieBook'>[HTF09]</a> <NAME>, <NAME> and <NAME>. "The Elements of Statistical Learning". (2009). # # <a name='Tipping01'>[Tip01]</a> M. Tipping "Sparse Bayesian learning and the relevance vector machine". In: jmlr (2001). # # <a name='Wright09'>[WNF09]</a> <NAME>, <NAME> and <NAME>. "Sparse reconstruction by separable approximation". In: IEEE Trans. on Signal Processing (2009). # #
book1/figures/chapter11_linear_regression_figures.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import os import numpy as np import tensorflow as tf import random as python_random def reset_random_seeds(): os.environ['PYTHONHASHSEED']=str(1) tf.random.set_seed(1) np.random.seed(1) python_random.seed(1) # + import pandas as pd import sys from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split, StratifiedKFold from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.svm import SVC import keras from keras import regularizers, optimizers from keras.layers import Lambda, Input, Dense, BatchNormalization as BN, concatenate, Dropout from keras.models import Model from sklearn.utils.class_weight import compute_class_weight from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC from sklearn.metrics import roc_curve import scikitplot as skplt import matplotlib.pyplot as plt # pip install -U imbalanced-learn from imblearn import over_sampling from imblearn.over_sampling import RandomOverSampler, SMOTE, ADASYN, BorderlineSMOTE, SVMSMOTE, KMeansSMOTE # - # # Predicting Hist with 1000 genes raw_data = pd.read_csv('MBdata_33CLINwMiss_1KfGE_1KfCNA.csv') raw_data['Histological_Type'].value_counts() raw_data_IDC_ILC = raw_data[(raw_data['Histological_Type'] == 'IDC') | (raw_data['Histological_Type'] == 'ILC')] raw_data_IDC_ILC['Histological_Type'].value_counts() raw_data_IDC_ILC_ge = raw_data_IDC_ILC.iloc[:, 34:1034] scaler = MinMaxScaler() raw_data_IDC_ILC_ge = scaler.fit_transform(raw_data_IDC_ILC_ge) hist_type = raw_data_IDC_ILC.loc[:,'Histological_Type'] hist_type.replace({"IDC":0,"ILC":1}, inplace=True) X_train, X_test, y_train, y_test = train_test_split(raw_data_IDC_ILC_ge, hist_type, test_size=0.33, random_state=42) genes_df = raw_data_IDC_ILC.iloc[:, 34:1034] hist_type_df = raw_data_IDC_ILC.loc[:, "Histological_Type"] mb_ge_hist_df = pd.concat([genes_df, hist_type_df], axis=1) mb_ge_hist_df.to_csv('MB-GE-Hist.csv', index=False) # ## Predicting with imbalanced data random_forest = RandomForestClassifier(n_estimators=50, random_state=42, max_features=.5) random_forest = random_forest.fit(X_train, y_train) predicted = random_forest.predict(X_test) print(accuracy_score(y_test,predicted)) print(confusion_matrix(y_test, predicted)) svm=SVC(C=1.5, kernel='rbf',random_state=42,gamma='auto',probability=True) svm.fit(X_train, y_train) predicted = svm.predict(X_test) print(accuracy_score(y_test,predicted)) print(confusion_matrix(y_test, predicted)) # + def build_model(): reset_random_seeds() inp = Input(shape=(int_size,)) x = Dense(ds, activation=act, kernel_regularizer=regularizers.l2(0.01))(inp) x = BN()(x) x = Dense(ds // 2, activation=act, kernel_regularizer=regularizers.l2(0.01))(x) x = BN()(x) out = Dense(out_size, activation='softmax')(x) model = Model(inp, out, name='dnn_ge') model.summary() sgd = optimizers.SGD(lr=0.001 ,nesterov=False) model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy']) return model def model_scores(dnn, X_train, y_train, X_test, y_test): class_weights = compute_class_weight('balanced', np.unique(y_train), y_train) y_train_enc = keras.utils.to_categorical(y_train, 2) y_test_enc = keras.utils.to_categorical(y_test, 2) dnn.fit(X_train, y_train_enc, epochs=epochs, batch_size=batch_size, class_weight=class_weights) y_pred_prob = dnn.predict(X_test) y_pred_class = y_pred_prob.argmax(axis=-1) print(confusion_matrix(y_test,y_pred_class)) train_scores = dnn.evaluate(X_train, y_train_enc) test_scores = dnn.evaluate(X_test, y_test_enc) print(train_scores) print(test_scores) return(train_scores, test_scores) # - batch_size = 32 act = "tanh" ds = 128 int_size = 1000 out_size = 2 epochs = 100 dnn = build_model() model_scores(dnn, X_train, y_train, X_test, y_test) # ### Comparing the classifiers rf_predicted_prob = random_forest.predict_proba(X_test) skplt.metrics.plot_roc_curve(y_test, rf_predicted_prob) plt.show() svm_predicted_prob = svm.predict_proba(X_test) skplt.metrics.plot_roc_curve(y_test, svm_predicted_prob) plt.show() dnn_predicted_prob = dnn.predict(X_test) skplt.metrics.plot_roc_curve(y_test, dnn_predicted_prob) plt.show() # ## Predicting with oversampling train set X_train_ros_tr, y_train_ros_tr = RandomOverSampler(sampling_strategy = 'minority', random_state=42).fit_resample(X_train, y_train) X_train_sm_tr, y_train_sm_tr = SMOTE(sampling_strategy = 'minority', random_state=42).fit_resample(X_train, y_train) X_train_ad_tr, y_train_ad_tr = ADASYN(sampling_strategy = 'minority', random_state=42).fit_resample(X_train, y_train) X_train_bls_tr, y_train_bls_tr = BorderlineSMOTE(sampling_strategy = 'minority', random_state=42).fit_resample(X_train, y_train) X_train_svms_tr, y_train_svms_tr = SVMSMOTE(sampling_strategy = 'minority', random_state=42).fit_resample(X_train, y_train) model_scores(dnn, X_train_ros_tr, y_train_ros_tr, X_test, y_test) model_scores(dnn, X_train_sm_tr, y_train_sm_tr, X_test, y_test) model_scores(dnn, X_train_ad_tr, y_train_ad_tr, X_test, y_test) model_scores(dnn, X_train_bls_tr, y_train_bls_tr, X_test, y_test) model_scores(dnn, X_train_svms_tr, y_train_svms_tr, X_test, y_test) # # Predicting Hist with the whole gene set MB_all_genes = pd.read_csv("all_genes.csv") MB_all_genes_hist = pd.concat([MB_all_genes, raw_data['Histological_Type']], axis=1) MB_all_genes_hist_IDC_ILC = MB_all_genes_hist[(MB_all_genes_hist['Histological_Type'] == 'IDC') | (MB_all_genes_hist['Histological_Type'] == 'ILC')] MB_all_genes_hist_IDC_ILC.shape nan_cols = [i for i in MB_all_genes_hist_IDC_ILC.columns if MB_all_genes_hist_IDC_ILC[i].isnull().any()] nan_cols # + # MB_all_genes_hist_IDC_ILC.replace([np.inf, -np.inf, np.nan], 0, inplace=True) # - hist_type = MB_all_genes_hist_IDC_ILC.iloc[:,-1] hist_type .replace({"IDC":0,"ILC":1}, inplace=True) MB_all_genes_hist_IDC_ILC = MB_all_genes_hist_IDC_ILC.drop(["Histological_Type"], axis = 1) MB_all_genes_hist_IDC_ILC = MB_all_genes_hist_IDC_ILC.drop( ['TMPRSS7', 'SLC25A19', 'IDO1', 'CSNK2A1', 'BAMBI', 'MRPL24', 'AK127905', 'FAM71A'], axis = 1) MB_all_genes_hist_IDC_ILC.shape X_train_all, X_test_all, y_train_all, y_test_all = train_test_split(MB_all_genes_hist_IDC_ILC, hist_type, test_size=0.33, random_state=42) # + def build_model_all(): reset_random_seeds() inp = Input(shape=(int_size,)) x = Dense(ds, activation=act, kernel_regularizer=regularizers.l2(0.01))(inp) x = BN()(x) x = Dense(ds//4, activation=act, kernel_regularizer=regularizers.l2(0.01))(x) x = BN()(x) out = Dense(out_size, activation='softmax')(x) dnn_all = Model(inp, out, name='dnn_ge') dnn_all.summary() # sgd = optimizers.SGD(lr=0.0001 ,nesterov=False) adam = optimizers.Adam(learning_rate=0.00005, clipvalue=1) dnn_all.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy']) return dnn_all # - batch_size = 64 act = "tanh" ds = 256 int_size = 24360 out_size = 2 epochs = 100 dnn_all = build_model_all() model_scores(dnn_all ,X_train_all, y_train_all, X_test_all, y_test_all) # ## Predicting with oversampling train set X_train_all_bls_tr, y_train_all_bls_tr = BorderlineSMOTE(sampling_strategy = 'minority', random_state=42).fit_resample(X_train_all, y_train_all) model_scores(dnn_all, X_train_all_bls_tr, y_train_all_bls_tr, X_test_all, y_test_all) # # Predicting Hist with Images # ## scalar-k50 scalar_k50 = pd.read_csv("scalar_measures_k50_all_v5.csv") len(scalar_k50.catalog_ID.unique()) scalar_k50.shape scalar_k50.rename(columns={"catalog_ID": "METABRIC_ID"}, inplace=True) scalar_k50_raw_data_hist = pd.merge(scalar_k50, raw_data, on='METABRIC_ID') scalar_k50_raw_data_hist_IDC_ILC = scalar_k50_raw_data_hist[(scalar_k50_raw_data_hist['Histological_Type'] == 'IDC') | (scalar_k50_raw_data_hist['Histological_Type'] == 'ILC')] scalar_k50_raw_data_hist_IDC_ILC.shape scalar_k50_hist_IDC_ILC= scalar_k50_raw_data_hist_IDC_ILC.iloc[:, 2:14] scalar_k50_hist_type = scalar_k50_raw_data_hist_IDC_ILC['Histological_Type'] scalar_k50_hist_type.replace({"IDC":0,"ILC":1}, inplace=True) X_train_sk50, X_test_sk50, y_train_sk50, y_test_sk50 = train_test_split(scalar_k50_hist_IDC_ILC, scalar_k50_hist_type, test_size=0.33, random_state=42) random_forest = random_forest.fit(X_train_sk50, y_train_sk50) predicted_rf = random_forest.predict(X_test_sk50) print(accuracy_score(y_test_sk50,predicted_rf)) print(confusion_matrix(y_test_sk50, predicted_rf)) # + def build_model_images(): reset_random_seeds() inp = Input(shape=(int_size,)) x = Dense(ds, activation=act)(inp) x = BN()(x) x = Dense(ds // 2, activation=act)(x) x = BN()(x) out = Dense(out_size, activation='softmax')(x) model = Model(inp, out, name='dnn_ge') model.summary() sgd = optimizers.SGD(lr=0.01 ,nesterov=False) model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy']) return model batch_size = 32 act = "tanh" ds = 10 int_size = 12 out_size = 2 epochs = 100 dnn_sk50 = build_model_images() # - model_scores(dnn_sk50, X_train_sk50, y_train_sk50, X_test_sk50, y_test_sk50) # ## scalar-k10 scalar_k10 = pd.read_csv("scalar_measures_k10_all_v5.csv") scalar_k10.shape scalar_k10.rename(columns={"catalog_ID": "METABRIC_ID"}, inplace=True) scalar_k10_raw_data_hist = pd.merge(scalar_k10, raw_data, on='METABRIC_ID') scalar_k10_raw_data_hist_IDC_ILC = scalar_k10_raw_data_hist[(scalar_k10_raw_data_hist['Histological_Type'] == 'IDC') | (scalar_k10_raw_data_hist['Histological_Type'] == 'ILC')] scalar_k10_hist_IDC_ILC= scalar_k10_raw_data_hist_IDC_ILC.iloc[:, 2:14] scalar_k10_hist_type = scalar_k10_raw_data_hist_IDC_ILC['Histological_Type'] scalar_k10_hist_type.replace({"IDC":0,"ILC":1}, inplace=True) X_train_sk10, X_test_sk10, y_train_sk10, y_test_sk10 = train_test_split(scalar_k10_hist_IDC_ILC, scalar_k10_hist_type, test_size=0.33, random_state=42) random_forest = random_forest.fit(X_train_sk10, y_train_sk10) predicted_rf = random_forest.predict(X_test_sk10) print(accuracy_score(y_test_sk10,predicted_rf)) print(confusion_matrix(y_test_sk10, predicted_rf)) dnn_sk10 = build_model_images() model_scores(dnn_sk10, X_train_sk10, y_train_sk10, X_test_sk10, y_test_sk10) # # vector_k10 pre-processing vector_k10 = pd.read_csv("vector_measures_k10_all_v5.csv") vector_k10.rename(columns={"catalog_ID": "METABRIC_ID"}, inplace=True) vector_k10.iloc[:,2:370] = scaler.fit_transform(vector_k10.iloc[:,2:370]) vector_k10_raw_data_hist = pd.merge(vector_k10, raw_data, on='METABRIC_ID') vector_k10_raw_data_hist_IDC_ILC = vector_k10_raw_data_hist[(vector_k10_raw_data_hist['Histological_Type'] == 'IDC') | (vector_k10_raw_data_hist['Histological_Type'] == 'ILC')] vector_k10_raw_data_hist_IDC_ILC['Histological_Type'].replace({"IDC":0,"ILC":1}, inplace=True) int_size = 368 ds = 32 dnn_vk10 = build_model_images() skf = StratifiedKFold(n_splits=5,shuffle=True) def cross_val(skf, X, y, model): train_scores = [] test_scores = [] for train_index, test_index in skf.split(X, y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] train_score, test_score = model_scores(model, X_train, y_train, X_test, y_test) train_scores.append(train_score[1]) test_scores.append(test_score[1]) print(np.mean(train_scores)) print(np.mean(test_scores)) # ## vector-k10 vector_k10_hist_IDC_ILC= vector_k10_raw_data_hist_IDC_ILC.iloc[:, 2:370] vector_k10_hist_type = vector_k10_raw_data_hist_IDC_ILC['Histological_Type'] # X_train_vk10, X_test_vk10, y_train_vk10, y_test_vk10 = train_test_split(vector_k10_hist_IDC_ILC, vector_k10_hist_type, test_size=0.33, random_state=42) X = vector_k10_hist_IDC_ILC y = vector_k10_hist_type.values cross_val(skf, X, y,dnn_vk10) # ### vector-k10 No Duplication vector_k10_raw_data_hist_IDC_ILC_ND = vector_k10_raw_data_hist_IDC_ILC.drop_duplicates(subset=['METABRIC_ID']) vector_k10_raw_data_hist_IDC_ILC_ND.shape vector_k10_hist_IDC_ILC_ND = vector_k10_raw_data_hist_IDC_ILC_ND.iloc[:, 2:370] vector_k10_hist_type_ND = vector_k10_raw_data_hist_IDC_ILC_ND['Histological_Type'] # X_train_vk10_ND, X_test_vk10_ND, y_train_vk10_ND, y_test_vk10_ND = train_test_split(vector_k10_hist_IDC_ILC_ND, vector_k10_hist_type_ND, test_size=0.33, random_state=42) X = vector_k10_hist_IDC_ILC_ND y = vector_k10_hist_type_ND.values model_scores(dnn_vk10, X_train_vk10_ND, y_train_vk10_ND, X_test_vk10_ND, y_test_vk10_ND) # ## vector-k50 vector_k50 = pd.read_csv("vector_measures_k50_all_v5.csv") vector_k50.shape vector_k50.rename(columns={"catalog_ID": "METABRIC_ID"}, inplace=True) vector_k50_raw_data_hist = pd.merge(vector_k50, raw_data, on='METABRIC_ID') vector_k50_raw_data_hist_IDC_ILC = vector_k50_raw_data_hist[(vector_k50_raw_data_hist['Histological_Type'] == 'IDC') | (vector_k50_raw_data_hist['Histological_Type'] == 'ILC')] vector_k50_hist_IDC_ILC= vector_k50_raw_data_hist_IDC_ILC.iloc[:, 2:370] vector_k50_hist_IDC_ILC =scaler.fit_transform(vector_k50_hist_IDC_ILC) vector_k50_hist_type = vector_k50_raw_data_hist_IDC_ILC['Histological_Type'] vector_k50_hist_type.replace({"IDC":0,"ILC":1}, inplace=True) X_train_vk50, X_test_vk50, y_train_vk50, y_test_vk50 = train_test_split(vector_k50_hist_IDC_ILC, vector_k50_hist_type, test_size=0.33, random_state=42) model_scores(dnn_vk10, X_train_vk50, y_train_vk50, X_test_vk50, y_test_vk50) # ### vector-k50 No Duplication vector_k50_raw_data_hist_IDC_ILC_ND = vector_k50_raw_data_hist_IDC_ILC.drop_duplicates(subset=['METABRIC_ID']) vector_k50_raw_data_hist_IDC_ILC_ND.shape vector_k50_hist_IDC_ILC_ND = vector_k50_raw_data_hist_IDC_ILC_ND.iloc[:, 2:370] vector_k50_hist_IDC_ILC_ND =scaler.fit_transform(vector_k50_hist_IDC_ILC_ND) vector_k50_hist_type_ND = vector_k50_raw_data_hist_IDC_ILC_ND['Histological_Type'] X_train_vk50_ND, X_test_vk50_ND, y_train_vk50_ND, y_test_vk50_ND = train_test_split(vector_k50_hist_IDC_ILC_ND, vector_k50_hist_type_ND, test_size=0.33, random_state=42) model_scores(dnn_vk10, X_train_vk10_ND, y_train_vk10_ND, X_test_vk10_ND, y_test_vk10_ND) # # Predicting PAM50 with images scalar_k50_raw_data_hist.shape scalar_k50_raw_data_hist[scalar_k50_raw_data_hist.Pam50Subtype != '?'] # + g= list(scalar_k50_raw_data_hist["Pam50Subtype"].values) g # - # ## Using Maja's dataset MBdata_all_genes = pd.read_csv("MBdata_all.csv") MBdata_all_genes.shape MBdata_all_genes_IDC_ILC = MBdata_all_genes[(MBdata_all_genes['Histological_Type'] == 'IDC') | (MBdata_all_genes['Histological_Type'] == 'ILC')] all_genes = MBdata_all_genes_IDC_ILC.iloc[:,35: 24403] all_genes = scaler.fit_transform(all_genes) hist_type X_train_m, X_test_m, y_train_m, y_test_m = train_test_split(all_genes, hist_type, test_size=0.33, random_state=42) model_scores(dnn_all, X_train_m, y_train_m, X_test_m,y_test_m) # # DR using all genes dr = raw_data["DR"] dr.value_counts() X_train_dr, X_test_dr, y_train_dr, y_test_dr = train_test_split(MB_all_genes, dr, test_size=0.33, random_state=42) scores(X_train_dr, y_train_dr, X_test_dr, y_test_dr) # # Notepad df = pd.read_csv("CURTIS_data_Expression.txt", delimiter='\t') df.shape col_names=list(df["SYMBOL"]) new_df = df.drop(["SYMBOL","ENTREZ"], axis = 1) transposed=new_df.T transposed transposed.columns=col_names transposed.head() normalised = scaler.fit_transform(transposed) back_to_df = pd.DataFrame(normalised, columns=col_names) back_to_df.head() back_to_df.to_csv("all_genes.csv", index=False) MB_all_genes = pd.read_csv("all_genes.csv") MB_All_Genes.shape MB_all_genes.head(2) M
data/preprocessing/raw_data/.ipynb_checkpoints/MB-process-hist-image-IDC-ILC-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Complete Guide for Transfer learning # Here I have used Caltech-101_object dataset but the basics of Transfer learning will remain same with other datasets. # We have to look about two things in our our dataset while using Transfer learning and these are: # 1. Similarity of our dataset with that of pre-trained model # 2. the amount of data we have # Based on these two we have to select which type of transfer learning we should use. # ###### The target dataset is small and similar to the base training dataset. # Since the target dataset is small, it is not a good idea to fine-tune the ConvNet due to the risk of overfitting. Since the target data is similar to the base data, we expect higher-level features in the ConvNet to be relevant to this dataset as well. Hence, we: # 1. Remove the fully connected layers near the end of the pretrained base ConvNet # 2. Add a new fully connected layer that matches the number of classes in the target dataset # 3. Randomize the weights of the new fully connected layer and freeze all the weights from the pre-trained network # 4. Train the network to update the weights of the new fully connected layers # ###### The target dataset is large and similar to the base training dataset. # Since the target dataset is large, we have more confidence that we won’t overfit if we try to fine-tune through the full network. Therefore, we: # # 1. Remove the last fully connected layer and replace with the layer matching the number of classes in the target dataset # 2. Randomly initialize the weights in the new fully connected layer # 3. Initialize the rest of the weights using the pre-trained weights, i.e., unfreeze the layers of the pre-trained network # 4. Retrain the entire neural network # ###### The target dataset is small and different from the base training dataset. # Since the data is small, overfitting is a concern. Hence, we train only the linear layers. But as the target dataset is very different from the base dataset, the higher level features in the ConvNet would not be of any relevance to the target dataset. So, the new network will only use the lower level features of the base ConvNet. To implement this scheme, we: # # 1. Remove most of the pre-trained layers near the beginning of the ConvNet # 2. Add to the remaining pre-trained layers new fully connected layers that match the number of classes in the new dataset # 3. Randomize the weights of the new fully connected layers and freeze all the weights from the pre-trained network # 4. Train the network to update the weights of the new fully connected layers # ###### The target dataset is large and different from the base training dataset. # As the target dataset is large and different from the base dataset, we can train the ConvNet from scratch. However, in practice, it is beneficial to initialize the weights from the pre-trained network and fine-tune them as it might make the training faster. In this condition, the implementation is the same as in case 3. # import libraries. import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import style import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from sklearn.metrics import accuracy_score from sklearn.preprocessing import LabelEncoder from keras import backend as K from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam,SGD,RMSprop from keras.utils import to_categorical from keras.callbacks import ReduceLROnPlateau import tensorflow as tf import random as rn from keras.layers import Dropout, Flatten,Activation from keras.layers import Conv2D, MaxPooling2D, BatchNormalization import cv2 import numpy as np from keras.preprocessing.text import Tokenizer import os from random import shuffle from PIL import Image # %matplotlib inline style.use('fivethirtyeight') sns.set(style='whitegrid',color_codes=True) #enter the path of your dataset directory. # Here I have used only five classes from our dataset and these are #airplanes, crayfish, butterfly, panda, crocodile print(os.listdir('C:/Users/Abhishek Gupta/Desktop/caltech small dataset')) # ###### Preparing dataset X=[] Y=[] airplanes_dir='C:/Users/<NAME>pta/Desktop/caltech small dataset/airplanes' butterfly_dir='C:/Users/<NAME>pta/Desktop/caltech small dataset/butterfly' crayfish_dir='C:/Users/<NAME>/Desktop/caltech small dataset/crayfish' crocodile_dir='C:/Users/<NAME>pta/Desktop/caltech small dataset/crocodile' panda_dir='C:/Users/<NAME>/Desktop/caltech small dataset/panda' # here we have checked type of our images in our dataset. #Since we are inputting 3 channels in our model so,images in our dataset must have 3 channels i.e.,RGB images. img = cv2.imread('C:/Users/<NAME>/Desktop/caltech small dataset/airplanes/image_0005.jpg') print(img.shape) # + #defining function to make lables and training data from tqdm import tqdm IMG_SIZE= 120 def locate_label(img,img_typ): return img_typ def train_data(img_typ,DIR): for img in tqdm(os.listdir(DIR)): label=locate_label(img,img_typ) path=os.path.join(DIR,img) img = cv2.imread(path,cv2.IMREAD_COLOR) img = cv2.resize(img, (IMG_SIZE,IMG_SIZE)) X.append(np.array(img)) Y.append(str(label)) # - train_data('panda',panda_dir) print(len(X)) train_data('crocodile',crocodile_dir) print(len(X)) train_data('crayfish',crayfish_dir) print(len(X)) train_data('butterfly',butterfly_dir) print(len(X)) train_data('airplanes',airplanes_dir) print(len(X)) # ###### visualising some random images # + # here we have imbalanced dataset which certainly affects weights initialization but this is just a intuation about transfer learning # so we can ignore our imbalanced datset. Visualised some random images from training dataset fig,ax=plt.subplots(5,2) fig.set_size_inches(15,15) for i in range(5): for j in range (2): l=rn.randint(0,len(Y)) ax[i,j].imshow(X[l]) ax[i,j].set_title('objects: '+Y[l]) plt.tight_layout() # - # ###### lebelling and one hot-encoding # + #here we encoded our labels in five as we have selected 5 classese from our dataset. le=LabelEncoder() Z=le.fit_transform(Y) Z=to_categorical(Z,5) X=np.array(X) X=X/255 # - # ###### splitting dataset #splitting dataset in training,testing set x_train,x_test,y_train,y_test=train_test_split(X,Z,test_size=0.25,random_state=10) # ###### Data augmentation for avoiding overfitting of model # + #avoiding overfitting with data augmentation from keras.preprocessing.image import ImageDataGenerator datagen = ImageDataGenerator( featurewise_center=False, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=False, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180) zoom_range = 0.1, # Randomly zoom image width_shift_range=0.2, # randomly shift images horizontally (fraction of total width) height_shift_range=0.2, # randomly shift images vertically (fraction of total height) horizontal_flip=True, # randomly flip images vertical_flip=False) # randomly flip images datagen.fit(x_train) # - # ###### Importing VGG-16 model as our pretrained model with imagenet weights #If you have weights downloaded explicitly remove comments and enter path by making weights None in place of imagenet #weights_path='C:/Users/<NAME>/Desktop/19_model_weight/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5' from keras.applications.vgg16 import VGG16 base_model=VGG16(include_top=False, weights='imagenet', input_shape=(120,120,3), pooling='avg') #base_model.load_weights(weights_path) base_model.summary() # ###### Adding our own fully connected layers model=Sequential() model.add(base_model) model.add(Dense(256,activation='relu')) model.add(Dense(5,activation='softmax')) # While using transfer learning in ConvNet; we have basically have 3 main approaches--> # # 1) To use the pretrained model as a feature extractor and just train your classifier on top of it. In this method we do not tune any weights of the model. # # 2) Fine Tuning- In this approach we tune the weights of the pretrained model. This can be done by unfreezing the layers that we want to train.In that case these layers will be initialised with their trained weights on imagenet. # # 3) Lasty we can use a pretrained model. # # Note that in this section I have used the first approach ie I have just use the conv layers and added my own fully connected layers on top of VGG model. Thus I have trained a classifier on top of the CNN codes. # freezed layers of imported model base_model.trainable=False batch_size=10 #red_lr=ReduceLROnPlateau(monitor='val_acc', factor=0.1, epsilon=0.0001, patience=2, verbose=1) model.summary() model.compile(optimizer=Adam(lr=1e-5),loss='categorical_crossentropy',metrics=['accuracy']) History = model.fit_generator(datagen.flow(x_train,y_train, batch_size=batch_size), epochs = 50, validation_data = (x_test,y_test), verbose = 1, steps_per_epoch=x_train.shape[0] // batch_size) # + plt.plot(History.history['accuracy']) plt.plot(History.history['val_accuracy']) plt.title('Model Accuracy') plt.ylabel('Accuracy') plt.xlabel('Epochs') plt.legend(['train', 'test']) plt.show() # - plt.plot(History.history['loss']) plt.plot(History.history['val_loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epochs') plt.legend(['train', 'test']) plt.show() # ###### Fine Tuning of model by unfreezing last block of model # In this section I have done fine tuning. To see the effect of the fine tuning I have first unfreezed the last block of the VGG16 model and have set it to trainable. You can also unfreeze more layers according to need by replacing indexes in for loop. # + for i in range (len(base_model.layers)): print (i,base_model.layers[i]) batch_size=10 for layer in base_model.layers[15:]: layer.trainable=True for layer in base_model.layers[0:15]: layer.trainable=False model.compile(optimizer=Adam(lr=1e-5),loss='categorical_crossentropy',metrics=['accuracy']) # - History = model.fit_generator(datagen.flow(x_train,y_train, batch_size=batch_size), epochs = 50, validation_data = (x_test,y_test), verbose = 1, steps_per_epoch=x_train.shape[0] // batch_size) plt.plot(History.history['accuracy']) plt.plot(History.history['val_accuracy']) plt.title('Model Accuracy') plt.ylabel('Accuracy') plt.xlabel('Epochs') plt.legend(['train', 'test']) plt.show() plt.plot(History.history['loss']) plt.plot(History.history['val_loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epochs') plt.legend(['train', 'test']) plt.show() # ###### model from scratch. # Since our dataset is small and may lead to overfitting of model # + model=Sequential() model.add(base_model) model.add(Dense(256,activation='relu')) model.add(BatchNormalization()) model.add(Dense(5,activation='softmax')) for layer in base_model.layers: layer.trainable=True batch_size=10 model.summary() model.compile(optimizer=Adam(lr=1e-5),loss='categorical_crossentropy',metrics=['accuracy']) # - History = model.fit_generator(datagen.flow(x_train,y_train, batch_size=batch_size), epochs = 50, validation_data = (x_test,y_test), verbose = 1, steps_per_epoch=x_train.shape[0] // batch_size) plt.plot(History.history['accuracy']) plt.plot(History.history['val_accuracy']) plt.title('Model Accuracy') plt.ylabel('Accuracy') plt.xlabel('Epochs') plt.legend(['train', 'test']) plt.show() plt.plot(History.history['loss']) plt.plot(History.history['val_loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epochs') plt.legend(['train', 'test']) plt.show() del model K.clear_session()
Transfer Learning (2).ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # conda update -n base conda # - conda install -c conda-forge fbprophet # + #pip install --upgrade pip # - pip install tensorflow pip install seaborn pip install statsmodels pip install scikit-learn pip install keras pip list
gantry-jupyterhub/install-pip.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/rohit392000/Data_cleaning_/blob/main/Untitled0.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="EV-kNsP_zX9t" # + id="xirtiCtPzb89" # + id="HdrUyx8Yyi-F" import pandas as pd import numpy as np from nltk.tokenize import word_tokenize from nltk import pos_tag from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from sklearn.preprocessing import LabelEncoder from collections import defaultdict from nltk.corpus import wordnet as wn from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import model_selection, naive_bayes, svm from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt import seaborn as sns # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="-xge1XeS1JP5" outputId="4a212b36-3e68-4709-cb24-b3676e56d7f4" np.random.seed(500) Corpus = pd.read_csv(r"/content/amit.csv",encoding='latin-1') Corpus.head() # + colab={"base_uri": "https://localhost:8080/"} id="g9vjfxYp1sDG" outputId="30440ba6-7179-49a0-df1b-5491059cafc4" Corpus.info() # + colab={"base_uri": "https://localhost:8080/", "height": 367} id="TIc7XUPq16B_" outputId="26c46ad4-139e-4e62-f57a-11ba1c1b1dba" sns.countplot(Corpus.category) plt.xlabel('Category') plt.title('CountPlot') # + colab={"base_uri": "https://localhost:8080/"} id="O9FZYsYe1_kA" outputId="c58c6546-dd92-4586-933a-20c9e7686a95" import nltk nltk.download('punkt') nltk.download('wordnet') # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="yfr_NJIy27y4" outputId="ee1cd799-1dd4-44e9-c832-0085e9592182" # 1. Removing Blank Spaces Corpus['text'].dropna(inplace=True) # 2. Changing all text to lowercase Corpus['text_original'] = Corpus['text'] Corpus['text'] = str(Corpus['text']) Corpus['text'] = [entry.lower() for entry in Corpus['text']] # 3. Tokenization-In this each entry in the corpus will be broken into set of words Corpus['text']= [word_tokenize(entry) for entry in Corpus['text']] # 4. Remove Stop words, Non-Numeric and perfoming Word Stemming/Lemmenting. # WordNetLemmatizer requires Pos tags to understand if the word is noun or verb or adjective etc. By default it is set to Noun tag_map = defaultdict(lambda : wn.NOUN) tag_mp['J'] = wn.ADJ tag_map['V'] = wn.VERB tag_map['R'] = wn.ADV Corpus.head() # + colab={"base_uri": "https://localhost:8080/"} id="WRS7mVcB584L" outputId="d6f9fdd5-0356-4706-ec4e-4205ca1a8ed1" import nltk nltk.download('averaged_perceptron_tagger') nltk.download('stopwords') # + id="AYFUnWLs6sXX" for index,entry in enumerate(Corpus['text']): # Declaring Empty List to store the words that follow the rules for this step Final_words = [] # Initializing WordNetLemmatizer() word_Lemmatized = WordNetLemmatizer() # pos_tag function below will provide the 'tag' i.e if the word is Noun(N) or Verb(V) or something else. for word, tag in pos_tag(entry): # Below condition is to check for Stop words and consider only alphabets if word not in stopwords.words('english') and word.isalpha(): word_Final = word_Lemmatized.lemmatize(word,tag_map[tag[0]]) Final_words.append(word_Final) # The final processed set of words for each iteration will be stored in 'text_final' Corpus.loc[index,'text_final'] = str(Final_words) # + id="SybgBm4o7BsZ" Corpus.drop(['text'], axis=1) output_path = 'preprocessed_data.csv' Corpus.to_csv(output_path, index=False) # + id="jqshHzpY7Di5" Train_X, Test_X, Train_Y, Test_Y = model_selection.train_test_split(Corpus['text_final'],Corpus['category'],test_size=0.3) # + id="IWYZqMy47I70" Encoder = LabelEncoder() Train_Y = Encoder.fit_transform(Train_Y) Test_Y = Encoder.fit_transform(Test_Y) # + colab={"base_uri": "https://localhost:8080/"} id="acnG54i67Nje" outputId="3190a4db-6cc6-420e-da60-33ef9702adfd" Tfidf_vect = TfidfVectorizer(max_features=5000) Tfidf_vect.fit(Corpus['text_final']) Train_X_Tfidf = Tfidf_vect.transform(Train_X) Test_X_Tfidf = Tfidf_vect.transform(Test_X) print(Tfidf_vect.vocabulary_) # + colab={"base_uri": "https://localhost:8080/"} id="LhoQ6F5d7smB" outputId="f0ec62bc-9903-4c42-d843-18aeeb592677" print(Train_X_Tfidf) # + colab={"base_uri": "https://localhost:8080/"} id="irE3RCwV7ylL" outputId="2218cd0b-ff13-4f24-bb3b-eb09ad609ba6" # fit the training dataset on the NB classifier Naive = naive_bayes.MultinomialNB() Naive.fit(Train_X_Tfidf,Train_Y) # predict the labels on validation dataset predictions_NB = Naive.predict(Test_X_Tfidf) # Use accuracy_score function to get the accuracy print("Naive Bayes Accuracy Score -> ",accuracy_score(predictions_NB, Test_Y)*100) from sklearn import model_selection, naive_bayes, svm from sklearn.metrics import accuracy_score Naive = naive_bayes.MultinomialNB() Naive.fit(Train_X_Tfidf,Train_Y) # predict the labels on validation dataset predictions_NB = Naive.predict(Test_X_Tfidf) # Use accuracy_score function to get the accuracy print("Naive Bayes Accuracy Score -> ",accuracy_score(predictions_NB, Test_Y)*100) # Classifier - Algorithm - SVM # fit the training dataset on the classifier SVM = svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto') SVM.fit(Train_X_Tfidf,Train_Y) # predict the labels on validation dataset predictions_SVM = SVM.predict(Test_X_Tfidf) # + colab={"base_uri": "https://localhost:8080/"} id="R8ulkczm74tH" outputId="25b40190-0119-40f4-e3d0-5e6f8fe6663f" Train_X_Tfidf.shape # + colab={"base_uri": "https://localhost:8080/"} id="Ywh4QC8Q8BwE" outputId="20801f26-6012-4499-8741-478b9e3d523f" print(classification_report(Test_Y, predictions_NB)) # + colab={"base_uri": "https://localhost:8080/"} id="QHXWDjwh8p8o" outputId="a53edbc1-7d41-4456-f574-3a50c85ec9cb" # Classifier - Algorithm - SVM # fit the training dataset on the classifier SVM = svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto') SVM.fit(Train_X_Tfidf,Train_Y) # predict the labels on validation dataset predictions_SVM = SVM.predict(Test_X_Tfidf) # Use accuracy_score function to get the accuracy print("SVM Accuracy Score -> ",accuracy_score(predictions_SVM, Test_Y)*100) # + colab={"base_uri": "https://localhost:8080/"} id="-whI0S0F8r2Z" outputId="c2123a02-bc97-4614-8ddc-9c2b8436931d" print(classification_report(Test_Y,predictions_SVM)) # + id="8aZSRnbU8wEM"
Untitled0.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Short Answers # 1. False. The Mean-Variance optimization aims at minimizing the total variance given a return mean or maximizing the total mean given a variance, basically generates the best Sharpe ratio based on all the assets. Its strategy is not necessarily just simply longing the best Sharpe-ratio and shorting the worst Sharpe-ratio. In HW1, QAI doesn't have the worst sharpe ratio but we are shorting it. # 2. False. Investing LETF short-term makes more sense than investing long-term, because of volatility decay due to the leveraged factors. The market has to perform better after a certain loss because of the leveraged factor of 2x or 3x. # 3. I would suggest that we run the regression with an intercept, because we do not believe that the estimated mean is accurate, so we want to eliminate it to focus on explaining the variation. # 4. HDG is effective at tracking HFRI in-sample because it achieves a high correlation with MLFM-ES which has a high correlation with HFRI, so it should be good at in-sample data. However, when being out-of-sample, the compounded correlation could be damaging the credibility of the estimation. # 5. The high alpha that the hedge fund claims to find could be just missing betas from the model, which their model fails to explain, while our regression on the six assets explains better. Also, it could be just due to in-sample luck as well. import numpy as np import pandas as pd import statsmodels.formula.api as smf import statsmodels.api as sm import matplotlib.pyplot as plt import seaborn as sns import warnings import scipy sns.set() pd.set_option('display.float_format', lambda x: '%.4f' % x) path = 'proshares_analysis_data.xlsx' df_merrill_facs = pd.read_excel(path, sheet_name='merrill_factors').set_index('date') # # Allocation def compute_tangency(df_tilde): # use cov() to output sigma Sigma = df_tilde.cov() # create a copy of sigma matrix for getting inverse Sigma_adj = Sigma.copy() #inverse the matrix Sigma_inv = np.linalg.inv(Sigma_adj) # get number of element in cov matrix for later matrix multiplication N = Sigma.shape[0] # get the mean mu_tilde = df_tilde.mean() # apply the formula in slides to get the weights of each asset weights = Sigma_inv @ mu_tilde / (np.ones(N) @ Sigma_inv @ mu_tilde) # we than put these weights as a series named omega_tangency with named omega_tangency omega_tangency = pd.Series(weights, index=mu_tilde.index) return omega_tangency, mu_tilde, Sigma df_merrill_facs_data = df_merrill_facs.drop(columns = ["USGG3M Index"]) df_merrill_facs_data.head() USGG3M = df_merrill_facs["USGG3M Index"] df_merrill_facs_data = df_merrill_facs_data.subtract(USGG3M, axis = 0) omega_star, mu_tilde, Sigma = compute_tangency(df_merrill_facs_data * 12) print("The weights of the tangency portfolios are") omega_star.sort_values() # + def target_mv_portfolio(df_tilde, target_return=0.1): omega_tangency, mu_tilde, Sigma = compute_tangency(df_tilde) Sigma_adj = Sigma.copy() # if diagonalize_Sigma: # Sigma_adj.loc[:,:] = np.diag(np.diag(Sigma_adj)) Sigma_inv = np.linalg.inv(Sigma_adj) N = Sigma_adj.shape[0] delta_tilde = ((np.ones(N) @ Sigma_inv @ mu_tilde)/(mu_tilde @ Sigma_inv @ mu_tilde)) * target_return omega_star = delta_tilde * omega_tangency return omega_star # TODO: Annualized target return in footnote is not up to date omega_star = target_mv_portfolio(df_merrill_facs_data * 12, target_return=0.02 * 12) print("The weights of the optimal portfolios are") omega_star.sort_values() # - omega_star.sum() # We see that the sum of the weights of the optimal portfolio is not 1, which means that there is investment in the risk-free rate. # + # Mean mean = mu_tilde @ omega_star # Volatlity vol = np.sqrt(omega_star @ Sigma @ omega_star) / np.sqrt(12) # Sharpe ratio sharpe_ratio = mean / vol print("Mean:", mean, ", vol:", vol, ", sharpe_ratio:", sharpe_ratio) # - data_till_2018 = df_merrill_facs_data[:"2018"] omega_star = target_mv_portfolio(data_till_2018 * 12, target_return=0.02 * 12) print("The weights of the optimal portfolios using data till 2018 are") omega_star return_2019_2021 = 3 * mu_tilde @ omega_star print("The return from 2019 to 2021 is", return_2019_2021) # + # Mean mean = 3 * mu_tilde @ omega_star # Volatlity vol = np.sqrt(3) * np.sqrt(omega_star @ Sigma @ omega_star) / np.sqrt(12) # Sharpe ratio sharpe_ratio = mean / vol print("Mean:", mean, ", vol:", vol, ", sharpe_ratio:", sharpe_ratio) # - # I think that the out-of-sample fragility problem would be better than the equities. These are daily products and their prices remain more stable than these equities, so historical data would actually provide better insights into the future values than that of these equities. # # Hedging and Replication SPY = df_merrill_facs_data["SPY US Equity"] EEM = df_merrill_facs_data["EEM US Equity"] model = sm.OLS(EEM, SPY).fit() print("The optimal hedge ratio is", model.params[0]) print("For every dollar invested in EEM, I would short 0.925 dollar of SPY") model.summary() hedged_pos = EEM - model.params[0] * SPY mean = hedged_pos.mean() * 12 vol = model.resid.std() * np.sqrt(12) sharpe_ratio = mean / vol print("Mean:", mean, ", vol:", vol, ", sharpe_ratio:", sharpe_ratio) EEM.mean() # No it does not have the same mean as EEM, because we hedged with SPY which decreases the mean. Now since we don't include an intercept, the mean simply came from the residuals. X = df_merrill_facs_data[["SPY US Equity", "IWM US Equity"]] sm.OLS(EEM, X).fit().summary() # Because now we have to consider the correlation between SPY and IWM, and now the beyond only hedging for EEM, during the regression, we will even hedge SPY with IWM or vice versa, which makes the final result not only related to the relation between EEM and the regressors. From the result, we can see that the beta has a huge confidence interval, and we are seemingly just moving part of the responsibility to hedge from SPY to IWM without being more effcient and useful. # # Modeling Risk SPY = df_merrill_facs["SPY US Equity"] EFA = df_merrill_facs["EFA US Equity"] log_SPY = np.log(SPY).dropna() log_EFA = np.log(EFA).dropna() def prob_calc(mu, bar_r, sigma, years = 10): # use the formula derived in question3 # mean is the difference in mean in log 1965-1999 and in 2000-2021 x = - np.sqrt(years) * (mu - bar_r) / sigma val = scipy.stats.norm.cdf(x) return val # variance of difference var_diff = log_SPY.var() + log_EFA.var() - 2 * log_SPY.cov(log_EFA) # difference of two normal variables are normal prob_calc(log_SPY.mean() - log_EFA.mean(), 0, var_diff ** 0.5) sigma_rolling_EFA = EFA.shift(1).dropna().rolling(60).apply(lambda x: ((x**2).sum()/len(x))**(0.5)) sep_std = sigma_rolling_EFA.iloc[-1] estimate_VaR = 0 + scipy.stats.norm.cdf(0.01) * sep_std print("Estimate VaR is", estimate_VaR)
solutions/mid1/submissions/Midterm_1/Midterm1-Kaijun_Lin.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Chapter 9 - Data Science # ## Data Preparation # ## 0 - Setting up the notebook # + import json import random from datetime import date, timedelta import faker # - # ## 1 - Preparing the Data # create the faker to populate the data fake = faker.Faker() # + usernames = set() usernames_no = 1000 # populate the set with 1000 unique usernames while len(usernames) < usernames_no: usernames.add(fake.user_name()) # + def get_random_name_and_gender(): skew = .6 # 60% of users will be female male = random.random() > skew if male: return fake.name_male(), 'M' else: return fake.name_female(), 'F' # for each username, create a complete user profile # simulate user data coming from an API. It is a list # of JSON strings (users). def get_users(usernames): users = [] for username in usernames: name, gender = get_random_name_and_gender() user = { 'username': username, 'name': name, 'gender': gender, 'email': fake.email(), 'age': fake.random_int(min=18, max=90), 'address': fake.address(), } users.append(json.dumps(user)) return users users = get_users(usernames) users[:3] # + # campaign name format: # InternalType_StartDate_EndDate_TargetAge_TargetGender_Currency def get_type(): # just some gibberish internal codes types = ['AKX', 'BYU', 'GRZ', 'KTR'] return random.choice(types) def get_start_end_dates(): duration = random.randint(1, 2 * 365) offset = random.randint(-365, 365) start = date.today() - timedelta(days=offset) end = start + timedelta(days=duration) def _format_date(date_): return date_.strftime("%Y%m%d") return _format_date(start), _format_date(end) def get_age(): age = random.randrange(20, 46, 5) diff = random.randrange(5, 26, 5) return '{}-{}'.format(age, age + diff) def get_gender(): return random.choice(('M', 'F', 'B')) def get_currency(): return random.choice(('GBP', 'EUR', 'USD')) def get_campaign_name(): separator = '_' type_ = get_type() start, end = get_start_end_dates() age = get_age() gender = get_gender() currency = get_currency() return separator.join( (type_, start, end, age, gender, currency)) # - # campaign data: # name, budget, spent, clicks, impressions def get_campaign_data(): name = get_campaign_name() budget = random.randint(10**3, 10**6) spent = random.randint(10**2, budget) clicks = int(random.triangular(10**2, 10**5, 0.2 * 10**5)) impressions = int(random.gauss(0.5 * 10**6, 2)) return { 'cmp_name': name, 'cmp_bgt': budget, 'cmp_spent': spent, 'cmp_clicks': clicks, 'cmp_impr': impressions } # + # assemble the logic to get the final version of the rough data # data will be a list of dictionaries. Each dictionary will follow # this structure: # {'user': user_json, 'campaigns': [c1, c2, ...]} # where user_json is the JSON string version of a user data dict # and c1, c2, ... are campaign dicts as returned by # get_campaign_data def get_data(users): data = [] for user in users: campaigns = [get_campaign_data() for _ in range(random.randint(2, 8))] data.append({'user': user, 'campaigns': campaigns}) return data # - # ## 2 - Cleaning the data # + # fetch simulated rough data rough_data = get_data(users) rough_data[:2] # let's take a peek # + # Let's start from having a different version of the data # I want a list whose items will be dicts. Each dict is # the original campaign dict plus the user JSON data = [] for datum in rough_data: for campaign in datum['campaigns']: campaign.update({'user': datum['user']}) data.append(campaign) data[:2] # let's take another peek # + # Warning: Uncommenting and executing this cell will overwrite data.json #with open('data.json', 'w') as stream: # stream.write(json.dumps(data))
ch13/ch13-dataprep.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- import numpy as np import os import glob # cd /scratch/rmb456/multif0_ismir2017/training_data_with_blur/ # ls # + dirname = 'melody1' files = glob.glob(os.path.join(dirname, '*.npz')) for f in files: data = np.load(f) bname = os.path.basename(f).split('.')[0] print(bname) input_bname = "{}_input.npy".format(bname) output_bname = "{}_output.npy".format(bname) input_path = os.path.join(dirname, 'inputs', input_bname) output_path = os.path.join(dirname, 'outputs', output_bname) np.save(input_path, data['data_in']) np.save(output_path, data['data_out']) # + dirname = 'melody2' files = glob.glob(os.path.join(dirname, '*.npz')) for f in files: data = np.load(f) bname = os.path.basename(f).split('.')[0] print(bname) input_bname = "{}_input.npy".format(bname) output_bname = "{}_output.npy".format(bname) input_path = os.path.join(dirname, 'inputs', input_bname) output_path = os.path.join(dirname, 'outputs', output_bname) np.save(input_path, data['data_in']) np.save(output_path, data['data_out']) # + dirname = 'melody3' files = glob.glob(os.path.join(dirname, '*.npz')) for f in files: data = np.load(f) bname = os.path.basename(f).split('.')[0] print(bname) input_bname = "{}_input.npy".format(bname) output_bname = "{}_output.npy".format(bname) input_path = os.path.join(dirname, 'inputs', input_bname) output_path = os.path.join(dirname, 'outputs', output_bname) np.save(input_path, data['data_in']) np.save(output_path, data['data_out']) # + dirname = 'multif0_complete' files = glob.glob(os.path.join(dirname, '*.npz')) for f in files: bname = os.path.basename(f).split('.')[0] print(bname) input_bname = "{}_input.npy".format(bname) output_bname = "{}_output.npy".format(bname) input_path = os.path.join(dirname, 'inputs', input_bname) output_path = os.path.join(dirname, 'outputs', output_bname) if os.path.exists(input_path) and os.path.exists(output_path): print(" > Already done!") continue try: data = np.load(f) np.save(input_path, data['data_in']) np.save(output_path, data['data_out']) except: print("failed on {}".format(f)) os.remove(f) # + dirname = 'multif0_incomplete' files = glob.glob(os.path.join(dirname, '*.npz')) for f in files: bname = os.path.basename(f).split('.')[0] print(bname) input_bname = "{}_input.npy".format(bname) output_bname = "{}_output.npy".format(bname) input_path = os.path.join(dirname, 'inputs', input_bname) output_path = os.path.join(dirname, 'outputs', output_bname) if os.path.exists(input_path) and os.path.exists(output_path): print(" > Already done!") continue try: data = np.load(f) np.save(input_path, data['data_in']) np.save(output_path, data['data_out']) except: print("failed on {}".format(f)) os.remove(f) # - files = glob.glob(os.path.join(dirname, '*.npz')) f = files[0] dat = np.load(f) x = dat['data_in'] x.shape f
notebooks/Split npz files.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda root] # language: python # name: conda-root-py # --- # <h3>Implementação da classe LVQ</h3> # + import csv import random import numpy as np class LVQ(): def __init__(self, dataset): """ Construtor da classe :param nome_arquivo: nome do arquivo csv que contem os dados """ self.dados = dataset self.dataset = dataset self.qtd_caracteristicas = 0 self.amplitudes = [] self.qtd_caracteristicas = len(self.dados[0])-1 def normalizar(self): """ Normalizada todas as caracteristicas para um intervalo de 0 - 1, para todas tenham o mesmo peso na classificacao """ lista = []*(len(self.dados[0])-1) self.amplitudes = [] for caracteristica in range(len(self.dados[0])-1): lista = [elemento[caracteristica] for elemento in self.dados] self.amplitudes += [[max(lista), min(lista)]] for elemento in self.dados: elemento[caracteristica] = (elemento[caracteristica] - min(lista))/(max(lista)+min(lista)) def triagem(self, split: float=0.65): """ Divide aleatoriament os elementos do conjunto de dados em dois subconjuntos: teste e treino :param split: de 0 a 1 -> 'porcentagem' dos elementos que serao do conjunto de treino """ self.treino, self.teste = [], [] for elemento in self.dados: if random.random() < split: self.treino += [elemento] else: self.teste += [elemento] def resumir(self, n: float=10, e: float=10, t: float=0.4): """ Retorna o codebook dos dados, ou seja, os elementos que melhor representam o todo :param t: taxa de aprendizado inicial :param e: numero de epocas :param n: numero de elementos do coodbook """ #Geracacao aleatorio dos elementos iniciais do codebook self.codebook = [[]]*n for i in range(n): self.codebook[i] = [0] * (self.qtd_caracteristicas + 1) for caracteristica in range(self.qtd_caracteristicas + 1): self.codebook[i][caracteristica] = random.choice(self.dados)[caracteristica] for epoca in range(e): taxa = t * (1.0-(epoca/float(e))) for elemento in self.treino: representante = self.encontrar_mais_proximo(elemento, self.codebook) o = -1 if representante[-1] == elemento[-1]: o = 1 for caracteristica in range(self.qtd_caracteristicas): erro = (elemento[caracteristica]-representante[caracteristica]) representante[caracteristica] += (erro * taxa * o) def testar(self): """ Executa a classificacao para cada elemento do conjunto teste e retorna a precisao do algoritmo """ qtd_teste = len(self.teste) precisao = 100.0 for elemento in self.teste: bmu = self.encontrar_mais_proximo(elemento, self.codebook) if bmu[-1] != elemento[-1]: precisao -= (1/qtd_teste)*100 return precisao def encontrar_mais_proximo(self, elemento, lista): """ Executa a classificacao para cada elemento do conjunto teste e retorna a precisao do algoritmo :param elemento: vetor para o qual deve-se vetor mais proximo de uma dada lista :param lista: lista de vetores """ resposta = [lista[0], spatial.distance.euclidean(elemento[0:-1], lista[0][0:-1])] for i in lista: distancia = spatial.distance.euclidean(elemento[0:-1], i[0:-1]) if distancia < resposta[1]: resposta = [i, distancia] return resposta[0] @property def representantes(self): """ Retorna o codebook "original", com as caracteristicas em seus intervalos originais. Ou seja, retorna o codebook desnormalizado, caso ele tenha sido normalizado """ representantes_desnormalizados = [[]]*len(self.codebook) if self.amplitudes: for index, representante in enumerate(self.codebook): representante_desnormalizado = [] for caracteristica in range(self.qtd_caracteristicas): aux = ((self.amplitudes[caracteristica][0] + self.amplitudes[caracteristica][1])\ * representante[caracteristica]) + self.amplitudes[caracteristica][1] representante_desnormalizado += [aux] representante_desnormalizado += [representante[-1]] representantes_desnormalizados[index] = representante_desnormalizado else: return self.codebook return representantes_desnormalizados @property def classes(self): """ Retorna as classes do dataset """ classes = [] for elemento in self.dados: if elemento[-1] not in classes: classes.append(elemento[-1]) return classes # - # <h3>Algumas outras funções utilizadas</h3> # + import random def importar_dataset(arquivo_csv: str=None): """ Carrega os dados iniciais da classe através de um arquivo csv. Esperar-se um arquivo possua linhas com n colunas, de modo que a n-ézima represente a classe do elemento e as anteriores representem, cada uma, uma caracteristica diferente. :param arquivo_csv: nome do arquivo csv """ dados = [] with open(arquivo_csv, 'r') as arquivo_csv: arquivo = csv.reader(arquivo_csv) for index, linha in enumerate(arquivo): if linha: dados += [list(map(float, linha[0:-1]))] dados[index] += [linha[-1]] return dados def random_cores(qtd: int=3): """ Retorna aleatoriamente cores no formato hexademal de acordo com a quantidade pedida """ lista = [(210,180,140), (139,69,19), (244,164,96), (85,107,47), (0,255,0), (102,205,170), (127,255,212), (72,209,204), (0,255,255), (176,196,222), (30,144,255), (0,0,255), (220,20,60), (255,105,180), (255,0,255), (139,0,139), (255,192,203), (255,0,0), (250,128,114), (255,165,0), (255,255,0)] random.shuffle(lista) cores = lista[0:qtd] resposta = [] for cor in cores: resposta += ['#%02x%02x%02x' % cor] return resposta # - # <h3>Aplicação da classe LVQ na classificação do conjunto de dados da IRIS</h3> # + import matplotlib.pyplot as plt dataset = importar_dataset("datas/IRIS.csv") # Dados normalizados print("Algoritmo com os dados normalizados entre 0 - 1") iris_norm = LVQ(dataset) iris_norm.triagem(0.75) iris_norm.normalizar() iris_norm.resumir(n=8, e=13, t=0.5) print("Precisão: ", iris_norm.testar(), "% \n") classes = iris_norm.classes classes_cor = {} cores = random_cores(len(classes)) for index, classe in enumerate(classes): classes_cor[classe] = cores[index] for elemento in iris_norm.dataset: plt.plot(elemento[0], elemento[1], 'o', color=classes_cor[elemento[-1]]) for representante in iris_norm.codebook: plt.plot(representante[0], representante[1], 'D' , ms=10, mfc='none', color=classes_cor[representante[-1]]) plt.show() # Sem normalização print("Algoritmo com os dados não normalizados") iris = LVQ(dataset) iris.triagem(0.75) iris.resumir(n=8, e=13, t=0.5) print("Precisão: ", iris.testar(),"% \n") # for representante in iris.representantes: # print(representante)
lvq.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <h1 style="text-align:center;">Nuc Adder <span style="text-align:center;font-size: 0.5em;">1.5.1</span></h1> # <h2 style="text-align:center;">Mito Hacker Toolkit <i style="font-size: 0.5em;">0.7.1</i></h2> # <h3 style="text-align:center;">Kashatus Lab @ UVA</h3> # # Welcome to Nuc Adder # #### Nuc Adder is part of Mito Hacker toolkit that enables you to make images that are missing nuclei staining compatible with CeMiA Cell Catcher and Mito Miner. # This Jupyter notebook provides you with step-by-step directions to transform your images. # ## 1) Importing necessary libraries # Please check the requirements in the Readme file. # + #Base import os import cv2 import numpy as np from copy import deepcopy import matplotlib.pyplot as plt import random #Interaction import ipywidgets as widgets from IPython.display import display from ipywidgets import interact, interactive, fixed, interact_manual, IntSlider, Checkbox, FloatSlider, Dropdown from IPython.display import clear_output #Core Functions import cemia55s as cemia layout = widgets.Layout(width='800px') # - # ## 2) Locate and Sample Files # # <br> # <details> # <summary><span style="font-size:16px;font-weight: bold; color:red">Instructions</span></summary> # # # #### <span style="color:red;">Interact with the code: </span> Please enter the relative address of the folder that contains your images. # # #### <span style="color:red;">You should interact with the next cell: </span> Please run the next cell, a box will appear. Enter the relative/absolute address of the folder that contains your images inside the box, then press enter. # # # #### <span style="color:red;">Examples: </span> # * Use . if the images are in the same folder as this file # * If the folder of the images is named "test" and is located on the upper level of the current folder, the address would be ../test (Mac) # # #### <span style="color:red;">Note: </span> # * It is preferred to have the folder of your images in the same folder as the current file that you are running # * After you enetered the address to your files in the box, you should press enter key. # # </details> address,file_list = cemia.address() cleaned_list = cemia.random_files(address,file_list,len(file_list)) cemia.nuc_adder_make_folders(address) # ## 3) Adjusting The Nuclei Size # # #### Cell Catcher and Mito Miner need nuclei boundary to assess the out-of-plane signal (Background Intensity). Apparently, nuclei staining is missing from your images, and that's why you are here! # # #### First things first! Let's find a proper nuclei size for your set of images. # <br> # <details> # <summary><span style="font-size:16px;font-weight: bold; color:red">Instructions</span></summary> # # # #### <span style="color:red;">Interaction Required: </span> # * Identify a proper nuclei size (as if the nuclei were stained in your images) for your set of images by adjusting the handle. # * You can move the simulated nucleus on the image. to ensure proper sizing. (The location has no effect of future analysis, and is for visualization purposes only. # # #### <span style="color:red;">Note: </span> # * We suggest to be a bit conservative with your size choice. Large nuclei sizes, may cause overlap with the actual mitochondrial network, and result in inaccurate background estimations. # * The circle size should be large enough to sample enough background pixels, and small enough to not have an overlap with mitochondrial network accross different cells # # </details> # + size = plt.imread(os.path.join(address,cleaned_list[0])).shape radii = [] @interact(file=cleaned_list, radius=IntSlider(min=25,max=100,step=5,value=10,continuous_update=False,layout=layout), x=IntSlider(min=100,max=size[0]-100,step=10,value=150,continuous_update=False,layout=layout), y=IntSlider(min=100,max=size[0]-100,step=10,value=150,continuous_update=False,layout=layout), filled=Checkbox(value=True,description='Filled',layout = layout),) def segment_nucleus(file, radius, x,y, filled): rad = cemia.simulate_circle(address, file, x,y,radius,filled) radii.append(rad) # - # ## 4) Marking nuclei centers in your images # # <br> # <details> # <summary><span style="font-size:16px;font-weight: bold; color:red">Instructions & Notes</span></summary> # # # ### <span style="color:red;"><b>Interaction with an external window is required.</b> </span> # #### 1) In this section, all the images in your target folder, will be displayed one-by-one. # #### 2) Once an image is displayed, an external window with the same image will open up. # #### 3) <span style="color:red;">Important: </span>On the external window, for each cell on the image, you have to <span style="color:red;">single click </span> (left click) on the point where you believe would be the center of the nucleus in that cell. Repeat this process for all the cells on the image. # #### 4) After you marked all the desired cell centers on the image, press "q" on the keyboard to go to the next image. # #### 5) Repeat this process for all the images in your target folder. # #### 6) Transformed images are saved in a sub directory names "transformed" in your target folder. # # #### <span style="color:red;">Note: </span> # * Mac Users, may experince that the external window for the last image won't close properly after pressing "q". This is not an issue. After you press "q" for the last image, on the Jupyter notebook you will see the message "You are all set!", which indicates you are all set! # * Windows users will not experince this issue. # # </details> # + roi_array = [] for image in cleaned_list: image_address = os.path.join(address,image) img1 = plt.imread(image_address,-1) img = deepcopy(img1) plt.figure(figsize=(10,10)) plt.imshow(img1) plt.show() how_many = 1#cemia.how_many_cells() for i in range(how_many): drawing=False # true if mouse is pressed mode=True # if True, draw rectangle. Press 'm' to toggle to curve points = [] roi_corners = [] # mouse callback function def boundary(event,former_x,former_y,flags,param): global current_former_x,current_former_y,drawing, mode if event==cv2.EVENT_LBUTTONDOWN: drawing=True current_former_x,current_former_y=former_x,former_y points.append((current_former_x,current_former_y)) elif event==cv2.EVENT_MOUSEMOVE: if drawing==True: if mode==True: cv2.line(img,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),3) current_former_x = former_x current_former_y = former_y points.append((current_former_x,current_former_y)) #print former_x,former_y elif event==cv2.EVENT_LBUTTONUP: drawing=False if mode==True: cv2.line(img,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),3) current_former_x = former_x current_former_y = former_y points.append((current_former_x,current_former_y)) return former_x,former_y, points cv2.namedWindow("Kashatus Lab",cv2.WINDOW_NORMAL) cv2.resizeWindow("Kashatus Lab",img.shape[0]//2,img.shape[1]//2) cv2.setMouseCallback('Kashatus Lab',boundary) while(1): cv2.imshow('Kashatus Lab',cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) if cv2.waitKey(1) & 0xFF == ord('q'): roi_corners = np.array(points, dtype=np.int32); roi_array.append(roi_corners) break cv2.waitKey(1) cv2.destroyAllWindows() cv2.waitKey(1) img_temp = deepcopy(img) print(img.shape) for x,y in points: cv2.circle(img_temp, (x,y), radii[-1], color=(0,0,255), thickness=-1, lineType=8, shift=0) img[:,:,2] = img_temp[:,:,2] # plt.figure() # plt.imshow(img[:,:,0]) trans_file_name = image[:image.rfind('.')] + '_transformed' + image[image.rfind('.'):] output_address = os.path.join(address,'transformed', trans_file_name) cv2.imwrite(output_address,cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) print('\nYou are all set!') print(f'\nYour transformed images are saved at: "{address}/transformed/" and are eady to to be used by other tools at CeMiA.') # - # # The End!
Nuc_Adder.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd # + df = pd.read_csv('MBE_WBE_Matches_in_GBH_Data.csv') df = df.drop(['LEGEND', 'Unnamed: 2'], axis=1) df_contractors = df['Contractors'] df_contractors.columns = ['GeneralContractor'] df_sub = df['Sub-Contractors'] df_sub.columns = ['SubContractor'] # - def cleaner(dirty_list): """ takes in a list of strings and cleans those by removing special characters and trimming excess whitespace to get rid of potential duplicates """ spec_chars = ["!",'"',"#","%","&","'","(",")", "*","+",",", "-",".","/",":",";","<", "=",">","?","@","[", "\\","]","^","_", "`","{","|","}","~","–", "\xc2", "\xa0", "\x80", "\x9c", "\x99", "\x94", "\xad", "\xe2", "\x9d", "\n"] for i in range(len(dirty_list)): for char in spec_chars: dirty_list[i] = dirty_list[i].replace(char, ' ') dirty_list[i] = dirty_list[i].strip() dirty_list[i] = dirty_list[i].split() dirty_list[i] = ' '.join(dirty_list[i]) return dirty_list # + data = pd.read_csv('Copy_of_wgbh.csv', index_col='DateEntered', parse_dates=True) # convert index to yearly DateTime object data.index = data.index.to_period('Y') # drop everything but race, sub-contractor columns data_sub = data.drop(['Agency', 'ProjectName', 'ProjectAddress_1', 'GeneralContractor', 'Developer', 'SubContractorAddress_1', 'SubContractorAddress_2', 'Trade', 'MINOR'], axis=1) data_contractors = data.drop(['Agency', 'ProjectName', 'ProjectAddress_1', 'SubContractor', 'Developer', 'SubContractorAddress_1', 'SubContractorAddress_2', 'Trade', 'MINOR'], axis=1) # + data_sub = data_sub.drop(['SEX', 'RESIDENT'], axis=1) data_contractors = data_contractors.drop(['SEX', 'RESIDENT'], axis=1) cleaned_subs = cleaner(data_sub['SubContractor'].to_list()) data_sub['SubContractor'] = cleaned_subs cleaned_contractors = cleaner(data_contractors['GeneralContractor'].to_list()) data_contractors['GeneralContractor'] = cleaned_contractors # - data_sub # + summary_subs = pd.DataFrame(columns=['SubContractor', 'CAUCASIAN', 'BLACK', 'HISPANIC', 'ASIAN', 'OTHER', 'Total']) subs = data_sub['SubContractor'].unique() print('Beginning Grouping') groups = data_sub.groupby(data_sub.SubContractor) print('Done Grouping By SubContractor') # compute percentage of employees for each developer by race for i in range(len(subs)): temp = groups.get_group(subs[i]) filt1 = temp['Race_Desc'] == 'CAUCASIAN' filt2 = temp['Race_Desc'] == 'BLACK' filt3 = temp['Race_Desc'] == 'ASIAN' filt4 = temp['Race_Desc'] == 'HISPANIC' filt5 = temp['Race_Desc'] == 'OTHER' CAUCASIAN = temp[filt1] BLACK = temp[filt2] ASIAN = temp[filt3] HISPANIC = temp[filt4] OTHER = temp[filt5] CAUCASIAN_hours = CAUCASIAN['TotalHours'].sum() / CAUCASIAN.shape[0] BLACK_hours = BLACK['TotalHours'].sum() / BLACK.shape[0] ASIAN_hours = ASIAN['TotalHours'].sum() / ASIAN.shape[0] HISPANIC_hours = HISPANIC['TotalHours'].sum() / HISPANIC.shape[0] OTHER_hours = OTHER['TotalHours'].sum() / OTHER.shape[0] summary_subs.loc[len(summary_subs.index)] = [subs[i], CAUCASIAN_hours, BLACK_hours, HISPANIC_hours, ASIAN_hours, OTHER_hours, (CAUCASIAN_hours + BLACK_hours + HISPANIC_hours + ASIAN_hours + OTHER_hours)] summary_subs = summary_subs.fillna(0) summary_subs.loc[len(summary_subs.index) - 1, ['Total']] = summary_subs.loc[len(summary_subs.index) - 1]['ASIAN'] + summary_subs.loc[len(summary_subs.index) - 1]['CAUCASIAN'] + summary_subs.loc[len(summary_subs.index) - 1]['HISPANIC'] + summary_subs.loc[len(summary_subs.index) - 1]['BLACK'] + summary_subs.loc[len(summary_subs.index) - 1]['OTHER'] # + summary_contractors = pd.DataFrame(columns=['GeneralContractor', 'CAUCASIAN', 'BLACK', 'HISPANIC', 'ASIAN', 'OTHER', 'Total']) contractors = data_contractors['GeneralContractor'].unique() print('Beginning Grouping') groups = data_contractors.groupby(data_contractors.GeneralContractor) print('Done Grouping By GeneralContractor') # compute percentage of employees for each developer by race for i in range(len(contractors)): temp = groups.get_group(contractors[i]) filt1 = temp['Race_Desc'] == 'CAUCASIAN' filt2 = temp['Race_Desc'] == 'BLACK' filt3 = temp['Race_Desc'] == 'ASIAN' filt4 = temp['Race_Desc'] == 'HISPANIC' filt5 = temp['Race_Desc'] == 'OTHER' CAUCASIAN = temp[filt1] BLACK = temp[filt2] ASIAN = temp[filt3] HISPANIC = temp[filt4] OTHER = temp[filt5] CAUCASIAN_hours = CAUCASIAN['TotalHours'].sum() / CAUCASIAN.shape[0] BLACK_hours = BLACK['TotalHours'].sum() / BLACK.shape[0] ASIAN_hours = ASIAN['TotalHours'].sum() / ASIAN.shape[0] HISPANIC_hours = HISPANIC['TotalHours'].sum() / HISPANIC.shape[0] OTHER_hours = OTHER['TotalHours'].sum() / OTHER.shape[0] summary_contractors.loc[len(summary_contractors.index)] = [contractors[i], CAUCASIAN_hours, BLACK_hours, HISPANIC_hours, ASIAN_hours, OTHER_hours, (CAUCASIAN_hours + BLACK_hours + HISPANIC_hours + ASIAN_hours + OTHER_hours)] summary_contractors = summary_contractors.fillna(0) summary_contractors.loc[len(summary_contractors.index) - 1, ['Total']] = summary_contractors.loc[len(summary_contractors.index) - 1]['ASIAN'] + summary_contractors.loc[len(summary_contractors.index) - 1]['CAUCASIAN'] + summary_contractors.loc[len(summary_contractors.index) - 1]['HISPANIC'] + summary_contractors.loc[len(summary_contractors.index) - 1]['BLACK'] + summary_contractors.loc[len(summary_contractors.index) - 1]['OTHER'] # - summary_contractors summary_subs.to_csv('Avg_Hours_Assigned_by_Race_SubContractors.csv') summary_contractors.to_csv('Avg_Hours_Assigned_by_Race_Contractors.csv') # + mbe_subs = df_sub.to_list() summary_subs_mbe_wbe = summary_subs.loc[summary_subs['SubContractor'].isin(mbe_subs)] mbe_contractors = df_contractors.to_list() summary_contractors_mbe_wbe = summary_contractors.loc[summary_contractors['GeneralContractor'].isin(mbe_contractors)] # - summary_subs_mbe_wbe.to_csv('Avg_Hours_Assigned_By_Race_MBEorWBE_Subcontractors.csv') summary_contractors_mbe_wbe.to_csv('Avg_Hours_Assigned_By_Race_MBEorWBE_Contractors.csv') non_mbe_wbe_subs = summary_subs.loc[~summary_subs['SubContractor'].isin(mbe_subs)] non_mbe_wbe_contractors = summary_contractors.loc[~summary_contractors['GeneralContractor'].isin(mbe_contractors)] avg_non_mbe_wbe_contractors = non_mbe_wbe_contractors[['CAUCASIAN', 'BLACK', 'HISPANIC', 'ASIAN', 'OTHER']].sum() / non_mbe_wbe_contractors.shape[0] avg_non_mbe_wbe_contractors avg_non_mbe_wbe_subs = non_mbe_wbe_subs[['CAUCASIAN', 'BLACK', 'HISPANIC', 'ASIAN', 'OTHER']].sum() / non_mbe_wbe_subs.shape[0] avg_non_mbe_wbe_subs avg_mbe_wbe_contractors = summary_contractors_mbe_wbe[['CAUCASIAN', 'BLACK', 'HISPANIC', 'ASIAN', 'OTHER']].sum() / summary_contractors_mbe_wbe.shape[0] avg_mbe_wbe_contractors avg_mbe_wbe_subs = summary_subs_mbe_wbe[['CAUCASIAN', 'BLACK', 'HISPANIC', 'ASIAN', 'OTHER']].sum() / summary_subs_mbe_wbe.shape[0] avg_mbe_wbe_subs sub_avgs = pd.concat([avg_non_mbe_wbe_subs, avg_mbe_wbe_subs], axis=1) sub_avgs.columns = ['Non-MBE/WBE Sub-Contractors', 'MBE/WBE Sub-Contractors'] sub_avgs.plot(kind='bar', figsize=(12, 6), ylabel='Hours Assigned') contractor_avgs = pd.concat([avg_non_mbe_wbe_contractors, avg_mbe_wbe_contractors], axis=1) contractor_avgs.columns = ['Non-MBE/WBE Contractors', 'MBE/WBE Contractors'] contractor_avgs.plot(kind='bar', figsize=(12, 6), ylabel='Hours Assigned') non_avg, avg = contractor_avgs.sum() contractor_avgs_pct = contractor_avgs.copy() for i in range(contractor_avgs_pct.shape[0]): contractor_avgs_pct.iloc[i]['Non-MBE/WBE Contractors'] = contractor_avgs_pct.iloc[i]['Non-MBE/WBE Contractors'] / non_avg contractor_avgs_pct.iloc[i]['MBE/WBE Contractors'] = contractor_avgs_pct.iloc[i]['MBE/WBE Contractors'] / avg contractor_avgs_pct.plot(kind='bar', figsize=(12, 6), ylabel='Percentage of Hours Assigned') non_avg_subs, avg_subs = sub_avgs.sum() subs_avgs_pct = sub_avgs.copy() for i in range(subs_avgs_pct.shape[0]): subs_avgs_pct.iloc[i]['Non-MBE/WBE Sub-Contractors'] = subs_avgs_pct.iloc[i]['Non-MBE/WBE Sub-Contractors'] / non_avg_subs subs_avgs_pct.iloc[i]['MBE/WBE Sub-Contractors'] = subs_avgs_pct.iloc[i]['MBE/WBE Sub-Contractors'] / avg_subs subs_avgs_pct.plot(kind='bar', figsize=(12, 6), ylabel='Percentage of Hours Assigned')
WGBH-Boston Jobs/Boston_Jobs/Avg_Hours_Assigned_by_Race_MBEWBE.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # _Development: Version 3 of Data Ingestion Python Script_ # !gitpython --version from datetime import datetime import git import re from pathlib import Path import pandas as pd import time import subprocess from google.cloud import storage twarc_command = ( f'twarc hydrate daypath/day_clean-dataset.txt > ' + f'daypath/day_clean-dataset.json' ) print(twarc_command) def setpath(): return Path.home() # + #homepath = setpath() #homepath # - def clone_panacea_repo(homepath): try: print('Cloning repository...') gitrepo = 'https://github.com/thepanacealab/covid19_twitter.git' git.Repo.clone_from(gitrepo, homepath / 'thepanacealab_covid19') print('Repo cloned.') except Exception as e: print(e) # + #clone_panacea_repo(homepath) # - def panacea_pull(panacearepopath): g = git.cmd.Git(panacearepopath) result = g.pull() return result # + #panacearepopath = setpath() / 'thepanacealab_covid19' #panacea_pull(panacearepopath) # - def make_raw_folders(myrepopath, daily_list): # for day in list of daily folders from Panacea Labs GitHub repo for day in daily_list: if (myrepopath / 'data' / 'raw_dailies' / day).exists(): pass else: newpath = myrepopath / 'data' / 'raw_dailies' / day newpath.mkdir() def make_proc_folders(myrepopath, daily_list): # for day in list of daily folders from Panacea Labs GitHub repo for day in daily_list: if (myrepopath / 'data' / 'processed_dailies' / day).exists(): pass else: newpath = myrepopath / 'data' / 'processed_dailies' / day newpath.mkdir() def get_txt_data(myrepopath, panacearepopath, daily_list): # for day in list of daily folders from Panacea Labs GitHub Repo for day in daily_list: # create path variables to access data in Panacea repo, and path to local storage folder storagepath = myrepopath / 'data' / 'raw_dailies' / day datapath = panacearepopath / 'dailies' / day # get list of contents within local daily storage folder files = [x.name for x in storagepath.iterdir()] # if txt file with that date is in daily storage folder, print confirmation if f'{day}_clean-dataset.txt' in files: pass # print(f'Txt detected in {storagepath}') # else read in compressed tsv file with Tweet IDs from Panacea repo & store txt file # with Tweet IDs in local daily storage folder else: df = pd.read_csv(f'{datapath}/{day}_clean-dataset.tsv.gz', sep='\t', usecols=['tweet_id'], compression='gzip') df.to_csv(f'{storagepath}/{day}_clean-dataset.txt', header=None, index=None) def main_setup(): # set up path to current working directory & path to directory containing Panacea data homepath = setpath() myrepopath = Path.cwd().parent.parent panacearepopath = homepath / 'thepanacealab_covid19' if myrepopath.exists(): pass else: myrepopath.mkdir() # if Panacea lab folder in working directory, print confirmation, else clone the repo if 'thepanacealab_covid19' in [x.name for x in homepath.iterdir()]: print('Panacea Labs COVID-19 GitHub has already been cloned...') else: clone_panacea_repo(path) # pull any recent updates from Panacea Lab repo pull_result = panacea_pull(panacearepopath) print(pull_result) # create list of daily folders located in Panacea repo (which contains data we need to access) file_ignore = ['README.md', '.ipynb_checkpoints'] daily_list = [x.name for x in sorted((panacearepopath / 'dailies').iterdir())\ if x.name not in file_ignore] # check to see if data sub-directory exists in my repo mydatapath = myrepopath / 'data' if mydatapath.exists(): pass else: mydatapath.mkdir() # if raw_dailies sub-folder exists make folders for raw data and get text of IDs if 'raw_dailies' in list(x.name for x in mydatapath.iterdir()): make_raw_folders(myrepopath, daily_list) get_txt_data(myrepopath, panacearepopath, daily_list) # else make raw_dailies folder, then make folders for raw data and get text of IDs else: mydailypath = mydatapath / 'raw_dailies' mydailypath.mkdir() make_raw_folders(myrepopath, daily_list) get_txt_data(myrepopath, panacearepopath, daily_list) # check to see if processed_dailies sub-folder exists then create daily folders if 'processed_dailies' in list(x.name for x in mydatapath.iterdir()): make_proc_folders(myrepopath, daily_list) else: myprocdailypath = mydatapath / 'processed_dailies' myprocdailypath.mkdir() make_proc_folders(myrepopath, daily_list) # + #main_setup() # - def blob_exists(bucket_name, source_file_name): storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(source_file_name) return blob.exists() def storage_check(daily_list): bucket_name = 'thepanacealab_covid19twitter' nojson = [] for day in daily_list: source_file_name1 = f'dailies/{day}/{day}_clean-dataset.json' source_file_name2 = f'dailies/{day}/panacealab_{day}_clean-dataset.json' json1_exist = blob_exists(bucket_name, source_file_name1) json2_exist = blob_exists(bucket_name, source_file_name2) if json1_exist or json2_exist == True: pass else: nojson.append(day) return nojson def upload_blob(bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" # bucket_name = "your-bucket-name" # source_file_name = "local/path/to/file" # destination_blob_name = "storage-object-name" storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print(f"File {source_file_name} uploaded to {destination_blob_name}.") # + #file_ignore = ['README.md', '.ipynb_checkpoints'] #daily_list = [x.name for x in sorted((panacearepopath / 'dailies').iterdir())\ # if x.name not in file_ignore] # + #def implicit(): # from google.cloud import storage # If you don't specify credentials when constructing the client, the # client library will look for credentials in the environment. # storage_client = storage.Client() # Make an authenticated API request # buckets = list(storage_client.list_buckets()) # print(buckets) # + #implicit() # + #nojson = storage_check(daily_list) # + #nojson # + #previous3 = nojson[-3:] #print(previous3) #testday = nojson[-1] # + #subprocess.call(["ls", "-l"]) # + #subprocess.check_output(["ls", "-l"]) # + #myrepopath = homepath/'Documents/SharpestMinds/covid_disinfo_detect' #myrawdatapath = myrepopath/'data'/'raw_dailies' #print(previous3) # + #day = '2020-05-18' #daypath = myrawdatapath / day # + #twarc_command = f'twarc hydrate {daypath}/{day}_clean-dataset.txt > {daypath}/{day}_clean-dataset.json' #print(twarc_command) # + #subprocess.call(twarc_command, shell=True) # - def twarc_gather(myrawdatapath, daily_list): #print(f'Hydrating data for the following days: {daily_list}') for day in daily_list: daypath = myrawdatapath / day twarc_command = f'twarc hydrate {daypath}/{day}_clean-dataset.txt > {daypath}/{day}_clean-dataset.json' # gzip_command = f'gzip -k {daypath}/{day}_clean-dataset.json' try: print(f'Hydrating data for {day}...') subprocess.call(twarc_command, shell=True) #print('Done gathering data via twarc, compressing JSON...') #subprocess.call(gzip_command, shell=True) #print('File compressed! Now uploading JSON file to Storage Bucket...') print('Uploading to bucket...') upload_blob( bucket_name='thepanacealab_covid19twitter', source_file_name=f'{daypath}/{day}_clean-dataset.json', destination_blob_name=f'dailies/{day}/{day}_clean-dataset.json' ) print(f'JSON file uploaded to Storage Bucket, now removing JSON from {day} folder...') filepath = daypath / f'{day}_clean-dataset.json' # remove JSON file filepath.unlink() print(f'JSON removed from {day} folder!') # clean data --> not for use locally # clean_data_wrapper(daypath, myprocdatapath, day) except Exception as e: print(e) # + #twarc_gather(myrawdatapath, previous3[::-1]) # + # #%%time #twarc_gather(myrawdatapath, previous3[::-1]) # + # #%%time #twarc_gather(myrawdatapath, previous3[::-1]) # + #homepath = setpath() #myrepopath = Path.cwd().parent.parent #print(homepath) #print(myrepopath) # - def main_gather(): # set up path to current working directory & path to directory containing Panacea data homepath = setpath() myrepopath = Path.cwd().parent.parent panacearepopath = homepath / 'thepanacealab_covid19' myrawdatapath = myrepopath / 'data' / 'raw_dailies' #myprocdatapath = myrepopath / 'data' / 'processed_dailies' --> don't belive I need at the moment # create list of daily folders located in Panacea repo (which contains data we need to access) file_ignore = ['README.md', '.ipynb_checkpoints'] daily_list = [x.name for x in sorted((panacearepopath / 'dailies').iterdir())\ if x.name not in file_ignore] # see what daily data we do not have in storage bucket nojson = storage_check(daily_list) #previous4 = nojson[-4:] print(f'\nTotal of {len(nojson)} folders do not contain a JSON file:\n{nojson}\n') print(f'Gathering data for the previous days without JSONs:\n{nojson[::-1]}') twarc_gather(myrawdatapath, nojson[::-1]) def main_program(): main_setup() main_gather() # %%time print(f'Started at: {datetime.now()}') main_program() print(f'Ended at: {datetime.now()}')
experiments/src_exp/data_experimentation/data_download_v3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd pd.options.plotting.backend = "plotly" #counties=pd.read_json('county_pop_dense_many.json') counties = pd.read_json('numpy_county_dense_14.json') # + pycharm={"name": "#%%\n"} for b in (str(x) for x in range(14, 15)): r = counties[[f'partition_{b}','total_pop']].groupby(f'partition_{b}').sum() print(f'{b} Mean: {r["total_pop"].mean()} Standard Deviation: {r["total_pop"].std()} ' f'Performance: {r["total_pop"].std()/r["total_pop"].mean()*100}') # + pycharm={"name": "#%%\n"} b = 14 r = counties[[f'partition_{b}','total_pop']].groupby(f'partition_{b}').sum() r.plot(kind='bar')
Compare Distributions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- Select a Model with Cross Validation # + from sklearn import datasets iris = datasets.load_iris() X = iris.data[:,2:] y = iris.target from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, stratify = y,random_state = 7) # + from sklearn.neighbors import KNeighborsClassifier kn_3 = KNeighborsClassifier(n_neighbors = 3) kn_5 = KNeighborsClassifier(n_neighbors = 5) # + from sklearn.model_selection import cross_val_score kn_3_scores = cross_val_score(kn_3, X_train, y_train, cv=4) kn_5_scores = cross_val_score(kn_5, X_train, y_train, cv=4) kn_3_scores # - kn_5_scores print "Mean of kn_3: ",kn_3_scores.mean() print "Mean of kn_5: ",kn_5_scores.mean() print "Std of kn_3: ",kn_3_scores.std() print "Std of kn_5: ",kn_5_scores.std()
Chapter07/Select a Model with Cross Validation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Deming Regression # ------------------------------- # # This function shows how to use TensorFlow to solve linear Deming regression. # # $y = Ax + b$ # # We will use the iris data, specifically: # # y = Sepal Length and x = Petal Width. # # Deming regression is also called total least squares, in which we minimize the shortest distance from the predicted line and the actual (x,y) points. # # If least squares linear regression minimizes the vertical distance to the line, Deming regression minimizes the total distance to the line. This type of regression minimizes the error in the y values and the x values. See the below figure for a comparison. # # <img src="../images/05_demming_vs_linear_reg.png" width="512"> # # To implement this in TensorFlow, we start by loading the necessary libraries. import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from sklearn import datasets from tensorflow.python.framework import ops ops.reset_default_graph() # Start a computational graph session: # + sess = tf.Session() # Set a random seed tf.set_random_seed(42) np.random.seed(42) # - # We load the iris data. # Load the data # iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)] iris = datasets.load_iris() x_vals = np.array([x[3] for x in iris.data]) # Petal Width y_vals = np.array([y[0] for y in iris.data]) # Sepal Length # Next we declare the batch size, model placeholders, model variables, and model operations. # + # Declare batch size batch_size = 125 # Initialize placeholders x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32) y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32) # Create variables for linear regression A = tf.Variable(tf.random_normal(shape=[1,1])) b = tf.Variable(tf.random_normal(shape=[1,1])) # Declare model operations model_output = tf.add(tf.matmul(x_data, A), b) # - # For the demming loss, we want to compute: # # $$ \frac{\left| A \cdot x + b - y \right|}{\sqrt{A^{2} + 1}} $$ # # Which will give us the shortest distance between a point (x,y) and the predicted line, $A \cdot x + b$. # Declare Deming loss function deming_numerator = tf.abs(tf.subtract(tf.add(tf.matmul(x_data, A), b), y_target)) deming_denominator = tf.sqrt(tf.add(tf.square(A),1)) loss = tf.reduce_mean(tf.truediv(deming_numerator, deming_denominator)) # Next we declare the optimization function and initialize all model variables. # + # Declare optimizer my_opt = tf.train.GradientDescentOptimizer(0.25) train_step = my_opt.minimize(loss) # Initialize variables init = tf.global_variables_initializer() sess.run(init) # - # Now we train our Deming regression for 250 iterations. # Training loop loss_vec = [] for i in range(1500): rand_index = np.random.choice(len(x_vals), size=batch_size) rand_x = np.transpose([x_vals[rand_index]]) rand_y = np.transpose([y_vals[rand_index]]) sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y}) temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y}) loss_vec.append(temp_loss) if (i+1)%100==0: print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b))) print('Loss = ' + str(temp_loss)) # Retrieve the optimal coefficients (slope and intercept). # + # Get the optimal coefficients [slope] = sess.run(A) [y_intercept] = sess.run(b) # Get best fit line best_fit = [] for i in x_vals: best_fit.append(slope*i+y_intercept) # - # Here is matplotlib code to plot the best fit Deming regression line and the Demming Loss. # + # Plot the result plt.plot(x_vals, y_vals, 'o', label='Data Points') plt.plot(x_vals, best_fit, 'r-', label='Best fit line', linewidth=3) plt.legend(loc='upper left') plt.title('Sepal Length vs Petal Width') plt.xlabel('Petal Width') plt.ylabel('Sepal Length') plt.show() # Plot loss over time plt.plot(loss_vec, 'k-') plt.title('Deming Loss per Generation') plt.xlabel('Iteration') plt.ylabel('Deming Loss') plt.show() # -
03_Linear_Regression/05_Implementing_Deming_Regression/05_deming_regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.3 64-bit (''datacan'': conda)' # name: python3 # --- import pyspark import pyspark.sql.functions as F from pyspark.sql import SparkSession import pandas as pd from functools import reduce # %run '../src/cancer_utilies.ipynb' # + # initialize sparksession spark = SparkSession.builder.appName('app').getOrCreate() # initialize list of lists data = [['Rand1', 'C34,C18,C19', '2021-01-01'], ['Rand1', 'C34,C18,C19', '2020-12-29'], ['Rand3', 'C50', '2021-07-10'], ['Rand3', 'C50,C21,C50', '2021-04-01'], ['Rand3', 'J12, C20', '2021-06-01'], ['Rand3', 'J12, C20', '2021-06-02'] ] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['dummy_name', 'dummy_condition','dummy_admis']) # - spark_df = spark.createDataFrame(df) cancer_chapter_instance = CreateCancerHighLevel_ML(spark_df) cancer_chapter_instance.show() diag_col = 'dummy_condition' C18_C21_df = cancer_chapter_instance .chapters_C18_C21_Colorectal(diag_col) C34_df = cancer_chapter_instance.chapters_C34_Lung(diag_col) def unionAll_custom(dfs, fill_by=0): clmns = {clm.name.lower(): (clm.dataType, clm.name) for df in dfs for clm in df.schema.fields} for i, df in enumerate (dfs): df_clmns = [clm. lower() for clm in df.columns] for clm, (dataType, name) in clmns.items(): if clm not in df_clmns: # Add the missing column dfs[i] = dfs[i].withColumn(name, F.lit(fill_by).cast(dataType)) return reduce(DataFrame.unionByName, dfs) cancer_union = unionAll_custom([C18_C21_df,C34_df]) cancer_union.show() (cancer_union.groupBy().sum()).show() cancer_union_fill = cancer_union.na.fill(0) cancer_union_fill.show() cancer_union_fill_dedup = cancer_union_fill.dropDuplicates() cancer_union_fill_dedup.show() cancer_union_fill_dedup.groupBy().sum().collect() agg_can_phenotypes = ['Lung','Colorectal'] # + agg_can_dfs = [] for cancer_type in agg_can_phenotypes: grouped_data_cancers = cancer_union_fill_dedup.groupBy(["dummy_admis", cancer_type]).agg({f'{cancer_type}':'sum'}) grouped_data_cancers = grouped_data_cancers.drop(cancer_type) grouped_data_cancers = grouped_data_cancers.withColumn('CANCER_CATEGORY', F.lit(f'{cancer_type}')) ordered_df = grouped_data_cancers.orderBy(['dummy_admis']) agg_can_dfs.append(ordered_df) # - dfs_colnames_dict = dict(zip(agg_can_dfs, agg_can_phenotypes)) # + new_dfs =[] for df, column_name in dfs_colnames_dict.items(): df = df.withColumnRenamed(f'sum({column_name})', 'count') new_dfs.append(df) # - reduced_dfs = reduce(DataFrame.union, new_dfs) (reduced_dfs.groupBy ('CANCER_CATEGORY').sum()).show() test = (reduced_dfs). toPandas() test.head() import pandas as pd test['dummy_admis'] = pd.to_datetime(test['dummy_admis'], format='%Y-%m') weekly_freq = test.groupby('CANCER_CATEGORY').resample('W',on='dummy_admis').sum() weekly_freq.reset_index(inplace = True) # weekly_freq.head() weekly_freq['moving'] = weekly_freq.groupby('CANCER_CATEGORY').rolling(7)['count'].mean().reset_index(drop = True) weekly_freq.head() #weekly_freq.set_index('dummy_admis', inplace=True) # + # %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns plt.rcParams["figure.figsize"] = (25,8) plt.style.use('seaborn-colorblind') sns.lineplot(x=weekly_freq.dummy_admis, y='moving', hue='CANCER_CATEGORY' ,data=weekly_freq) # -
tests/test_colorectal.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.9.12 ('river') # language: python # name: python3 # --- # # Bike-sharing forecasting # %load_ext autoreload # %autoreload 2 # In this tutorial we're going to forecast the number of bikes in 5 bike stations from the city of Toulouse. We'll do so by building a simple model step by step. The dataset contains 182,470 observations. Let's first take a peak at the data. # + tags=[] from pprint import pprint from river import datasets dataset = datasets.Bikes() for x, y in dataset: pprint(x) print(f'Number of available bikes: {y}') break # - # Let's start by using a simple linear regression on the numeric features. We can select the numeric features and discard the rest of the features using a `Select`. Linear regression is very likely to go haywire if we don't scale the data, so we'll use a `StandardScaler` to do just that. We'll evaluate the model by measuring the mean absolute error. Finally we'll print the score every 20,000 observations. # + tags=[] from river import compose from river import linear_model from river import metrics from river import evaluate from river import preprocessing from river import optim model = compose.Select('clouds', 'humidity', 'pressure', 'temperature', 'wind') model |= preprocessing.StandardScaler() model |= linear_model.LinearRegression(optimizer=optim.SGD(0.001)) metric = metrics.MAE() evaluate.progressive_val_score(dataset, model, metric, print_every=20_000) # - # The model doesn't seem to be doing that well, but then again we didn't provide a lot of features. Generally, a good idea for this kind of problem is to look at an average of the previous values. For example, for each station we can look at the average number of bikes per hour. To do so we first have to extract the hour from the `moment` field. We can then use a `TargetAgg` to aggregate the values of the target. # + tags=[] from river import feature_extraction from river import stats def get_hour(x): x['hour'] = x['moment'].hour return x model = compose.Select('clouds', 'humidity', 'pressure', 'temperature', 'wind') model += ( get_hour | feature_extraction.TargetAgg(by=['station', 'hour'], how=stats.Mean()) ) model |= preprocessing.StandardScaler() model |= linear_model.LinearRegression(optimizer=optim.SGD(0.001)) metric = metrics.MAE() evaluate.progressive_val_score(dataset, model, metric, print_every=20_000) # - # By adding a single feature, we've managed to significantly reduce the mean absolute error. At this point you might think that the model is getting slightly complex, and is difficult to understand and test. Pipelines have the advantage of being terse, but they aren't always to debug. Thankfully `river` has some ways to relieve the pain. # # The first thing we can do it to visualize the pipeline, to get an idea of how the data flows through it. # + tags=[] model # - # We can also use the `debug_one` method to see what happens to one particular instance. Let's train the model on the first 10,000 observations and then call `debug_one` on the next one. To do this, we will turn the `Bike` object into a Python generator with `iter()` function. The Pythonic way to read the first 10,000 elements of a generator is to use `itertools.islice`. # + tags=[] import itertools model = compose.Select('clouds', 'humidity', 'pressure', 'temperature', 'wind') model += ( get_hour | feature_extraction.TargetAgg(by=['station', 'hour'], how=stats.Mean()) ) model |= preprocessing.StandardScaler() model |= linear_model.LinearRegression() for x, y in itertools.islice(dataset, 10000): y_pred = model.predict_one(x) model.learn_one(x, y) x, y = next(iter(dataset)) print(model.debug_one(x)) # - # The `debug_one` method shows what happens to an input set of features, step by step. # # And now comes the catch. Up until now we've been using the `progressive_val_score` method from the `evaluate` module. What this does it that it sequentially predicts the output of an observation and updates the model immediately afterwards. This way of proceeding is often used for evaluating online learning models. But in some cases it is the wrong approach. # # When evaluating a machine learning model, the goal is to simulate production conditions in order to get a trust-worthy assessment of the performance of the model. In our case, we typically want to forecast the number of bikes available in a station, say, 30 minutes ahead. Then, once the 30 minutes have passed, the true number of available bikes will be available and we will be able to update the model using the features available 30 minutes ago. # # What we really want is to evaluate the model by forecasting 30 minutes ahead and only updating the model once the true values are available. This can be done using the `moment` and `delay` parameters in the `progressive_val_score` method. The idea is that each observation in the stream of the data is shown twice to the model: once for making a prediction, and once for updating the model when the true value is revealed. The `moment` parameter determines which variable should be used as a timestamp, while the `delay` parameter controls the duration to wait before revealing the true values to the model. # + tags=[] import datetime as dt evaluate.progressive_val_score( dataset=dataset, model=model.clone(), metric=metrics.MAE(), moment='moment', delay=dt.timedelta(minutes=30), print_every=20_000 ) # - # The performance is a bit worse, which is to be expected. Indeed, the task is more difficult: the model is only shown the ground truth 30 minutes after making a prediction. # # The takeaway of this notebook is that the `progressive_val_score` method can be used to simulate a production scenario, and is thus extremely valuable.
docs/examples/bike-sharing-forecasting.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # #!/usr/bin/env python3.6 # -*-coding:utf-8 -*- # %matplotlib inline import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns np.random.seed(sum(map(ord, "aesthetics"))) # - def sinplot(flip=1): x = np.linspace(0, 14, 100) for i in range(1, 7): plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip) sinplot() sns.set() sinplot() sns.set_style("whitegrid") data = np.random.normal(size=(20, 6)) + np.arange(6) / 2 sns.boxplot(data=data); sns.set_style("dark") sinplot() sns.set_style("white") sinplot() sns.set_style("ticks") sinplot() sinplot() sns.despine() f, ax = plt.subplots() sns.violinplot(data=data) sns.despine(offset=10, trim=True); sns.set_style("whitegrid") sns.boxplot(data=data, palette="deep") sns.despine(left=True) with sns.axes_style("darkgrid"): plt.subplot(211) sinplot() plt.subplot(212) sinplot(-1) sns.axes_style()
ipynb/seaborn/.ipynb_checkpoints/Controlling_figure_aesthetics-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import xarray as xr import matplotlib.pyplot as plt import os import sys import numpy as np import pandas as pd from scipy.signal import detrend # add the 'src' directory as one where we can import modules src_dir = os.path.join(os.environ.get('projdir'),'src') sys.path.append(src_dir) from features.pySSA.mySSA import mySSA from features.log_progress import log_progress # + # load tides and no tides hourly melting over two month file_path = os.path.join(os.environ.get('rawdir'),'waom10_v2.0_small','ocean_his_hourly.nc') tides = xr.open_dataset(file_path)#.sel(ocean_time=slice('2001-1-1','2001-2-28')) file_path = os.path.join(os.environ.get('rawdir'),'waom10_v2.0_small_noTides','ocean_his_hourly.nc') no_tides = xr.open_dataset(file_path).sel(ocean_time=tides.ocean_time) # load grid grid_path = os.path.join(os.environ.get('rawdir'),'gdata','waom10_v2.0_frc','waom10_small_grd.nc') grd = xr.open_dataset(grid_path) # + #subset region for testing purposes #FRIS_nt = no_tides.isel(xi_rho = slice(270,380),eta_rho = slice(380,486)) #FRIS_t = tides.isel(xi_rho = slice(270,380),eta_rho = slice(380,486)) #grd = tides.isel(xi_rho = slice(270,380),eta_rho = slice(380,486)) # - #check that times are the same and sample length print('start stop\n tides: ',tides.ocean_time.values[[0,-1]],'\n no_tides: ',no_tides.ocean_time.values[[0,-1]]) print('sample length in days: ',tides.ocean_time.size/24) # + #define function that give you the percent variance explained by frequencies below and above certain value def get_var(ts_cell,K): if np.var(ts_cell.values) == 0.0: var_slow,var_fast,var_slow_contr,var_fast_contr = 0,0,0,0 else: ts = ts_cell.copy() ts[:] = detrend(ts_cell.values,-1,'linear') ssa = mySSA(ts.to_dataframe()['m']) ssa.embed(embedding_dimension=K) ssa.decompose() slow_rho_idx = np.argmax(np.abs(ssa.U.sum(0))/(np.abs(ssa.U).sum(0))) fast_rho_idx = np.delete(range(K),slow_rho_idx) var_slow,var_slow_contr = ssa.s[slow_rho_idx],ssa.s_contributions.values[slow_rho_idx][0] var_fast,var_fast_contr = sum(np.delete(ssa.s,slow_rho_idx)),sum(np.delete(ssa.s_contributions.values.squeeze(),slow_rho_idx)) return var_slow,var_slow_contr,var_fast,var_fast_contr def get_var_map(ts_map,grd,K): var_map = np.tile(np.zeros_like(ts_map[0].values),(4,1,1)) for j in log_progress(ts_map.eta_rho.values,name='eta'): for i in ts_map.xi_rho.values: var_map[:,j,i] = get_var(ts_map[:,j,i],K) var = xr.Dataset({'total':(['eta_rho','xi_rho'],var_map[0]+var_map[2]), 'slow':(['eta_rho','xi_rho'],var_map[0]), 'slow_contr':(['eta_rho','xi_rho'],var_map[1]), 'fast':(['eta_rho','xi_rho'],var_map[2]), 'fast_contr':(['eta_rho','xi_rho'],var_map[3])}) for name,da in var.items(): da[:] = da.where(((grd.zice<0)&(grd.mask_rho==1))) return var # - #calculate maps of percent variance explained by less than 24h period effects and more than 24h period effects var_nt = get_var_map(no_tides.m,grd,24) var_t = get_var_map(tides.m,grd,24) #convert to meter ice per year w2i = 1025/917 s2a = 3600*24*365 for ds in [var_nt,var_t]: ds['total'] = ds.total*(s2a*w2i)**2 # %matplotlib notebook #plot variances of raw, low pass and high pass filtered signals def plot_var(var_nt,var_t): plt.close() fig,axes = plt.subplots(ncols=3,nrows=3,figsize=(15,10)) var_nt.total.plot(ax=axes[0,0],vmax=(var_nt.total.std()+var_nt.total.mean()).values) axes[0,0].text(0.5,-0.1, 'mean = %.3g m2/a2'%var_nt.total.mean().values, size=12, ha="center", transform=axes[0,0].transAxes) var_t.total.plot(ax=axes[0,1],vmax=(var_t.total.std()+var_t.total.mean()).values) axes[0,1].text(0.5,-0.1, 'mean = %.3g m2/a2'%var_t.total.mean().values, size=12, ha="center", transform=axes[0,1].transAxes) ((var_t.total-var_nt.total)).plot(ax=axes[0,2]) axes[0,2].text(0.5,-0.1, 'mean = %.3g m2/a2'%(var_t.total-var_nt.total).mean().values, size=12, ha="center", transform=axes[0,2].transAxes) var_nt.slow_contr.plot(ax=axes[1,0]) #axes[1,0].text(0.5,-0.1, 'mean = %.3g m2/a2'%var_nt.slow.mean().values, size=12, ha="center", transform=axes[1,0].transAxes) var_t.slow_contr.plot(ax=axes[1,1]) #axes[1,1].text(0.5,-0.1, 'mean = %.3g m2/a2'%var_t.slow.mean().values, size=12, ha="center", transform=axes[1,1].transAxes) ((var_t.slow_contr-var_nt.slow_contr)).plot(ax=axes[1,2]) #axes[1,2].text(0.5,-0.1, 'mean = %.3g m2/a2'%(var_t.slow.mean()-var_nt.slow.mean()).values, size=12, ha="center", transform=axes[1,2].transAxes) var_nt.fast_contr.plot(ax=axes[2,0]) #axes[2,0].text(0.5,-0.1, 'mean = %.3g m2/a2'%var_nt.fast.mean().values, size=12, ha="center", transform=axes[2,0].transAxes) var_t.fast_contr.plot(ax=axes[2,1]) #axes[2,1].text(0.5,-0.1, 'mean = %.3g m2/a2'%var_t.fast.mean().values, size=12, ha="center", transform=axes[2,1].transAxes) ((var_t.fast_contr-var_nt.fast_contr)).plot(axes=axes[2,2]) #axes[2,2].text(0.5,-0.1, 'mean = %.3g m2/a2'%(var_t.fast-var_nt.fast).mean().values, size=12, ha="center", transform=axes[2,2].transAxes) for ax in axes.flatten(): ax.set_aspect('equal') ax.axis('off') cols = ['Without tides','With tides','Difference'] rows = ['var [m2/a2]','% Var > 24h band','% Var < 24h band'] pad = 5 # in points for ax, col in zip(axes[0], cols): ax.annotate(col, xy=(0.5, 1), xytext=(0, pad), xycoords='axes fraction', textcoords='offset points', size='large', ha='center', va='baseline') for ax, row in zip(axes[:,0], rows): ax.annotate(row, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0), xycoords=ax.yaxis.label, textcoords='offset points', size='large', ha='right', va='center') fig.tight_layout() fig.subplots_adjust(left=0.15, top=0.95) plt.show() # %matplotlib notebook plt.close() plot_var(var_nt.isel(eta_rho=slice(270,390),xi_rho=slice(150,250)),var_t.isel(eta_rho=slice(270,390),xi_rho=slice(150,250))) plot_var(var_nt,var_t)
notebooks/reports/tidal_variance.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Manipulação de dados - II # + [markdown] slideshow={"slide_type": "slide"} # ## *DataFrames* # # Como dissemos anterioremente, o *DataFrame* é a segunda estrutura basilar do *pandas*. Um *DataFrame*: # - é uma tabela, ou seja, é bidimensional; # - tem cada coluna formada como uma *Series* do *pandas*; # - pode ter *Series* contendo tipos de dado diferentes. # - import numpy as np import pandas as pd # + [markdown] slideshow={"slide_type": "slide"} # ## Criação de um *DataFrame* # - # O método padrão para criarmos um *DataFrame* é através de uma função com mesmo nome. # # ```python # df_exemplo = pd.DataFrame(dados_de_interesse, index = indice_de_interesse, # columns = colunas_de_interesse) # ``` # + [markdown] slideshow={"slide_type": "-"} # Ao criar um *DataFrame*, podemos informar # - `index`: rótulos para as linhas (atributos *index* das *Series*). # - `columns`: rótulos para as colunas (atributos *name* das *Series*). # + [markdown] slideshow={"slide_type": "slide"} # No _template_, `dados_de_interesse` pode ser # # * um dicionário de: # * *arrays* unidimensionais do *numpy*; # * listas; # * dicionários; # * *Series* do *pandas*. # * um *array* bidimensional do *numpy*; # * uma *Series* do *Pandas*; # * outro *DataFrame*. # + [markdown] slideshow={"slide_type": "slide"} # ### *DataFrame* a partir de dicionários de *Series* # # Neste método de criação, as *Series* do dicionário não precisam possuir o mesmo número de elementos. O *index* do *DataFrame* será dado pela **união** dos *index* de todas as *Series* contidas no dicionário. # + [markdown] slideshow={"slide_type": "slide"} # Exemplo: # + slideshow={"slide_type": "-"} serie_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22}, name="Idade") # + slideshow={"slide_type": "-"} serie_Peso = pd.Series({'Ana':55, 'João': 80, 'Maria': 62, 'Pedro': 67, 'Túlio': 73}, name="Peso") # + slideshow={"slide_type": "-"} serie_Altura = pd.Series({'Ana':162, 'João': 178, 'Maria': 162, 'Pedro': 165, 'Túlio': 171}, name="Altura") # - dicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura} df_dict_series = pd.DataFrame(dicionario_series_exemplo) df_dict_series # Compare este resultado com a criação de uma planilha pelos métodos usuais. Veja que há muita flexibilidade para criarmos ou modificarmos uma tabela. # # Vejamos exemplos sobre como acessar intervalos de dados na tabela. # + slideshow={"slide_type": "-"} pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria']) # - pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria'], columns=['Peso','Altura']) # + [markdown] slideshow={"slide_type": "slide"} # Neste exemplo, adicionamos a coluna `IMC`, ainda sem valores calculados. # + slideshow={"slide_type": "-"} pd.DataFrame(dicionario_series_exemplo, index=['Ana','Maria','Paula'], columns=['Peso','Altura','IMC']) # + slideshow={"slide_type": "slide"} df_exemplo_IMC = pd.DataFrame(dicionario_series_exemplo, columns=['Peso','Altura','IMC']) # - # Agora, mostramos como os valores do IMC podem ser calculados diretamente por computação vetorizada sobre as *Series*. df_exemplo_IMC['IMC']=round(df_exemplo_IMC['Peso']/(df_exemplo_IMC['Altura']/100)**2,2) df_exemplo_IMC # + [markdown] slideshow={"slide_type": "slide"} # ### *DataFrame* a partir de dicionários de listas ou *arrays* do *numpy* # # Neste método de criação, os *arrays* ou as listas **devem** possuir o mesmo comprimento. Se o *index* não for informado, o *index* será dado de forma similar ao do objeto tipo *Series*. # + [markdown] slideshow={"slide_type": "slide"} # Exemplo com dicionário de listas: # - dicionario_lista_exemplo = {'Idade': [20,19,21,22,20], 'Peso': [55,80,62,67,73], 'Altura': [162,178,162,165,171]} pd.DataFrame(dicionario_lista_exemplo) # + [markdown] slideshow={"slide_type": "slide"} # Mais exemplos: # + slideshow={"slide_type": "-"} pd.DataFrame(dicionario_lista_exemplo, index=['Ana','João','Maria','Pedro','Túlio']) # + [markdown] slideshow={"slide_type": "slide"} # Exemplos com dicionário de *arrays* do *numpy*: # - dicionario_array_exemplo = {'Idade': np.array([20,19,21,22,20]), 'Peso': np.array([55,80,62,67,73]), 'Altura': np.array([162,178,162,165,171])} pd.DataFrame(dicionario_array_exemplo) # + [markdown] slideshow={"slide_type": "slide"} # Mais exemplos: # + slideshow={"slide_type": "-"} pd.DataFrame(dicionario_array_exemplo, index=['Ana','João','Maria','Pedro','Túlio']) # + [markdown] slideshow={"slide_type": "slide"} # ### *DataFrame* a partir de uma *Series* do *pandas* # # Neste caso, o *DataFrame* terá o mesmo *index* que a *Series* do *pandas* e apenas uma coluna. # - series_exemplo = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}) pd.DataFrame(series_exemplo) # + [markdown] slideshow={"slide_type": "slide"} # Caso a *Series* possua um atributo `name` especificado, este será o nome da coluna do *DataFrame*. # - series_exemplo_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}, name="Idade") pd.DataFrame(series_exemplo_Idade) # + [markdown] slideshow={"slide_type": "slide"} # ### *DataFrame* a partir de lista de *Series* do *pandas* # # Neste caso, a entrada dos dados da lista no *DataFrame* será feita por linha. # - pd.DataFrame([serie_Peso, serie_Altura, serie_Idade]) # + [markdown] slideshow={"slide_type": "slide"} # Podemos corrigir a orientação usando o método `transpose`. # - pd.DataFrame([serie_Peso, serie_Altura, serie_Idade]).transpose() # + [markdown] slideshow={"slide_type": "slide"} # ### *DataFrame* a partir de arquivos # # Para criar um *DataFrame* a partir de um arquivo, precisamos de funções do tipo `pd.read_FORMATO`, onde `FORMATO` indica o formato a ser importado sob o pressuposto de que a biblioteca *pandas* foi devidamente importada com `pd`. # + [markdown] slideshow={"slide_type": "slide"} # Os formatos mais comuns são: # # * *csv* (comma-separated values), # * *xls* ou *xlsx* (formatos do Microsoft Excel), # * *hdf5* (comumente utilizado em *big data*), # * *json* (comumente utilizado em páginas da internet). # + [markdown] slideshow={"slide_type": "slide"} # As funções para leitura correspondentes são: # * `pd.read_csv`, # * `pd.read_excel`, # * `pd.read_hdf`, # * `pd.read_json`, # # respectivamente. # + [markdown] slideshow={"slide_type": "slide"} # De todas elas, a função mais utilizada é `read_csv`. Ela possui vários argumentos. Vejamos os mais utilizados: # # * `file_path_or_buffer`: o endereço do arquivo a ser lido. Pode ser um endereço da internet. # * `sep`: o separador entre as entradas de dados. O separador padrão é `,`. # * `index_col`: a coluna que deve ser usada para formar o *index*. O padrão é `None`. Porém pode ser alterado para outro. Um separador comumente encontrado é o `\t` (TAB). # * `names`: nomes das colunas a serem usadas. O padrão é `None`. # * `header`: número da linha que servirá como nome para as colunas. O padrão é `infer` (ou seja, tenta deduzir automaticamente). Se os nomes das colunas forem passados através do `names`, então `header` será automaticamente considerado como `None`. # + [markdown] slideshow={"slide_type": "slide"} # **Exemplo:** considere o arquivo `data/exemplo_data.csv` contendo: # # ``` # ,coluna_1,coluna_2 # 2020-01-01,-0.4160923582996922,1.8103644347460834 # 2020-01-02,-0.1379696602473578,2.5785204825192785 # 2020-01-03,0.5758273450544708,0.06086648807755068 # 2020-01-04,-0.017367186564883633,1.2995865328684455 # 2020-01-05,1.3842792448510655,-0.3817320973859929 # 2020-01-06,0.5497056238566345,-1.308789022968975 # 2020-01-07,-0.2822962331437976,-1.6889791765925102 # 2020-01-08,-0.9897300598660013,-0.028120707936426497 # 2020-01-09,0.27558240737928663,-0.1776585993494299 # 2020-01-10,0.6851316082235455,0.5025348904591399 # ``` # # Para ler o arquivo acima basta fazer: # + slideshow={"slide_type": "slide"} df_exemplo_0 = pd.read_csv('../database/exemplo_data.csv') # + slideshow={"slide_type": "-"} df_exemplo_0 # + [markdown] slideshow={"slide_type": "slide"} # No exemplo anterior, as colunas receberam nomes corretamentes exceto pela primeira coluna que gostaríamos de considerar como *index*. Neste caso fazemos: # - df_exemplo = pd.read_csv('../database/exemplo_data.csv', index_col=0) df_exemplo # + [markdown] slideshow={"slide_type": "slide"} # #### O método *head* do *DataFrame* # # O método `head`, sem argumento, permite que visualizemos as 5 primeiras linhas do *DataFrame*. # - df_exemplo.head() # + [markdown] slideshow={"slide_type": "slide"} # Se for passado um argumento com valor `n`, as `n` primeiras linhas são impressas. # - df_exemplo.head(2) df_exemplo.head(7) # + [markdown] slideshow={"slide_type": "slide"} # #### O método `tail` do *DataFrame* # # O método `tail`, sem argumento, retorna as últimas 5 linhas do *DataFrame*. # - df_exemplo.tail() # + [markdown] slideshow={"slide_type": "slide"} # Se for passado um argumento com valor `n`, as `n` últimas linhas são impressas. # - df_exemplo.tail(2) df_exemplo.tail(7) # + [markdown] slideshow={"slide_type": "slide"} # ## Atributos de *Series* e *DataFrames* # # Atributos comumente usados para *Series* e *DataFrames* são: # # * `shape`: fornece as dimensões do objeto em questão (*Series* ou *DataFrame*) em formato consistente com o atributo `shape` de um *array* do *numpy*. # * `index`: fornece o índice do objeto. No caso do *DataFrame* são os rótulos das linhas. # * `columns`: fornece as colunas (apenas disponível para *DataFrames*) # + [markdown] slideshow={"slide_type": "slide"} # Exemplo: # - df_exemplo.shape serie_1 = pd.Series([1,2,3,4,5]) serie_1.shape df_exemplo.index serie_1.index df_exemplo.columns # + [markdown] slideshow={"slide_type": "slide"} # Se quisermos obter os dados contidos nos *index* ou nas *Series* podemos utilizar a propriedade `.array`. # - serie_1.index.array df_exemplo.columns.array # + [markdown] slideshow={"slide_type": "slide"} # Se o interesse for obter os dados como um `array` do *numpy*, devemos utilizar o método `.to_numpy()`. # # Exemplo: # - serie_1.index.to_numpy() df_exemplo.columns.to_numpy() # + [markdown] slideshow={"slide_type": "slide"} # O método `.to_numpy()` também está disponível em *DataFrames*: # - df_exemplo.to_numpy() # + [markdown] slideshow={"slide_type": "slide"} # A função do *numpy* `asarray()` é compatível com *index*, *columns* e *DataFrames* do *pandas*: # - np.asarray(df_exemplo.index) np.asarray(df_exemplo.columns) np.asarray(df_exemplo) # + [markdown] slideshow={"slide_type": "slide"} # ### Informações sobre as colunas de um *DataFrame* # # Para obtermos uma breve descrição sobre as colunas de um *DataFrame* utilizamos o método `info`. # # Exemplo: # - df_exemplo.info() # + [markdown] slideshow={"slide_type": "slide"} # ## Criando arquivos a partir de *DataFrames* # # Para criar arquivos a partir de *DataFrames*, basta utilizar os métodos do tipo `pd.to_FORMATO`, onde `FORMATO` indica o formato a ser exportado e supondo que a biblioteca *pandas* foi importada com `pd`. # + [markdown] slideshow={"slide_type": "slide"} # Com relação aos tipos de arquivo anteriores, os métodos para exportação correspondentes são: # * `.to_csv` ('endereço_do_arquivo'), # * `.to_excel` ('endereço_do_arquivo'), # * `.to_hdf` ('endereço_do_arquivo'), # * `.to_json`('endereço_do_arquivo'), # # onde `endereço_do_arquivo` é uma `str` que contém o endereço do arquivo a ser exportado. # + [markdown] slideshow={"slide_type": "slide"} # Exemplo: # # Para exportar para o arquivo `exemplo_novo.csv`, utilizaremos o método `.to_csv` ao *DataFrame* `df_exemplo`: # - df_exemplo.to_csv('../database/exemplo_novo.csv') # + [markdown] slideshow={"slide_type": "slide"} # ### Exemplo COVID-19 PB # + [markdown] slideshow={"slide_type": "-"} # Dados diários de COVID-19 do estado da Paraíba: # # *Fonte: https://superset.plataformatarget.com.br/superset/dashboard/microdados/* # + slideshow={"slide_type": "slide"} dados_covid_PB = pd.read_csv('https://superset.plataformatarget.com.br/superset/explore_json/?form_data=%7B%22slice_id%22%3A1550%7D&csv=true', sep=',', index_col=0) # + slideshow={"slide_type": "slide"} dados_covid_PB.info() # + slideshow={"slide_type": "slide"} dados_covid_PB.head() # + slideshow={"slide_type": "slide"} dados_covid_PB.tail() # + slideshow={"slide_type": "slide"} dados_covid_PB['estado'] = 'PB' # - dados_covid_PB.head() dados_covid_PB.to_csv('../database/dadoscovidpb.csv') # + [markdown] slideshow={"slide_type": "slide"} # ### Índices dos valores máximos ou mínimos # # Os métodos `idxmin()` e `idxmax()` retornam o *index* cuja entrada fornece o valor mínimo ou máximo da *Series* ou *DataFrame*. Se houver múltiplas ocorrências de mínimos ou máximos, o método retorna a primeira ocorrência. # # Vamos recriar um *DataFrame* genérico. # + slideshow={"slide_type": "-"} serie_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}, name="Idade") serie_Peso = pd.Series({'Ana':55, 'João': 80, 'Maria': 62, 'Pedro': 67, 'Túlio': 73}, name="Peso") serie_Altura = pd.Series({'Ana':162, 'João': 178, 'Maria': 162, 'Pedro': 165, 'Túlio': 171}, name="Altura") # - dicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura} df_dict_series = pd.DataFrame(dicionario_series_exemplo) # + slideshow={"slide_type": "slide"} df_dict_series # - # Assim, podemos localizar quem possui menores idade, peso e altura. # + slideshow={"slide_type": "-"} df_dict_series.idxmin() # - # De igual forma, localizamos quem possui maiores idade, peso e altura. df_dict_series.idxmax() # + [markdown] slideshow={"slide_type": "slide"} # **Exemplo:** Aplicaremos as funções `idxmin()` e `idxmax()` aos dados do arquivo `data/exemplo_data.csv` para localizar entradas de interesse. # - df_exemplo = pd.read_csv('../database/exemplo_data.csv', index_col=0); df_exemplo # + slideshow={"slide_type": "slide"} df_exemplo = pd.DataFrame(df_exemplo, columns=['coluna_1','coluna_2','coluna_3']) # - # Inserimos uma terceira coluna com dados fictícios. # + slideshow={"slide_type": "-"} df_exemplo['coluna_3'] = pd.Series([1,2,3,4,5,6,7,8,np.nan,np.nan],index=df_exemplo.index) df_exemplo # - # Os *index* correspondentes aos menores e maiores valores são datas, evidentemente. # + slideshow={"slide_type": "slide"} df_exemplo.idxmin() # - df_exemplo.idxmax() # + [markdown] slideshow={"slide_type": "slide"} # ### Reindexação de *DataFrames* # # No *pandas*, o método `reindex` # # * reordena o *DataFrame* de acordo com o conjunto de rótulos inserido como argumento; # * insere valores faltantes caso um rótulo do novo *index* não tenha valor atribuído no conjunto de dados; # * remove valores correspondentes a rótulos que não estão presentes no novo *index*. # + [markdown] slideshow={"slide_type": "slide"} # Exemplos: # - df_dict_series.reindex(index=['Victor', 'Túlio', 'Pedro', 'João'], columns=['Altura','Peso','IMC']) # + [markdown] slideshow={"slide_type": "slide"} # ## Remoção de linhas ou colunas de um *DataFrame* # # Para remover linhas ou colunas de um *DataFrame* do *pandas* podemos utilizar o método `drop`. O argumento `axis` identifica o eixo de remoção: `axis=0`, que é o padrão, indica a remoção de uma ou mais linhas; `axis=1` indica a remoção de uma ou mais colunas. # + [markdown] slideshow={"slide_type": "slide"} # Nos exemplos que segue, note que novos *DataFrames* são obtidos a partir de `df_dict_series` sem que este seja sobrescrito. # - df_dict_series.drop('Túlio') # axis=0 implícito df_dict_series.drop(['Ana','Maria'], axis=0) df_dict_series.drop(['Idade'], axis=1) # + [markdown] slideshow={"slide_type": "slide"} # ### Renomeando *index* e *columns* # # O método `rename` retorna uma cópia na qual o *index* (no caso de *Series* e *DataFrames*) e *columns* (no caso de *DataFrames*) foram renomeados. O método aceita como entrada um dicionário, uma *Series* do *pandas* ou uma função. # + [markdown] slideshow={"slide_type": "slide"} # Exemplo: # - serie_exemplo = pd.Series([1,2,3], index=['a','b','c']) serie_exemplo serie_exemplo.rename({'a':'abacaxi', 'b':'banana', 'c': 'cebola'}) # Exemplo: # + slideshow={"slide_type": "slide"} df_dict_series # - df_dict_series.rename(index = {'Ana':'a', 'João':'j', 'Maria':'m', 'Pedro':'p','Túlio':'t'}, columns = {'Idade':'I', 'Peso':'P','Altura':'A'}) # No próximo exemplo, usamos uma *Series* para renomear os rótulos. # + slideshow={"slide_type": "slide"} indice_novo = pd.Series({'Ana':'a', 'João':'j', 'Maria':'m', 'Pedro':'p','Túlio':'t'}) # - df_dict_series.rename(index = indice_novo) # Neste exemplo, usamos a função `str.upper` (altera a `str` para "todas maiúsculas") para renomear colunas. df_dict_series.rename(columns=str.upper) # + [markdown] slideshow={"slide_type": "slide"} # ## Ordenação de *Series* e *DataFrames* # # É possível ordenar ambos pelos rótulos do *index* (para tanto é necessário que eles sejam ordenáveis) ou por valores nas colunas. # # O método `sort_index` ordena a *Series* ou o *DataFrame* pelo *index*. O método `sort_values` ordena a *Series* ou o *DataFrame* pelos valores (escolhendo uma ou mais colunas no caso de *DataFrames*). No caso do *DataFrame*, o argumento `by` é necessário para indicar qual(is) coluna(s) será(ão) utilizada(s) como base para a ordenação. # + [markdown] slideshow={"slide_type": "slide"} # Exemplos: # - serie_desordenada = pd.Series({'Maria': 21, 'Pedro': 22, 'Túlio': 20, 'João': 19, 'Ana':20}); serie_desordenada serie_desordenada.sort_index() # ordenação alfabética # + [markdown] slideshow={"slide_type": "slide"} # Mais exemplos: # - df_desordenado = df_dict_series.reindex(index=['Pedro','Maria','Ana','Túlio','João']) # + slideshow={"slide_type": "-"} df_desordenado # - df_desordenado.sort_index() # + [markdown] slideshow={"slide_type": "slide"} # Mais exemplos: # + slideshow={"slide_type": "-"} serie_desordenada.sort_values() # - df_desordenado.sort_values(by=['Altura']) # ordena por 'Altura' # + [markdown] slideshow={"slide_type": "slide"} # No caso de "empate", podemos utilizar outra coluna para desempatar. # - df_desordenado.sort_values(by=['Altura','Peso']) # usa a coluna 'Peso' para desempatar # + [markdown] slideshow={"slide_type": "slide"} # Os métodos `sort_index` e `sort_values` admitem o argumento opcional `ascending`, que permite inverter a ordenação caso tenha valor `False`. # - df_desordenado.sort_index(ascending=False) df_desordenado.sort_values(by=['Idade'], ascending=False) # + [markdown] slideshow={"slide_type": "slide"} # ## Comparação de *Series* e *DataFrames* # # *Series* e *DataFrames* possuem os seguintes métodos de comparação lógica: # # - `eq` (igual); # - `ne` (diferente); # - `lt` (menor do que); # - `gt` (maior do que); # - `le` (menor ou igual a); # - `ge` (maior ou igual a) # # que permitem a utilização dos operadores binários `==`, `!=`, `<`, `>`, `<=` e `>=`, respectivamente. As comparações são realizadas em cada entrada da *Series* ou do *DataFrame*. # # **Observação**: Para que esses métodos sejam aplicados, todos os objetos presentes nas colunas do *DataFrame* devem ser de mesma natureza. Por exemplo, se um *DataFrame* possui algumas colunas numéricas e outras com *strings*, ao realizar uma comparação do tipo `> 1`, um erro ocorrerá, pois o *pandas* tentará comparar objetos do tipo `int` com objetos do tipo `str`, assim gerando uma incompatibilidade. # # Exemplos: # - serie_exemplo # + slideshow={"slide_type": "-"} serie_exemplo == 2 # - # De outra forma: serie_exemplo.eq(2) serie_exemplo > 1 # Ou, na forma funcional: serie_exemplo.gt(1) # + slideshow={"slide_type": "slide"} df_exemplo > 1 # + [markdown] slideshow={"slide_type": "slide"} # **Importante:** Ao comparar *np.nan*, o resultado tipicamente é falso: # - np.nan == np.nan np.nan > np.nan np.nan >= np.nan # + [markdown] slideshow={"slide_type": "slide"} # Só é verdadeiro para indicar que é diferente: # - np.nan != np.nan # + [markdown] slideshow={"slide_type": "slide"} # Neste sentido, podemos ter tabelas iguais sem que a comparação usual funcione: # + slideshow={"slide_type": "-"} # 'copy', como o nome sugere, gera uma cópia do DataFrame df_exemplo_2 = df_exemplo.copy() # - (df_exemplo == df_exemplo_2) # + [markdown] slideshow={"slide_type": "slide"} # O motivo de haver entradas como `False` ainda que `df_exemplo_2` seja uma cópia exata de `df_exemplo` é a presença do `np.nan`. Neste caso, devemos utilizar o método `equals` para realizar a comparação. # - df_exemplo.equals(df_exemplo_2) # + [markdown] slideshow={"slide_type": "slide"} # ## Os métodos `any`, `all` e a propriedade `empty` # # O método `any` é aplicado a entradas booleanas (verdadeiras ou falsas) e retorna *verdadeiro* se existir alguma entrada verdadeira, ou *falso*, se todas forem falsas. O método `all` é aplicado a entradas booleanas e retorna *verdadeiro* se todas as entradas forem verdadeiras, ou *falso*, se houver pelo menos uma entrada falsa. A propriedade `empty` retorna *verdadeiro* se a *Series* ou o *DataFrame* estiver vazio, ou *falso* caso contrário. # + [markdown] slideshow={"slide_type": "slide"} # Exemplos: # - serie_exemplo serie_exemplo_2 = serie_exemplo-2; serie_exemplo_2 (serie_exemplo_2 > 0).any() (serie_exemplo > 1).all() # Este exemplo reproduz um valor `False` único. (df_exemplo == df_exemplo_2).all().all() serie_exemplo.empty # + [markdown] slideshow={"slide_type": "slide"} # Mais exemplos: # - (df_exemplo == df_exemplo_2).any() df_exemplo.empty df_vazio = pd.DataFrame() # + slideshow={"slide_type": "-"} df_vazio.empty # + [markdown] slideshow={"slide_type": "slide"} # ## Seleção de colunas de um *DataFrame* # # Para selecionar colunas de um *DataFrame*, basta aplicar *colchetes* a uma lista contendo os nomes das colunas de interesse. # + [markdown] slideshow={"slide_type": "slide"} # No exemplo abaixo, temos um *DataFrame* contendo as colunas `'Idade'`, `'Peso'` e `'Altura'`. Selecionaremos `'Peso'` e `'Altura'`, apenas. # + slideshow={"slide_type": "-"} df_dict_series[['Peso','Altura']] # + [markdown] slideshow={"slide_type": "slide"} # Se quisermos selecionar apenas uma coluna, não há necessidade de inserir uma lista. Basta utilizar o nome da coluna: # - df_dict_series['Peso'] # + [markdown] slideshow={"slide_type": "slide"} # Para remover colunas, podemos utilizar o método `drop`. # - df_dict_series.drop(['Peso','Altura'], axis=1) # + [markdown] slideshow={"slide_type": "slide"} # ### Criação de novas colunas a partir de colunas existentes # # Um método eficiente para criar novas colunas a partir de colunas já existentes é `eval`. Neste método, podemos utilizar como argumento uma *string* contendo uma expressão matemática envolvendo nomes de colunas do *DataFrame*. # + [markdown] slideshow={"slide_type": "slide"} # Como exemplo, vamos ver como calcular o IMC no *DataFrame* anterior: # - df_dict_series.eval('Peso/(Altura/100)**2') # + [markdown] slideshow={"slide_type": "slide"} # Se quisermos obter um *DataFrame* contendo o IMC como uma nova coluna, podemos utilizar o método `assign` (sem modificar o *DataFrame* original): # + slideshow={"slide_type": "-"} df_dict_series.assign(IMC=round(df_dict_series.eval('Peso/(Altura/100)**2'),2)) # - df_dict_series # não modificado # + [markdown] slideshow={"slide_type": "slide"} # Se quisermos modificar o *DataFrame* para incluir a coluna IMC fazemos: # - df_dict_series['IMC']=round(df_dict_series.eval('Peso/(Altura/100)**2'),2) df_dict_series # modificado "in-place" # + [markdown] slideshow={"slide_type": "slide"} # ## Seleção de linhas de um *DataFrame* # # Podemos selecionar linhas de um *DataFrame* de diversas formas diferentes. Veremos agora algumas dessas formas. # # Diferentemente da forma de selecionar colunas, para selecionar diretamente linhas de um *DataFrame* devemos utilizar o método `loc` (fornecendo o *index*, isto é, o rótulo da linha) ou o `iloc` (fornecendo a posição da linha): # - # Trabalharemos a seguir com um banco de dados atualizado sobre a COVID-19. Para tanto, importaremos o módulo `datetime` que nos auxiliará com datas. import datetime # + slideshow={"slide_type": "slide"} dados_covid_PB = pd.read_csv('https://superset.plataformatarget.com.br/superset/explore_json/?form_data=%7B%22slice_id%22%3A1550%7D&csv=true', sep=',', index_col=0) # busca o banco na data D-1, visto que a atualização # ocorre em D ontem = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d') # - dados_covid_PB.head(1) # + [markdown] slideshow={"slide_type": "slide"} # Podemos ver as informações de um único dia como argumento. Para tanto, excluímos a coluna `'Letalidade'` (valor não inteiro) e convertemos o restante para valores inteiros: # + slideshow={"slide_type": "-"} dados_covid_PB.loc[ontem].drop('Letalidade').astype('int') # + [markdown] slideshow={"slide_type": "slide"} # Podemos selecionar um intervalo de datas como argumento (excluindo letalidade): # - dados_covid_PB.index = pd.to_datetime(dados_covid_PB.index) # Convertendo o index de string para data dados_covid_PB.loc[pd.date_range('2021-02-01',periods=5,freq="D")].drop('Letalidade',axis=1) #função pd.date_range é muito útil para criar índices a partir de datas. # + [markdown] slideshow={"slide_type": "slide"} # Podemos colocar uma lista como argumento: # - dados_covid_PB.loc[pd.to_datetime(['2021-01-01','2021-02-01'])] # + [markdown] slideshow={"slide_type": "slide"} # Vamos agora examinar os dados da posição 100 (novamente excluindo a coluna letalidade e convertendo para inteiro): # - dados_covid_PB.iloc[100].drop('Letalidade').astype('int') # + [markdown] slideshow={"slide_type": "slide"} # Podemos colocar um intervalo como argumento: # - dados_covid_PB.iloc[50:55].drop('Letalidade', axis=1).astype('int') # + [markdown] slideshow={"slide_type": "slide"} # ### Seleção de colunas com `loc` e `iloc` # # Podemos selecionar colunas utilizando os métodos `loc` e `iloc` utilizando um argumento adicional. # + slideshow={"slide_type": "slide"} dados_covid_PB.loc[:,['casosNovos','obitosNovos']] # + slideshow={"slide_type": "slide"} dados_covid_PB.iloc[:,4:6] # fatiamento na coluna # + [markdown] slideshow={"slide_type": "slide"} # ### Seleção de linhas e colunas específicas com `loc` e `iloc` # - # Usando o mesmo princípio de *fatiamento* aplicado a *arrays* do numpy, podemos selecionar linhas e colunas em um intervalo específico de forma a obter uma subtabela. # + slideshow={"slide_type": "-"} dados_covid_PB.iloc[95:100,4:6] # - # Neste exemplo um pouco mais complexo, buscamos casos novos e óbitos novos em um período específico e ordenamos a tabela da data mais recente para a mais antiga. # + slideshow={"slide_type": "slide"} dados_covid_PB.loc[pd.date_range('2020-04-06','2020-04-10'),['casosNovos','obitosNovos']].sort_index(ascending=False) # + [markdown] slideshow={"slide_type": "slide"} # Suponha que o peso de Ana foi medido corretamente, mas registrado de maneira errônea no *DataFrame* `df_dict_series` como 55. # - df_dict_series # Supondo que, na realidade, o valor é 65, alteramos a entrada específica com um simples `loc`. Em seguida, atualizamos a tabela. # + slideshow={"slide_type": "-"} df_dict_series.loc['Ana','Peso'] = 65 df_dict_series = df_dict_series.assign(IMC=round(df_dict_series.eval('Peso/(Altura/100)**2'),2)) # O IMC mudou # - df_dict_series # + [markdown] slideshow={"slide_type": "slide"} # ### Seleção de linhas através de critérios lógicos ou funções # # Vamos selecionar quais os dias em que houve mais de 40 mortes registradas: # - dados_covid_PB.loc[dados_covid_PB['obitosNovos']>40] # + [markdown] slideshow={"slide_type": "slide"} # Selecionando os dias com mais de 25 óbitos e mais de 1500 casos novos: # - dados_covid_PB.loc[(dados_covid_PB.obitosNovos > 25) & (dados_covid_PB.casosNovos>1500)] # **Obs**.: Note que podemos utilizar o nome da coluna como um atributo. # + [markdown] slideshow={"slide_type": "slide"} # Vamos inserir uma coluna sobrenome no `df_dict_series`: # - df_dict_series['Sobrenome'] = ['Silva', 'PraDo', 'Sales', 'MachadO', 'Coutinho'] df_dict_series # + [markdown] slideshow={"slide_type": "slide"} # Vamos encontrar as linhas cujo sobrenome termina em "do". Para tanto, note que a função abaixo retorna `True` se o final é "do" e `False` caso contrário. # # ```python # def verifica_final_do(palavra): # return palavra.lower()[-2:] == 'do' # ``` # **Obs**.: Note que convertemos tudo para minúsculo. # + [markdown] slideshow={"slide_type": "slide"} # Agora vamos utilizar essa função para alcançar nosso objetivo: # - # 'map' aplica a função lambda a cada elemento da *Series* df_dict_series['Sobrenome'].map(lambda palavra: palavra.lower()[-2:]=='do') # procurando no df inteiro df_dict_series.loc[df_dict_series['Sobrenome'].map(lambda palavra: palavra.lower()[-2:]=='do')] # + [markdown] slideshow={"slide_type": "slide"} # Vamos selecionar as linhas do mês 2 (fevereiro) usando `index.month`: # + slideshow={"slide_type": "-"} dados_covid_PB.loc[dados_covid_PB.index.month==2].head() # + [markdown] slideshow={"slide_type": "slide"} # ### Seleção de linhas com o método *query* # # Similarmente ao método `eval`, ao utilizarmos `query`, podemos criar expressões lógicas a partir de nomes das colunas do *DataFrame*. # + [markdown] slideshow={"slide_type": "slide"} # Assim, podemos reescrever o código # # ```python # dados_covid_PB.loc[(dados_covid_PB.obitosNovos>25) & # (dados_covid_PB.casosNovos>1500)] # ``` # como # - dados_covid_PB.query('obitosNovos>25 and casosNovos>1500') # note que 'and' é usado em vez de '&'
_build/jupyter_execute/ipynb/10b-pandas-dataframe.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python (tbd) # language: python # name: tbd # --- # + buffer_size = 11 in_question = False with open('CLEVR_train_questions.json') as f: with open('clean_questions.txt', "w") as w: buffer = f.read(buffer_size) while True: next_character = f.read(1) if not next_character: print("End of file") break if in_question: w.write(next_character) buffer = buffer[1:] buffer += next_character if buffer == '"question":': in_question = True if in_question == True and next_character == '}': in_question = False w.write('\n') # - with open('clean_questions.txt', "r+") as g: with open('small_no_brackets.txt','w') as v: i = 0 while i < 600: line = g.readline() v.write(line[2:-3]) v.write('\n') i += 1 with open('not_brackets.txt', 'r') as p: print(p.readline())
data_cleaning_scripts/Clean_Questions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="eSA4DnL3itZG" # Lambda School Data Science, Unit 2: Predictive Modeling # # # Regression & Classification, Module 4 # # # #### Objectives # - begin with baselines for **classification** # - use classification metric: **accuracy** # - do **train/validate/test** split # - use scikit-learn for **logistic regression** # + [markdown] colab_type="text" id="mBrdnrAiSlAh" # ### Setup # + [markdown] colab_type="text" id="eYW8zY1Zn_h-" # #### Get started on Kaggle # 1. [Sign up for a Kaggle account](https://www.kaggle.com/), if you don’t already have one. # 2. Go to our Kaggle InClass competition website. You will be given the URL in Slack. # 3. Go to the Rules page. Accept the rules of the competition. # + [markdown] colab_type="text" id="vuoAHQDuSp1A" # #### If you're using [Anaconda](https://www.anaconda.com/distribution/) locally # # Install required Python packages, if you haven't already: # # - [category_encoders](http://contrib.scikit-learn.org/categorical-encoding/), version >= 2.0 # - [pandas-profiling](https://github.com/pandas-profiling/pandas-profiling), version >= 2.0 # # ``` # conda install -c conda-forge category_encoders plotly # ``` # + colab={} colab_type="code" id="wqHsEt-vTArf" # If you're in Colab... import os, sys in_colab = 'google.colab' in sys.modules if in_colab: # Install required python packages: # category_encoders, version >= 2.0 # pandas-profiling, version >= 2.0 # plotly, version >= 4.0 # !pip install --upgrade category_encoders pandas-profiling plotly # Pull files from Github repo os.chdir('/content') # !git init . # !git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Regression-Classification.git # !git pull origin master # Change into directory for module os.chdir('module4') # + colab={} colab_type="code" id="CDs_QjVJpaSP" # Ignore this Numpy warning when using Plotly Express: # FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead. import warnings warnings.filterwarnings(action='ignore', category=FutureWarning, module='numpy') # + [markdown] colab_type="text" id="Ph7_ka3DrjzA" # ## Read data # # The files are in the GitHub repository, in the `data/tanzania` folder: # # - `train_features.csv` : the training set features # - `train_labels.csv` : the training set labels # - `test_features.csv` : the test set features # - `sample_submission.csv` : a sample submission file in the correct format # + [markdown] colab_type="text" id="3_1DyzxZje5X" # #### Alternative option to get data & make submissions: Kaggle API # # 1. Go to our Kaggle InClass competition webpage. Accept the rules of the competiton. # # 2. [Follow these instructions](https://github.com/Kaggle/kaggle-api#api-credentials) to create a Kaggle “API Token” and download your `kaggle.json` file. # # 3. Put `kaggle.json` in the correct location. # # - If you're using Anaconda, put the file in the directory specified in the [instructions](https://github.com/Kaggle/kaggle-api#api-credentials). # # - If you're using Google Colab, upload the file to your Google Drive, and run this cell: # # ``` # from google.colab import drive # drive.mount('/content/drive') # # %env KAGGLE_CONFIG_DIR=/content/drive/My Drive/ # ``` # # 4. [Install the Kaggle API package](https://github.com/Kaggle/kaggle-api#installation). # # 5. [Use Kaggle API to download competition files](https://github.com/Kaggle/kaggle-api#download-competition-files). # # 6. [Use Kaggle API to submit to competition](https://github.com/Kaggle/kaggle-api#submit-to-a-competition). # + colab={} colab_type="code" id="nhiIa4x_pEPD" import pandas as pd train_features = pd.read_csv('../data/tanzania/train_features.csv') train_labels = pd.read_csv('../data/tanzania/train_labels.csv') test_features = pd.read_csv('../data/tanzania/test_features.csv') sample_submission = pd.read_csv('../data/tanzania/sample_submission.csv') assert train_features.shape == (59400, 40) assert train_labels.shape == (59400, 2) assert test_features.shape == (14358, 40) assert sample_submission.shape == (14358, 2) # + colab={} colab_type="code" id="_jUjpFduLlVt" # + [markdown] colab_type="text" id="ScT5oOhCraOO" # ### Features # # Your goal is to predict the operating condition of a waterpoint for each record in the dataset. You are provided the following set of information about the waterpoints: # # - `amount_tsh` : Total static head (amount water available to waterpoint) # - `date_recorded` : The date the row was entered # - `funder` : Who funded the well # - `gps_height` : Altitude of the well # - `installer` : Organization that installed the well # - `longitude` : GPS coordinate # - `latitude` : GPS coordinate # - `wpt_name` : Name of the waterpoint if there is one # - `num_private` : # - `basin` : Geographic water basin # - `subvillage` : Geographic location # - `region` : Geographic location # - `region_code` : Geographic location (coded) # - `district_code` : Geographic location (coded) # - `lga` : Geographic location # - `ward` : Geographic location # - `population` : Population around the well # - `public_meeting` : True/False # - `recorded_by` : Group entering this row of data # - `scheme_management` : Who operates the waterpoint # - `scheme_name` : Who operates the waterpoint # - `permit` : If the waterpoint is permitted # - `construction_year` : Year the waterpoint was constructed # - `extraction_type` : The kind of extraction the waterpoint uses # - `extraction_type_group` : The kind of extraction the waterpoint uses # - `extraction_type_class` : The kind of extraction the waterpoint uses # - `management` : How the waterpoint is managed # - `management_group` : How the waterpoint is managed # - `payment` : What the water costs # - `payment_type` : What the water costs # - `water_quality` : The quality of the water # - `quality_group` : The quality of the water # - `quantity` : The quantity of water # - `quantity_group` : The quantity of water # - `source` : The source of the water # - `source_type` : The source of the water # - `source_class` : The source of the water # - `waterpoint_type` : The kind of waterpoint # - `waterpoint_type_group` : The kind of waterpoint # # ### Labels # # There are three possible values: # # - `functional` : the waterpoint is operational and there are no repairs needed # - `functional needs repair` : the waterpoint is operational, but needs repairs # - `non functional` : the waterpoint is not operational # + [markdown] colab_type="text" id="LIWeFmyWswtB" # ## Why doesn't Kaggle give you labels for the test set? # # #### <NAME>, [How (and why) to create a good validation set](https://www.fast.ai/2017/11/13/validation-sets/) # # > One great thing about Kaggle competitions is that they force you to think about validation sets more rigorously (in order to do well). For those who are new to Kaggle, it is a platform that hosts machine learning competitions. Kaggle typically breaks the data into two sets you can download: # # > 1. a **training set**, which includes the _independent variables_, as well as the _dependent variable_ (what you are trying to predict). # # > 2. a **test set**, which just has the _independent variables_. You will make predictions for the test set, which you can submit to Kaggle and get back a score of how well you did. # # > This is the basic idea needed to get started with machine learning, but to do well, there is a bit more complexity to understand. You will want to create your own training and validation sets (by splitting the Kaggle “training” data). You will just use your smaller training set (a subset of Kaggle’s training data) for building your model, and you can evaluate it on your validation set (also a subset of Kaggle’s training data) before you submit to Kaggle. # # > The most important reason for this is that Kaggle has split the test data into two sets: for the public and private leaderboards. The score you see on the public leaderboard is just for a subset of your predictions (and you don’t know which subset!). How your predictions fare on the private leaderboard won’t be revealed until the end of the competition. The reason this is important is that you could end up overfitting to the public leaderboard and you wouldn’t realize it until the very end when you did poorly on the private leaderboard. Using a good validation set can prevent this. You can check if your validation set is any good by seeing if your model has similar scores on it to compared with on the Kaggle test set. ... # # > Understanding these distinctions is not just useful for Kaggle. In any predictive machine learning project, you want your model to be able to perform well on new data. # + [markdown] colab_type="text" id="simUkHjSs2t_" # ## Why care about model validation? # # #### <NAME>, [How (and why) to create a good validation set](https://www.fast.ai/2017/11/13/validation-sets/) # # > An all-too-common scenario: a seemingly impressive machine learning model is a complete failure when implemented in production. The fallout includes leaders who are now skeptical of machine learning and reluctant to try it again. How can this happen? # # > One of the most likely culprits for this disconnect between results in development vs results in production is a poorly chosen validation set (or even worse, no validation set at all). # # #### <NAME>, [Winning Data Science Competitions](https://www.slideshare.net/OwenZhang2/tips-for-data-science-competitions/8) # # > Good validation is _more important_ than good models. # # #### James, Witten, <NAME>, [An Introduction to Statistical Learning](http://www-bcf.usc.edu/~gareth/ISL/), Chapter 2.2, Assessing Model Accuracy # # > In general, we do not really care how well the method works training on the training data. Rather, _we are interested in the accuracy of the predictions that we obtain when we apply our method to previously unseen test data._ Why is this what we care about? # # > Suppose that we are interested test data in developing an algorithm to predict a stock’s price based on previous stock returns. We can train the method using stock returns from the past 6 months. But we don’t really care how well our method predicts last week’s stock price. We instead care about how well it will predict tomorrow’s price or next month’s price. # # > On a similar note, suppose that we have clinical measurements (e.g. weight, blood pressure, height, age, family history of disease) for a number of patients, as well as information about whether each patient has diabetes. We can use these patients to train a statistical learning method to predict risk of diabetes based on clinical measurements. In practice, we want this method to accurately predict diabetes risk for _future patients_ based on their clinical measurements. We are not very interested in whether or not the method accurately predicts diabetes risk for patients used to train the model, since we already know which of those patients have diabetes. # + [markdown] colab_type="text" id="LVZMzBqwvTdD" # ## Why hold out an independent test set? # # #### <NAME>, [Winning Data Science Competitions](https://www.slideshare.net/OwenZhang2/tips-for-data-science-competitions) # # > There are many ways to overfit. Beware of "multiple comparison fallacy." There is a cost in "peeking at the answer." # # > Good validation is _more important_ than good models. Simple training/validation split is _not_ enough. When you looked at your validation result for the Nth time, you are training models on it. # # > If possible, have "holdout" dataset that you do not touch at all during model build process. This includes feature extraction, etc. # # > What if holdout result is bad? Be brave and scrap the project. # # #### Hastie, Tibshirani, and Friedman, [The Elements of Statistical Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/), Chapter 7: Model Assessment and Selection # # > If we are in a data-rich situation, the best approach is to randomly divide the dataset into three parts: a training set, a validation set, and a test set. The training set is used to fit the models; the validation set is used to estimate prediction error for model selection; the test set is used for assessment of the generalization error of the final chosen model. Ideally, the test set should be kept in a "vault," and be brought out only at the end of the data analysis. Suppose instead that we use the test-set repeatedly, choosing the model with the smallest test-set error. Then the test set error of the final chosen model will underestimate the true test error, sometimes substantially. # # #### <NAME> and <NAME>, [Introduction to Machine Learning with Python](https://books.google.com/books?id=1-4lDQAAQBAJ&pg=PA270) # # > The distinction between the training set, validation set, and test set is fundamentally important to applying machine learning methods in practice. Any choices made based on the test set accuracy "leak" information from the test set into the model. Therefore, it is important to keep a separate test set, which is only used for the final evaluation. It is good practice to do all exploratory analysis and model selection using the combination of a training and a validation set, and reserve the test set for a final evaluation - this is even true for exploratory visualization. Strictly speaking, evaluating more than one model on the test set and choosing the better of the two will result in an overly optimistic estimate of how accurate the model is. # # #### <NAME>, [R for Data Science](https://r4ds.had.co.nz/model-intro.html#hypothesis-generation-vs.hypothesis-confirmation) # # > There is a pair of ideas that you must understand in order to do inference correctly: # # > 1. Each observation can either be used for exploration or confirmation, not both. # # > 2. You can use an observation as many times as you like for exploration, but you can only use it once for confirmation. As soon as you use an observation twice, you’ve switched from confirmation to exploration. # # > This is necessary because to confirm a hypothesis you must use data independent of the data that you used to generate the hypothesis. Otherwise you will be over optimistic. There is absolutely nothing wrong with exploration, but you should never sell an exploratory analysis as a confirmatory analysis because it is fundamentally misleading. # # > If you are serious about doing an confirmatory analysis, one approach is to split your data into three pieces before you begin the analysis. # + [markdown] colab_type="text" id="n-nP5AUBtAsk" # ### Why begin with baselines? # # [My mentor](https://www.linkedin.com/in/jason-sanchez-62093847/) [taught me](https://youtu.be/0GrciaGYzV0?t=40s): # # >***Your first goal should always, always, always be getting a generalized prediction as fast as possible.*** You shouldn't spend a lot of time trying to tune your model, trying to add features, trying to engineer features, until you've actually gotten one prediction, at least. # # > The reason why that's a really good thing is because then ***you'll set a benchmark*** for yourself, and you'll be able to directly see how much effort you put in translates to a better prediction. # # > What you'll find by working on many models: some effort you put in, actually has very little effect on how well your final model does at predicting new observations. Whereas some very easy changes actually have a lot of effect. And so you get better at allocating your time more effectively. # # My mentor's advice is echoed and elaborated in several sources: # # [Always start with a stupid model, no exceptions](https://blog.insightdatascience.com/always-start-with-a-stupid-model-no-exceptions-3a22314b9aaa) # # > Why start with a baseline? A baseline will take you less than 1/10th of the time, and could provide up to 90% of the results. A baseline puts a more complex model into context. Baselines are easy to deploy. # # [Measure Once, Cut Twice: Moving Towards Iteration in Data Science](https://blog.datarobot.com/measure-once-cut-twice-moving-towards-iteration-in-data-science) # # > The iterative approach in data science starts with emphasizing the importance of getting to a first model quickly, rather than starting with the variables and features. Once the first model is built, the work then steadily focuses on continual improvement. # # [*Data Science for Business*](https://books.google.com/books?id=4ZctAAAAQBAJ&pg=PT276), Chapter 7.3: Evaluation, Baseline Performance, and Implications for Investments in Data # # > *Consider carefully what would be a reasonable baseline against which to compare model performance.* This is important for the data science team in order to understand whether they indeed are improving performance, and is equally important for demonstrating to stakeholders that mining the data has added value. # # ### What does baseline mean? # # Baseline is an overloaded term, as you can see in the links above. Baseline has multiple meanings: # # #### The score you'd get by guessing # # > A baseline for classification can be the most common class in the training dataset. # # > A baseline for regression can be the mean of the training labels. # # > A baseline for time-series regressions can be the value from the previous timestep. —[<NAME>](https://twitter.com/koehrsen_will/status/1088863527778111488) # # #### Fast, first models that beat guessing # # What my mentor was talking about. # # #### Complete, tuned "simpler" model # # Can be simpler mathematically and computationally. For example, Logistic Regression versus Deep Learning. # # Or can be simpler for the data scientist, with less work. For example, a model with less feature engineering versus a model with more feature engineering. # # #### Minimum performance that "matters" # # To go to production and get business value. # # #### Human-level performance # # Your goal may to be match, or nearly match, human performance, but with better speed, cost, or consistency. # # Or your goal may to be exceed human performance. # + [markdown] colab_type="text" id="tG74jmbKrsj-" # ## Begin with baselines for classification # + [markdown] colab_type="text" id="QKCDx07WxXZj" # ### Get majority class baseline # # [<NAME>](https://twitter.com/koehrsen_will/status/1088863527778111488) # # > A baseline for classification can be the most common class in the training dataset. # # [*Data Science for Business*](https://books.google.com/books?id=4ZctAAAAQBAJ&pg=PT276), Chapter 7.3: Evaluation, Baseline Performance, and Implications for Investments in Data # # > For classification tasks, one good baseline is the _majority classifier_, a naive classifier that always chooses the majority class of the training dataset (see Note: Base rate in Holdout Data and Fitting Graphs). This may seem like advice so obvious it can be passed over quickly, but it is worth spending an extra moment here. There are many cases where smart, analytical people have been tripped up in skipping over this basic comparison. For example, an analyst may see a classification accuracy of 94% from her classifier and conclude that it is doing fairly well—when in fact only 6% of the instances are positive. So, the simple majority prediction classifier also would have an accuracy of 94%. # + [markdown] colab_type="text" id="nRnL7Bw12YZo" # #### Determine majority class # + colab={} colab_type="code" id="6D6UZ1XJxTpj" y_train = train_labels['status_group'] y_train.value_counts(normalize=True) # + [markdown] colab_type="text" id="Hl8qcAgp2bKC" # #### What if we guessed the majority class for every prediction? # + colab={} colab_type="code" id="sNhv3xPc2GHl" majority_class = y_train.mode()[0] y_pred = [majority_class] * len(y_train) len(y_pred) # - # # + [markdown] colab_type="text" id="2WWkumm3rwdb" # ## Use classification metric: accuracy # # #### [_Classification metrics are different from regression metrics!_](https://scikit-learn.org/stable/modules/model_evaluation.html) # - Don't use _regression_ metrics to evaluate _classification_ tasks. # - Don't use _classification_ metrics to evaluate _regression_ tasks. # # [Accuracy](https://scikit-learn.org/stable/modules/model_evaluation.html#accuracy-score) is a common metric for classification. Accuracy is the ["proportion of correct classifications"](https://en.wikipedia.org/wiki/Confusion_matrix): the number of correct predictions divided by the total number of predictions. # + [markdown] colab_type="text" id="p7TYYqJT28f1" # #### What is the baseline accuracy if we guessed the majority class for every prediction? # + colab={} colab_type="code" id="IhhM1vAd2s0b" from sklearn.metrics import accuracy_score accuracy_score(y_train, y_pred) # + [markdown] colab_type="text" id="Y2OLlsMar1c3" # ## Do train/validate/test split # + [markdown] colab_type="text" id="Pq01q_kp3QKd" # #### <NAME>, [How (and why) to create a good validation set](https://www.fast.ai/2017/11/13/validation-sets/) # # > You will want to create your own training and validation sets (by splitting the Kaggle “training” data). You will just use your smaller training set (a subset of Kaggle’s training data) for building your model, and you can evaluate it on your validation set (also a subset of Kaggle’s training data) before you submit to Kaggle. # # #### <NAME>, [Model Evaluation](https://sebastianraschka.com/blog/2018/model-evaluation-selection-part4.html) # # > Since “a picture is worth a thousand words,” I want to conclude with a figure (shown below) that summarizes my personal recommendations ... # # <img src="https://sebastianraschka.com/images/blog/2018/model-evaluation-selection-part4/model-eval-conclusions.jpg" width="600"> # # + [markdown] colab_type="text" id="M1tGjw9_4u0r" # # Usually, we want to do **"Model selection (hyperparameter optimization) _and_ performance estimation."** # # Therefore, we use **"3-way holdout method (train/validation/test split)"** or we use **"cross-validation with independent test set."** # + [markdown] colab_type="text" id="1JkSL6K14ry6" # #### We have two options for where we choose to split: # - Time # - Random # # To split on time, we can use pandas. # # To split randomly, we can use the [**`sklearn.model_selection.train_test_split`**](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function. # + colab={} colab_type="code" id="86bG7yPe5aXI" from sklearn.model_selection import train_test_split X_train = train_features y_train = train_labels['status_group'] X_train.shape, y_train.shape # + X_train, X_val, y_train, y_val = train_test_split( X_train, y_train, train_size = 0.80, test_size = 0.20, stratify = y_train, random_state = 42 ) X_train.shape, X_val.shape, y_train.shape, y_val.shape # - y_train.value_counts(normalize=True) # + [markdown] colab_type="text" id="kOdIbMMCr4Nc" # ## Use scikit-learn for logistic regression # - [sklearn.linear_model.LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) # - Wikipedia, [Logistic regression](https://en.wikipedia.org/wiki/Logistic_regression) # + [markdown] colab_type="text" id="RIiTQPQ_8bDX" # ### Begin with baselines: fast, first models # # #### Drop non-numeric features # + colab={} colab_type="code" id="OEUujvzH7pBO" X_train_numeric = X_train.select_dtypes('number') X_train_numeric # - X_val_numeric = X_val.select_dtypes('number') # + [markdown] colab_type="text" id="5cVaFgL_8lZl" # #### Drop nulls if necessary # + colab={} colab_type="code" id="FAkDFto77qec" X_train_numeric.isnull().sum() # + [markdown] colab_type="text" id="xMJL579p8tSM" # #### Fit Logistic Regresson on train data # + colab={} colab_type="code" id="2pEyqCGy7-kZ" import sklearn sklearn.__version__ # - # Import from sklearn.linear_model import LogisticRegressionCV # Instantiate model = LogisticRegressionCV() # Fit model.fit(X_train_numeric, y_train) # + [markdown] colab_type="text" id="WyIUh-th9Bnw" # #### Evaluate on validation data # + colab={} colab_type="code" id="Um_q4k9-8zvp" from sklearn.metrics import accuracy_score y_pred = model.predict(X_val_numeric) accuracy_score(y_val,y_pred) # - model.score(X_val_numeric,y_val) # + [markdown] colab_type="text" id="jgYwtN7D9ewk" # #### What predictions does a Logistic Regression return? # + colab={} colab_type="code" id="-X9KwbEl9VJu" y_pred # - pd.Series(y_pred).value_counts(normalize=True) y_pred_proba = model.predict_proba(X_val_numeric) y_pred_proba # + [markdown] colab_type="text" id="CkE2lbblr7Fn" # ## Do one-hot encoding of categorical features # + [markdown] colab_type="text" id="y1AuoNR-BO-N" # ### Check "cardinality" of categorical features # # [Cardinality](https://simple.wikipedia.org/wiki/Cardinality) means the number of unique values that a feature has: # > In mathematics, the cardinality of a set means the number of its elements. For example, the set A = {2, 4, 6} contains 3 elements, and therefore A has a cardinality of 3. # # One-hot encoding adds a dimension for each unique value of each categorical feature. So, it may not be a good choice for "high cardinality" categoricals that have dozens, hundreds, or thousands of unique values. # + colab={} colab_type="code" id="hLbD2DLmAm1g" X_train.describe(exclude = 'number').T.sort_values(by = 'unique') # + [markdown] colab_type="text" id="MbV7HjibCYV5" # ### Explore `quantity` feature # + colab={} colab_type="code" id="iOZ3QQoFBhoS" X_train['quantity'].value_counts(normalize=True) # + #Recombine X_train and y_train, for exploratory data analysis train = X_train.copy() train['status_group'] = y_train #Now we do groupby train.groupby('quantity')['status_group'].value_counts(normalize=True) # + # %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns train['functional'] = (train['status_group']== 'functional').astype(int) train[['status_group', 'functional']] # - sns.catplot(x='quantity', y='functional', data = train, kind = 'bar', color = 'grey') plt.title('Percentage of Waterpumps Functional By Water Quality') # + [markdown] colab_type="text" id="6kCA47KPr9PE" # ## Do one-hot encoding & Scale features, # within a complete model fitting workflow. # # ### Why and how to scale features before fitting linear models # # Scikit-Learn User Guide, [Preprocessing data](https://scikit-learn.org/stable/modules/preprocessing.html) # > Standardization of datasets is a common requirement for many machine learning estimators implemented in scikit-learn; they might behave badly if the individual features do not more or less look like standard normally distributed data: Gaussian with zero mean and unit variance. # # > The `preprocessing` module further provides a utility class `StandardScaler` that implements the `Transformer` API to compute the mean and standard deviation on a training set. The scaler instance can then be used on new data to transform it the same way it did on the training set. # # ### How to use encoders and scalers in scikit-learn # - Use the **`fit_transform`** method on the **train** set # - Use the **`transform`** method on the **validation** set # # + colab={} colab_type="code" id="yTkS24UwHJHa" import category_encoders as ce from sklearn.preprocessing import StandardScaler categorical_features = ['quantity'] numeric_features = X_train.select_dtypes('number').columns.drop('id').tolist() features = categorical_features + numeric_features X_train_subset = X_train[features] X_val_subset = X_val[features] encoder = ce.OneHotEncoder(use_cat_names=True) X_train_encoded = encoder.fit_transform(X_train_subset) X_val_encoded = encoder.transform(X_val_subset) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train_encoded) X_val_scaled = scaler.transform(X_val_encoded) model = LogisticRegressionCV() model.fit(X_train_scaled, y_train) print('Validation Accuracy', model.score(X_val_scaled, y_val)) # + [markdown] colab_type="text" id="Chix-W9-LTEX" # ### Compare original features, encoded features, & scaled features # + colab={} colab_type="code" id="YhJ3PHTAKzFx" # Shape of the original frame print(X_train.shape) X_train[:1] # - # Shape of subset frame print(X_train_subset.shape) X_train_subset[:1] # Shape of encoded dataframe print(X_train_encoded.shape) X_train_encoded[:1] # + [markdown] colab_type="text" id="ZfVECpN7J6gb" # ### Get & plot coefficients # + colab={} colab_type="code" id="9nHkKk5XKwVm" model.coef_ # + functional_coefficients = pd.Series( model.coef_[0], X_train_encoded.columns ) plt.figure(figsize=(10,10)) functional_coefficients.sort_values().plot.barh() # + [markdown] colab_type="text" id="ZhUzucgPr_he" # ## Submit to predictive modeling competition # # # ### Write submission CSV file # # The format for the submission file is simply the row id and the predicted label (for an example, see `sample_submission.csv` on the data download page. # # For example, if you just predicted that all the waterpoints were functional you would have the following predictions: # # <pre>id,status_group # 50785,functional # 51630,functional # 17168,functional # 45559,functional # 49871,functional # </pre> # # Your code to generate a submission file may look like this: # <pre># estimator is your scikit-learn estimator, which you've fit on X_train # # # X_test is your pandas dataframe or numpy array, # # with the same number of rows, in the same order, as test_features.csv, # # and the same number of columns, in the same order, as X_train # # y_pred = estimator.predict(X_test) # # # # Makes a dataframe with two columns, id and status_group, # # and writes to a csv file, without the index # # sample_submission = pd.read_csv('sample_submission.csv') # submission = sample_submission.copy() # submission['status_group'] = y_pred # submission.to_csv('your-submission-filename.csv', index=False) # </pre> # - X_test_subset = test_features[features] X_test_encoded = encoder.transform(X_test_subset) X_test_scaled = scaler.transform(X_test_encoded) assert all(X_test_encoded.columns == X_train_encoded.columns) y_pred = model.predict(X_test_scaled) # + colab={} colab_type="code" id="yRitgZ_ULx6K" submission = sample_submission.copy() submission['status_group'] = y_pred submission.to_csv('submission-01.csv', index = False) # + [markdown] colab_type="text" id="PpG9knom1FN7" # ### Send submission CSV file to Kaggle # # #### Option 1. Kaggle web UI # # Go to our Kaggle InClass competition webpage. Use the blue **Submit Predictions** button to upload your CSV file. # # # #### Option 2. Kaggle API # # Use the Kaggle API to upload your CSV file.
module4/lesson_regression_classification_4.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- set.seed(1485) len = 24 x = runif(len) y = x^3+rnorm(len, 0,0.06) ds = data.frame(x = x, y = y) str(ds) plot( y ~ x, main ="Known cubic with noise") s = seq(0,1,length =100) lines(s, s^3, lty =2, col ="green") m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T) class(m) summary(m) power = round(summary(m)$coefficients[1], 3) power.se = round(summary(m)$coefficients[2], 3) plot(y ~ x, main = "Fitted power model", sub = "Blue: fit; green: known") s = seq(0, 1, length = 100) lines(s, s^3, lty = 2, col = "green") lines(s, predict(m, list(x = s)), lty = 1, col = "blue") text(0, 0.5, paste("y =x^ (", power, " +/- ", power.se, ")", sep = ""), pos = 4)
doc/Programs/JupyterFiles/Examples/Lecture Examples/R Cubic Gaussian White Noise.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline dataSet = pd.read_csv('Data/pm25.csv') dataSet dataSet.plot(x='Months',y='AQI_Value',style='.') plt.title('AQI data of last 5 years') plt.xlabel('Months from 01-01-2015 to 01-09-2019') plt.ylabel('PM2.5 Level') plt.show() dataSet.plot(x='Months',y='AQI_Value',style='-') plt.title('AQI data of last 5 years') plt.xlabel('Months from 01-01-2015 to 01-09-2019') plt.ylabel('PM2.5 Level') plt.show() from sklearn.model_selection import train_test_split x = dataSet.iloc[:,:-1].values y = dataSet.iloc[:,1].values x_train,x_test,y_train,y_test = train_test_split(x,y, test_size=0.18) from sklearn.linear_model import LinearRegression regressor =LinearRegression() regressor.fit(x_train,y_train) plt.scatter(x=x_train,y=y_train) print(regressor.intercept_) print(regressor.coef_) y_pred = regressor.predict(x_test) print(x_pred) df = pd.DataFrame({'Actual':y_test,'Predicted':y_pred}) df from sklearn import metrics from sklearn.metrics import mean_squared_error, r2_score print('Mean Squared Error : ', mean_squared_error(y_test, y_pred)) print('Root means squared error : ', np.sqrt(mean_squared_error(y_test, y_pred))) print('r_2 statistic (Accuracy): %.2f' %r2_score(y_test, y_pred))
Predict/predict.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R [conda env:Georg_animal_feces-tidyverse] # language: R # name: conda-env-Georg_animal_feces-tidyverse-r # --- # # Goal # # * Primer design for clade of interest # # Var base_dir = '/ebio/abt3_projects/software/dev/ll_pipelines/llprimer/experiments/HMP_most-wanted/' clade = 'Butyricimonas' taxid = 574697 # # Init library(dplyr) library(tidyr) library(ggplot2) library(LeyLabRMisc) df.dims() work_dir = file.path(base_dir, clade) make_dir(work_dir) # # Genome download # # * Downloading genomes from NCBI # ``` # OUTDIR=/ebio/abt3_projects/software/dev/ll_pipelines/llprimer/experiments/HMP_most-wanted/Butyricimonas/ # mkdir -p $OUTDIR # ncbi-genome-download -p 12 -s genbank -F fasta --genera Butyricimonas -o $OUTDIR bacteria # ``` # # Genome quality # # * Filtering genomes by quality # + D = file.path(base_dir, clade, 'genbank') files = list_files(D, '.fna.gz') samps = data.frame(Name = files %>% as.character %>% basename, Fasta = files, Domain = 'Bacteria', Taxid = taxid) %>% mutate(Name = gsub('\\.fna\\.gz$', '', Name), Fasta = gsub('/+', '/', Fasta)) samps # writing file outfile = file.path(D, 'samples.txt') write_table(samps, outfile) # - # ### LLG # #### Config cat_file(file.path(work_dir, 'config_llg.yaml')) # #### Run # # ``` # (snakemake) @ rick:/ebio/abt3_projects/software/dev/ll_pipelines/llg # $ screen -L -S llg ./snakemake_sge.sh /ebio/abt3_projects/software/dev/ll_pipelines/llprimer/experiments/HMP_most-wanted/Butyricimonas/config_llg.yaml 20 -F # ``` # ### Samples table of high-quality genomes # checkM summary checkm = file.path(work_dir, 'LLG_output', 'checkM', 'checkm_qa_summary.tsv') %>% read.delim(sep='\t') checkm # dRep summary drep = file.path(work_dir, 'LLG_output', 'drep', 'checkm_markers_qa_summary.tsv') %>% read.delim(sep='\t') %>% mutate(Bin.Id = gsub('.+/', '', genome), Bin.Id = gsub('\\.fna$', '', Bin.Id)) drep # de-replicated genomes drep_gen = file.path(work_dir, 'LLG_output', 'drep', 'dereplicated_genomes.tsv') %>% read.delim(sep='\t') drep_gen # GTDBTk summary tax = file.path(work_dir, 'LLG_output', 'gtdbtk', 'gtdbtk_bac_summary.tsv') %>% read.delim(, sep='\t') %>% separate(classification, c('Domain', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species'), sep=';') %>% select(-note, -classification_method, -pplacer_taxonomy, -other_related_references.genome_id.species_name.radius.ANI.AF.) tax # checking overlap cat('-- drep --\n') overlap(basename(as.character(drep_gen$Fasta)), basename(as.character(drep$genome))) cat('-- checkm --\n') overlap(drep$Bin.Id, checkm$Bin.Id) cat('-- gtdbtk --\n') overlap(drep$Bin.Id, tax$user_genome) # joining based on Bin.Id drep = drep %>% inner_join(checkm, c('Bin.Id')) %>% mutate(GEN = genome %>% as.character %>% basename) %>% inner_join(drep_gen %>% mutate(GEN = Fasta %>% as.character %>% basename), by=c('GEN')) %>% inner_join(tax, c('Bin.Id'='user_genome')) #%>% drep # filtering by quality hq_genomes = drep %>% filter(completeness >= 90, contamination < 5, Strain.heterogeneity < 50) hq_genomes # summarizing the taxonomy df.dims(20) hq_genomes %>% group_by(Family, Genus) %>% summarize(n_genomes = n(), .groups='drop') df.dims() # writing samples table for LLPRIMER outfile = file.path(work_dir, 'samples_genomes_hq.txt') hq_genomes %>% select(Bin.Id, Fasta) %>% rename('Taxon' = Bin.Id) %>% mutate(Taxon = gsub('_chromosome.+', '', Taxon), Taxon = gsub('_bin_.+', '', Taxon), Taxon = gsub('_genomic', '', Taxon), Taxon = gsub('_annotated_assembly', '', Taxon), Taxid = taxid) %>% write_table(outfile) # # Primer design # ### Config F = file.path(work_dir, 'primers', 'config.yaml') cat_file(F) # ### Run # ``` # (snakemake) @ rick:/ebio/abt3_projects/software/dev/ll_pipelines/llprimer # $ screen -L -S llprimer-But ./snakemake_sge.sh /ebio/abt3_projects/software/dev/ll_pipelines/llprimer/experiments/HMP_most-wanted/Butyricimonas/primers/config.yaml 50 -F # ``` # ### Summary primer_info = read.delim(file.path(work_dir, 'primers', 'cgp', 'primers_final_info.tsv'), sep='\t') primer_info %>% unique_n('primer sets', primer_set) primer_info # ### Gene cluster annotations gene_annot = read.delim(file.path(work_dir, 'primers', 'cgp', 'core_clusters_blastx.tsv'), sep='\t') %>% mutate(cluster_id = gsub('cluster_', '', cluster_id) %>% as.Num) %>% semi_join(primer_info, c('cluster_id')) %>% mutate(gene_name = gsub(' \\[.+', '', subject_name), gene_taxonomy = gsub('.+\\[', '', subject_name), gene_taxonomy = gsub('\\]', '', gene_taxonomy)) gene_annot df.dims(50) gene_annot %>% distinct(cluster_id, gene_name) df.dims() df.dims(50) gene_annot %>% distinct(cluster_id, gene_taxonomy) df.dims() # ### Gene cluster: clostest related gene_annot = read.delim(file.path(work_dir, 'primers', 'cgp', 'core_clusters_blastx_nontarget.tsv'), sep='\t') %>% mutate(cluster_id = gsub('cluster_', '', cluster_id) %>% as.Num) %>% semi_join(primer_info, c('cluster_id')) %>% mutate(gene_name = gsub(' \\[.+', '', subject_name), gene_taxonomy = gsub('.+\\[', '', subject_name), gene_taxonomy = gsub('\\]', '', gene_taxonomy)) gene_annot # + df.dims(50) gene_annot %>% filter(pident > 80, pident_rank <= 3) %>% select(cluster_id, gene_name, gene_taxonomy, pident) df.dims() # - # # sessionInfo pipelineInfo('/ebio/abt3_projects/software/dev/ll_pipelines/llg/') pipelineInfo('/ebio/abt3_projects/software/dev/ll_pipelines/llprimer/') sessionInfo()
notebooks/HMP_most_wanted/v0.2/02d_Butyricimonas.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.8.10 64-bit # name: python3 # --- # # Imports from IPython.display import display import pandas as pd from os import mkdir # # Paso 0: Establecer archivos a cargar y descarga # + contentFolder = "./v2" #mkdir(f"{contentFolder}/Output") openAireCSV = f"{contentFolder}/openAireORCIDs.csv" upmCSV = f"{contentFolder}/archivoDigitalUPM.csv" orcidCSV = f"v3/orcidData.csv" path2Results = f"./v3/Output/" # - # # Paso 1: Carga de Archivos depurados openAireDF = pd.read_csv(openAireCSV) upmDF = pd.read_csv(upmCSV) orcidDF = pd.read_csv(orcidCSV) # # Paso 2: Eliminacion de redundancias al abrir # # + # Remove duplicates openAireDF = openAireDF.drop_duplicates(subset=["OA UPM"]) upmDF = upmDF.drop_duplicates(subset=["OA UPM"]) orcidDF = orcidDF.drop_duplicates(subset=["orcid-id"]) # Remove Unnamed columns try: upmDF = upmDF.drop(columns=["Unnamed: 0"]) except: pass try: upmDF = upmDF.drop(columns=["Unnamed: 0"]) except: pass try: orcidDF = orcidDF.drop(columns=["Unnamed: 0"]) except: pass # - # # Paso 3: Display de Tablas display(openAireDF) display(upmDF) display(orcidDF) # # Paso 4: Análisis de los Datos # + orcidOpenAire = orcidDF.merge(openAireDF, on="orcid-id", how="inner") orcidOpenAire.drop(columns=list(orcidDF.keys())+["fullname","name","surname"], inplace=True) # Remove Columns not related to Paper itself orcidOpenAire.drop_duplicates(subset=["id"], inplace=True) # Remove duplicates based on openAire ID display(orcidOpenAire) # - # #### Comentarios # Aqui obtenemos los papers de aquellos que en Orcid aparezcan como que forman parte de la Universidad Politecnica de Madrid, es decir papers de la UPM # # Observacion importante: # <ol> # <li>La busqueda en Orcid depende del Usuario haya puesto "Universidad Politecnica de Madrid" en el campo de instituciones</li> # <li>La busqueda en Orcid tambien añade el campo de GRID asociado a la UPM</li> # </ol> openAireADUPM = orcidOpenAire.merge(upmDF, on="OA UPM", how="inner") openAireADUPM.drop_duplicates(subset=["OA UPM"], inplace=True) # Remove duplicates based on openAire ID display(openAireADUPM) openAireADUPM.to_csv(f"{path2Results}Orcid_OpenAire_ADUPM-ORCIDs-MERGE.csv", index=False) # #### Comentarios # # Recomendacion importante: # <ol> # <li>Dar la recomendacion de publicar por ORCID en OpenAire</li> # </ol> porNombres = orcidDF.merge(openAireDF, left_on=["given-names","family-names"],right_on=["name","surname"], how="inner") porNombres.drop(columns=list(orcidDF.keys()[1:])+["orcid-id_x","orcid-id_y","fullname","name","surname"], inplace=True) # Remove Columns not related to Paper itself porNombres.drop_duplicates(subset=["id"], inplace=True) # Remove duplicates based on openAire ID display(porNombres) openAireADUPM = porNombres.merge(upmDF, on="OA UPM", how="inner") openAireADUPM.drop_duplicates(subset=["OA UPM"], inplace=True) # Remove duplicates based on openAire ID display(openAireADUPM) openAireADUPM.to_csv(f"{path2Results}Orcid_OpenAire_ADUPM-NAMES-MERGE.csv", index=False)
Fast2Results/ResultsQ2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import sys sys.path.insert(0, "ov-predict/src/") import numpy as np from model.lstm import buildModel from api.model_loader import init_embedding from api.model_loader import predict_outcome from preprocessing.InputHelper import InputHelper NODEVEC_DIM=128 PUBMED_DIM=200 NUM_CLASSES=0 EMB_FILE='../../core/prediction/graphs/nodevecs/ndvecs.cv.128-10-0.1-0.9-both-0-false.merged.vec' DATAFILE='../../core/prediction/sentences/train.tsv' TESTFILE='../../core/prediction/sentences/test.tsv' SAVED_MODEL_FILE='ov-predict/saved_models/model.h5' FOLLOWUP_ATTRIB_NAME='4087191' VAL_DIMENSIONS=5 MAXLEN=50 def is_number(s): try: float(s) return True except ValueError: return False # + def isFollowupNode(token): parts = token.split(':') nodename = parts[1] if nodename == FOLLOWUP_ATTRIB_NAME: return True return False def followupAttribOccurrenceIndex(attribseq): for i in range(len(attribseq)): token = attribseq[i] if isFollowupNode(token) == True: return i return -1 # + ''' To make the prediction workflow work, we need to first load the word vectors in memory and then dynamically change the vectors. For example, if in arm (document) D1, the followup time was 't_0', and suppose in the same document, we want to change it to 't', then 1. Find the vector from the dictionary (say v) with the value closest to 't' (the value for which we want to predict). 2. Replace the context part of v with the context vector of the current arm. 3. Put the value of 't' in place of 't_0' in the vector. While working with a pre-trained model, the index of a word in the vocabulary represents a context vector for a feature, e.g., the vocabulary index 'i' may refer to the followup attribute for document D1. At run-time, we simply replace this i-th vector with the one mentioned above. Once prediction is done, we revert back to the original vector. This ensures that we don't need to insert new words in the vocabulary. ''' class FollowupAnalyzer: def constructFollowupNodes(self): self.followupNodes = [] for token in self.inpH.pre_emb: parts = token.split(':') nodename = parts[1] if nodename == FOLLOWUP_ATTRIB_NAME and is_number(parts[2])==True: self.followupNodes.append(token) def __init__(self, embfile): self.inpH = init_embedding(embfile) self.model = buildModel(NUM_CLASSES, self.inpH.vocab_size, self.inpH.embedding_matrix.shape[1], MAXLEN, self.inpH.embedding_matrix) self.model.summary() self.model.load_weights(SAVED_MODEL_FILE) self.constructFollowupNodes() def closestFollowupNode(self, value): #value: float mindiff = 10000 minIndex = 0 i = 0 for n in self.followupNodes: x = float(n.split(':')[2]) diff = abs(value - x) if diff < mindiff: mindiff = diff minIndex = i i+=1 return self.followupNodes[minIndex] #change the vector of an instance node so that the embedding layer will then #use the modified instance vec for making predictions def modifyNodeInstanceVec(self, node, value): #node:string -- an entire node <Type>:<AttribId>:<ArmId> # get the closest node to the given value matchedNode = self.closestFollowupNode(value) #print ("**Matched Node**: {}, value = {}".format(matchedNode, self.inpH.pre_emb[matchedNode][-VAL_DIMENSIONS])) # Get the vector of the current node (from the arm) and also that of # the closest node (node definition). The former is a context vector, # the latter is a node defintion vector. attrvec = self.inpH.pre_emb[matchedNode] instvec = [] #replace the nodevec part of instvec with attrvec for i in range(NODEVEC_DIM): instvec.append(float(attrvec[i])) #context part comes from the current instance for i in range(NODEVEC_DIM, NODEVEC_DIM+PUBMED_DIM+VAL_DIMENSIONS): #instvec.append(0) instvec.append(float(self.inpH.pre_emb[node][i])) instvec_array = np.asarray(instvec) instvec_array[-VAL_DIMENSIONS] = value #new followup value self.inpH.pre_emb[node] = instvec_array # modified instvec def revertNodeInstanceVec(self, node, subvec, value): i=0 for x in subvec: self.inpH.pre_emb[node][i] = x i+=1 self.inpH.pre_emb[node][-VAL_DIMENSIONS] = value # reverting back # + ''' A token is of the form <TYPE>:ATTRIBID:<DOC-ARM>. The DOC-ARM part of the token will be useful to get the exact numerical value of an attribute (if the attribute is numeric, which is true for the follow-up attribute type). For this, we need to find out the vector from the embedding file corresponding to the given token. The first component of the last 5 numbers from the vector gives its value. E.g. O:4087191:Schnoll_2019.pdf_1 0.19425800442695618... <52.0> 0.0 0.0 0.0 0.0 We know from the above line that the value of the followup duration is 52 weeks. ''' def geTrueFollowupValue(token, inpH): vec = inpH.pre_emb[token] # vec is a numnp array return vec[-VAL_DIMENSIONS] # + def getInstanceVecInfo(followupAnalyzer, instance): followupAttribIndex = followupAttribOccurrenceIndex(instance) if followupAttribIndex < 0: return None, 0, None node = instance[followupAttribIndex] #get the true value valueInData = geTrueFollowupValue(node, followupAnalyzer.inpH) instance_without_followup = [] i=0 for x in instance: if not i==followupAttribIndex: instance_without_followup.append(x) i+=1 return node, valueInData, instance_without_followup def getNodeVec(vec): subvec = [] for i in range(NODEVEC_DIM): subvec.append(vec[i]) return subvec # - def predictionOnInstance(followupAnalyzer, avpsequence): results=[] #predict for true followup node, valueInData, instance_without_followup = getInstanceVecInfo(followupAnalyzer, avpsequence) if node==None: return ndvec = getNodeVec(followupAnalyzer.inpH.pre_emb[node]) #print("Original instance-vec: {} {} {} {}".format(node, followupAnalyzer.inpH.pre_emb[node][0:5], # followupAnalyzer.inpH.pre_emb[node][200:205], # followupAnalyzer.inpH.pre_emb[node][-VAL_DIMENSIONS])) #print ('Attribute Instance with followup: {} (length = {})'.format(avpsequence, len(avpsequence))) predicted_val = predict_outcome(followupAnalyzer.inpH, followupAnalyzer.model, avpsequence) #print ('Predicted outcome with followup of {} weeks = {}'.format(valueInData, str(predicted_val[0]))) results.append(predicted_val[0]) #print ('Attribute Instance w/o followup: {} (length={})'.format(instance_without_followup, len(instance_without_followup))) predicted_val = predict_outcome(followupAnalyzer.inpH, followupAnalyzer.model, instance_without_followup) #print ('Predicted outcome without followup attribute {} = {}'.format(valueInData, str(predicted_val[0]))) results.append(predicted_val[0]) #print("Original: {}".format(followupAnalyzer.inpH.pre_emb[node][-VAL_DIMENSIONS-5:])) #predict for pseudo-data #for t in range(8, 104, 8): for t in range(8, 52, 4): #call to this function changes the vector for the embedding layer followupAnalyzer.modifyNodeInstanceVec(node, t) #print("Modified: {} {} {}".format(followupAnalyzer.inpH.pre_emb[node][0:5], # followupAnalyzer.inpH.pre_emb[node][200:205], # followupAnalyzer.inpH.pre_emb[node][-VAL_DIMENSIONS])) predicted_val = predict_outcome(followupAnalyzer.inpH, followupAnalyzer.model, avpsequence) #print ('Predicted outcome with followup of {} weeks = {}'.format(t, str(predicted_val[0]))) #revert back after every change followupAnalyzer.revertNodeInstanceVec(node, ndvec, float(valueInData)) #print("Reverted: {} {} {}".format(followupAnalyzer.inpH.pre_emb[node][0:5], # followupAnalyzer.inpH.pre_emb[node][200:205], # followupAnalyzer.inpH.pre_emb[node][-VAL_DIMENSIONS])) results.append(predicted_val[0]) print(results) # + def isIntervention(token): if token.split(':')[0]=='I': return True return False #Function to filter out only the interventions from an avp sequence def filterInterventions(avpseq): interventionseq = [] for x in avpseq: if isFollowupNode(x)==True or isIntervention(x)==True: interventionseq.append(x) return ' '.join(interventionseq) # - # Load the data as two matrices - X and Y def getTsvData(filepath): print("Loading data from " + filepath) x = [] # positive samples from file for line in open(filepath): l = line.strip().split("\t") x.append(l[0].split(' ')) return x #DATA_INSTANCE='C:5579689:18 I:3675717:1 C:5579088:35 I:3673272:1 O:4087191:52.0' followupAnalyzer = FollowupAnalyzer(EMB_FILE) # + text_instances = getTsvData(DATAFILE) #y's are unused text_instances_interventions_only = [] for instance in text_instances: filteredInstance = filterInterventions(instance) # work only with interventions text_instances_interventions_only.append(filteredInstance) # + #collect instances with followups followup_datainstances = [] for avpseq in text_instances_interventions_only: avpseq = avpseq.split(' ') # string to list of tokens if not len(avpseq) > 1: continue node, valueInData, instance_without_followup = getInstanceVecInfo(followupAnalyzer, avpseq) if not node==None: followup_datainstances.append(avpseq) #for avpseq in followup_datainstances[:4]: for avpseq in followup_datainstances: predictionOnInstance(followupAnalyzer, avpseq) # -
prediction-experiments/python-nb/followup_analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: cmip6 # language: python # name: cmip6 # --- # !/gws/pw/j05/cop26_hackathons/bristol/install-kernel # + #import packages - works in CMIP6 notebook from itertools import chain from glob import glob import matplotlib.tri as tri import matplotlib.pyplot as plt import xarray as xr from matplotlib import cm from cartopy import config import cartopy.crs as ccrs import cartopy.feature as cfeature from palettable.cmocean.sequential import Algae_20 from palettable.cmocean.diverging import Balance_20 import numpy as np from matplotlib.colors import BoundaryNorm # Set some plotting defaults plt.rcParams['figure.figsize'] = (10, 6) plt.rcParams['figure.dpi'] = 100 # - #read in ssp370 2015-2024 model='UKESM1' path='/gws/pw/j05/cop26_hackathons/bristol/project03/output_nc/transeff_Omon_UKESM1-0-LL_ssp370_r1i1p1f2_gn_*.nc' dataset = xr.open_mfdataset(path) #read in ssp370 2090-2099 #path2='/gws/pw/j05/cop26_hackathons/bristol/project03/output_nc/timeslice_fluxes_2090_2100expc_Omon_UKESM1-0-LL_ssp585_r1i1p1f2_gn_*.nc' #dataset2 = xr.open_mfdataset(path2) dataset # + #dataset2 # - #define function for a single spatial plot def spatialplot(x, y, z, vmin, vmax, cbi, cblab, title, name): # The following section interpolates from the weird grid to a regularly spaced lat lon grid. X = x.values.ravel() Y = y.values.ravel() Z = z.values.ravel() triangles = tri.Triangulation(X, Y) X_interp, Y_interp = np.meshgrid(np.linspace(-180, 180, 360), np.linspace(-90, 90, 330)) interp_lin = tri.LinearTriInterpolator(triangles, Z) Z_interp = interp_lin(X_interp, Y_interp) #load land and create colorbar levels levls=np.arange(vmin,vmax,cbi)#arranging the colorbar levels land_10m = cfeature.NaturalEarthFeature('physical', 'land', '110m', edgecolor='face', facecolor=cfeature.COLORS['land']) #Plotting fig = plt.figure(figsize=(10, 5)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mollweide(central_longitude=0))#change the projection here cmap=Algae_20.mpl_colormap #change colormap here norm = BoundaryNorm(levls, ncolors=cmap.N, clip=True)#normalising the colorbar to the specified levels plot=plt.pcolormesh(X_interp,Y_interp,Z_interp, transform=ccrs.PlateCarree(), cmap=cmap, norm=norm, vmin=vmin, vmax=vmax) ax.add_feature(land_10m,facecolor='gray') ax.coastlines(resolution='110m') cb=plt.colorbar(plot,shrink=0.6,extend='max')#shrink colorbar relative to figure size, extend top of the colorbar cb.ax.set_ylabel(cblab)#set colorbar label plt.title(title) plt.show() fig.savefig(name) #load 2015-2024 mean transfer efficiency expc=dataset['expc'] expc_15_24=expc.sel(time=slice("2015", "2024")) print(expc_15_24.shape) expc_15_24_mean=expc_15_24.mean(axis=0) # + #load in data and undertake any calculations/ unit conversions #x=lon, y=lat, z= 2D xarray variable, vmin=colorbar min value, vmax=colorbar maximum value, cbi=colorbar intervals, cblab=colorbar label, title=plot title #x = dataset['lon'] #y = dataset['lat'] x=dataset['longitude'] y=dataset['latitude'] z = expc_15_24_mean vmin=0 vmax=0.151 cbi=0.01 cblab='Transfer Efficiency' title=model+' ssp370 - 2015-2024 Mean' name="UKESM1_ssp370_teff_15_25_mean.jpg" # - #run function spatialplot(x,y,z,vmin,vmax,cbi,cblab,title,name) #calculate 2090s mean transfer efficiency - ssp370 #expc_90s_mean=dataset2['expc'] expc_90s=expc.sel(time=slice("2090", "2099")) print(expc_90s.shape) expc_90s_mean=expc_90s.mean(axis=0) #load in data and undertake any calculations/ unit conversions #x=lon, y=lat, z= 2D xarray variable, vmin=colorbar min value, vmax=colorbar maximum value, cbi=colorbar intervals, cblab=colorbar label, title=plot title x = dataset['longitude'] y = dataset['latitude'] z = expc_90s_mean vmin=0 vmax=0.151 cbi=0.01 cblab='Transfer Efficiency' title=model+' ssp370 2090-2099 Mean' name="UKESM1_ssp370_teff_90s_mean.jpg" #run function spatialplot(x,y,z,vmin,vmax,cbi,cblab,title,name) #define function for a single spatial plot - difference def spatialdiff(x, y, z, vmin, vmax, cbi, cblab, title, name): # The following section interpolates from the weird grid to a regularly spaced lat lon grid. X = x.values.ravel() Y = y.values.ravel() Z = z.values.ravel() triangles = tri.Triangulation(X, Y) X_interp, Y_interp = np.meshgrid(np.linspace(-180, 180, 360), np.linspace(-90, 90, 330)) interp_lin = tri.LinearTriInterpolator(triangles, Z) Z_interp = interp_lin(X_interp, Y_interp) #load land and create colorbar levels levls=np.arange(vmin,vmax,cbi)#arranging the colorbar levels land_10m = cfeature.NaturalEarthFeature('physical', 'land', '110m', edgecolor='face', facecolor=cfeature.COLORS['land']) #Plotting fig = plt.figure(figsize=(10, 5)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mollweide(central_longitude=0))#change the projection here cmap=Balance_20.mpl_colormap #change colormap here norm = BoundaryNorm(levls, ncolors=cmap.N, clip=True)#normalising the colorbar to the specified levels plot=plt.pcolormesh(X_interp,Y_interp,Z_interp, transform=ccrs.PlateCarree(), cmap=cmap, norm=norm, vmin=vmin, vmax=vmax) ax.add_feature(land_10m,facecolor='gray') ax.coastlines(resolution='110m') cb=plt.colorbar(plot,shrink=0.6,extend='both')#shrink colorbar relative to figure size, extend top of the colorbar cb.ax.set_ylabel(cblab)#set colorbar label plt.title(title) plt.show() fig.savefig(name) #calculate difference in transfer efficiency between the 2015-2024 and 2090s expcdiff=expc_90s_mean-expc_15_24_mean #load in data and undertake any calculations/ unit conversions #x=lon, y=lat, z= 2D xarray variable, vmin=colorbar min value, vmax=colorbar maximum value, cbi=colorbar intervals, cblab=colorbar label, title=plot title x = dataset['longitude'] y = dataset['latitude'] z = expcdiff vmin=-0.06 vmax=0.07 cbi=0.005 cblab='Transfer Efficiency' title=model+' -ssp370 - 2090s-2015s Difference' name="UKESM1_ssp370_teff_15_24_90s_diff.jpg" #run function spatialdiff(x,y,z,vmin,vmax,cbi,cblab,title,name)
code/Transfer_efficiency_15s_90s_plot_ssp370.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # <span style="color:red">Seaborn | Part-9: Strip Plot:</span> # Welcome back to another lecture on visualizing *categorical data* with Seaborn! In the last lecture, we discussed in detail the importance of Categorical data and general representation. In this lecture, we shall continue from where we left previously. Our discussion has majorly been around beeswarm visualization using Seaborn's Swarmplot. Today, we are going to discuss another important type of plot, i.e. **Strip Plot**, which is pretty similar to what we have already seen previously. # # So, let us begin by importing our requisities, that we have gathered over time. Then, slowly we shall start exploring parameters and scenarios where this plot could come in handy for us: # + # Importing intrinsic libraries: import numpy as np import pandas as pd np.random.seed(0) import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline sns.set(style="whitegrid", palette="rocket") import warnings warnings.filterwarnings("ignore") # Let us also get tableau colors we defined earlier: tableau_20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] # Scaling above RGB values to [0, 1] range, which is Matplotlib acceptable format: for i in range(len(tableau_20)): r, g, b = tableau_20[i] tableau_20[i] = (r / 255., g / 255., b / 255.) # - # We have already observed **Strip Plot** representation earlier as well so let us plot it at a basic level once again to begin our discussion with: # + # Loading built-in Tips dataset: tips = sns.load_dataset("tips") # Plotting basic Strip Plot by adding little noise with 'jitter' parameter: sns.stripplot(x="day", y="total_bill", data=tips, jitter=True) # - # Looks quite familiar, right? Indeed it is! This is again a *scatterplot presentation* with one of it's variable as *Categorical*. From *Tips* dataset, we have chosen *Days* of a Week as our categorical variable against the *Total bill* generated in the restaurant for that particular *day*. Just like *Swarm plot*, even [Strip Plot](https://seaborn.pydata.org/generated/seaborn.stripplot.html) can be plotted on it's own but generally it is coupled with other plots like **Violin plot**, as discussed earlier, and we shall go through those kind of coupling as well later on in this lecture. # # Important to note is that sometimes you might find professionals referring to **Strip plot** as **Dot Plot**, so that shouldn't actually confuse you as both refer to the same type of plot that we're looking at right now. # # For now, let us quickly go through the *parameters* to find if there is something that requires extra attention, or better to say, something that we haven't covered as of now: # # `seaborn.stripplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, jitter=False, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', linewidth=0, ax=None)` # Not that difficult to guess by now that `x`, `y` and `data` are our three mandatory parameters. Quick note here would be that you would often find me as well as other domain specific people abbreviating *parameters* as **params**, so I just thought of letting you know so that it doesn't ever confuse you. Moving on, rest of the *optional parameters* are similar to our Swarm plot and in the same order so nothing new out here for us to explore. # Let us then add few more *optional params* to our previous code to check it's flexibility: sns.stripplot(x="day", y="total_bill", hue="smoker", data=tips, jitter=True, palette="icefire", size= 7, dodge=True, lw=0.5) # There isn't much to explain here that we not aware of in terms of inference, though remember that if you need to plot these scattered points *horizontally*, all that you need to do is *interchange* `x` and `y` variable position. Let us slightly alter the aesthetics of our plot now: # + # Loading Iris dataset for this experiment: iris = sns.load_dataset("iris") # Melt dataset to 'long-form' or 'tidy' representation: iris = pd.melt(iris, "species", var_name="measurement") # - sns.stripplot(x="measurement", y="value", hue="species", order=['sepal_width','petal_width','sepal_length','petal_length'], data=iris, palette="hsv_r", size=15, marker="D", alpha=.30) # Personally, I am not really a great fan of these kind of strips but I have often seen it's implication in FinTech so if work for a bank or any closely related domain, you can play around with this by increasing the *size* or transparency with `alpha`, etc. You even have the option to change marker. Let me quickly replace this plot with `+` sign marker: sns.stripplot(x="measurement", y="value", hue="species", order=['sepal_width','petal_width','sepal_length','petal_length'], data=iris, palette="icefire", size=15, marker="P", alpha=.30) # This graphical data analysis technique for summarizing a univariate data set, pretty well suits the requirement to plot the sorted response values along one axis. So now let us try to enhance it even more by coupling with other plots. # # Meanwhile, I would also like you to know that generally in real-world, **Strip Plot** acts as a replacement to **Histogram** or **Density Plot**; but again *Strip Plots* are much more efficient with *long-form data* and not so good with *wide-form data*. For wide-form dataset, histograms and Density plot that we discussed in our previous lecture are going to be a better choice. Also need to remember that there is no *thumb-rule* for choosing a type of plot for any dataset because as mentioned earlier, it majorly depends upon the dataset in-hand and associated requirements. # Just like we explored pairing of plots with Swarm plot, let us now try thise with Strip plot on our Tips dataset: sns.boxplot(x="day", y="tip", data=tips, whis=np.inf, palette="cividis") sns.stripplot(x="day", y="tip", data=tips, jitter=True, color=tableau_20[2]) # We shall be discussing **Box plot** later in detail but for now, the *horizontal bar* at the top that you see is actually known as **whisker** and marks the extreme values for particular variable. Here, it marks the top **tip amount** given for **each day**. `np.inf` is a Python or say Cython attribute for getting float values. As always, `jitter` helps in adding *noise* to our dataset. Let us get a mix with Violin plot now. As stated earlier, such mixes get a broader visualization impact on insight extraction. sns.violinplot(x="day", y="total_bill", data=tips, inner=None) sns.stripplot(x="day", y="total_bill", data=tips, jitter=True, color=tableau_20[7]) # **Violin plot** has few different *optional params* that we shall discuss in it's specific lecture, but for now I would just like you to focus on the **strip plot** that gets beautifully enclosed within a Violin plot. # # You must have noticed by now that everytime I am adding noise to the dataset with `jitter`, but not necessarily had been doing this earlier, so let me explain why I add this parameter. The reason is that *Strip plots* in general struggle to display multiple data points with the same value. And `jitter` adds that random noise to vertical axis to compensate. # OKAY! That pretty much gets us done with everything that Seaborn Strip plot in general has to offer so now it is time for me to share with you few *tips and tricks* of real-world business. # # For illustration purpose, I shall build a simple Pandas DataFrame with just 3 variables, *City*, *Gender* and *Age*. And then try to plot a **Strip plot** with just 2 data points, one for each *Gender*. Let's do this: # + sample = [["Brooklyn", "Female", 80], ["Brooklyn", "Male", 66], ["Manhattan", "Female", 90], ["Manhattan", "Male", 53], ["Queens", "Female", 75], ["Queens", "Male", 63]] sample = pd.DataFrame(sample, columns=["City", "Gender", "Age"]) sns.stripplot(x="City", y="Age", hue="Gender", data=sample, palette="hsv", size=12, lw=1.5) # - # For this *sample* dataframe, we get our data points plotted but this plot doesn't give us too much of a feel, because obviously we do not have that many data points. This is a scenario you may come across, and then it is a better idea to have this plot modified a little to look good. And for that, let us add a *line* attaching both data points: # + # Customization help from underlying Matplotlib: from matplotlib import collections # Copy-paste previous code: sample = [["Brooklyn", "Female", 80], ["Brooklyn", "Male", 66], ["Manhattan", "Female", 90], ["Manhattan", "Male", 53], ["Queens", "Female", 75], ["Queens", "Male", 63]] sample = pd.DataFrame(sample, columns=["City", "Gender", "Age"]) ax = sns.stripplot(x="City", y="Age", hue="Gender", data=sample, palette="hsv", size=12, lw=1.5) # Modifications - Creating a Line connecting both Data points: lines = ([[x, i] for i in df] for x, (_, df) in enumerate(sample.groupby(["City"], sort=False)["Age"])) mlc = collections.LineCollection(lines, colors='red', linewidths=1.5) ax.add_collection(mlc) # - # I believe that looks much better and shows relevance upto an extent. Well, this can be customized further by adding *markers*, etc. but I shall leave that as a homework for you. # Moving on, let us try to plot a Strip plot with Tips dataset once again. There is something I want to show you regarding Legends on the plot here: sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True) # What if we want to *remove the legend* from our plot? Let's try that: sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True, legend=False) # Do you notice the **"AttributeError"** at the end? Generally a simple addition of `legend=False` should get you rid of Legends but with **Strip Plot**, it doesn't work and people often struggle with it. So let me show you how simple it actually is to remove that legend: # + ax = sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True) ax.legend_.remove() # - # And we successfully removed Legend from our plot. Okay! Now let me show you something that might be useful, if you into *Research domain* or trying to get into one such domain. What if we require *Mean*, *median*, *mode* from our plot. Let me show you **how to get median line** for a random dataset: # Every time we try to customize our plot, be it any of *Seaborn* plot, we shall be referencing underlying *Matplotlib*, just as we're going to do here for getting **horizontal lines for the median** points of our dataset. Let us try to get this done: # + # Creating sample DataFrame: sample = pd.DataFrame({"City": ["X", "X", "X", "Y", "Y", "Y"], "Moisture": [0.2, 0.275, 0.35, 0.7, 0.8, 0.9]}) # Calculating Median for both axes: x_med = sample.loc[sample["City"] == 'X'].median()['Moisture'] y_med = sample.loc[sample["City"] == 'Y'].median()['Moisture'] sns.stripplot(x="City", y="Moisture", data=sample, hue="City", palette="icefire") x = plt.gca().axes.get_xlim() # how to plot median line? plt.plot(x, len(x) * [x_med], sns.xkcd_rgb["denim blue"]) plt.plot(x, len(x) * [y_med], sns.xkcd_rgb["pale red"]) # - # With all these variations that we've learnt, we now have a good idea to deal with **Strip Plot**, as & when required. In the next lecture, we shall be dealing with a plot that we've already observed umpteen number of times but this time, it would be a detailed discussion about it's scope, variations and few more real-world scenarios. # # Till then, I would highly recommend to play around with these plots as much as you can and if you have any doubts, feel free to post in the forum. Also, it would be nice if you could take out a minute of your time to leave a review or at least rate this course using Course Dashboard; because that shall help other students gauge if this course is worth their time and money. # # And, I shall meet you in the next lecture where we will discuss **Box Plot**. Till then, Happy Visualizing!
Seaborn - Strip Plot.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: PredictiveMaintenance dlvmjme # language: python # name: predictivemaintenance_dlvmjme # --- # # Step 2B: Model Testing # # This notebook examines the model created in the `2b_model_building` notebook. # # Using the `2a_feature_engineering` Jupyter notebook, this notebook creates a new test data set and scores the observations using the machine learning model (a decision tree classifier or a random forest classifier) created in the `2b_model_building` to predict when different components within the test machine population will fail. Then using the known labels from the existing data, we calculate a set of evaluation metrics to understand how the model may perform when used in production settings. # # **Note:** This notebook will take about 2-4 minutes to execute all cells, depending on the compute configuration you have setup. # + # import the libraries # For some data handling import numpy as np import pandas as pd from collections import OrderedDict import pyspark.sql.functions as F from pyspark.ml import PipelineModel # for creating pipelines and model from pyspark.ml.feature import StringIndexer, VectorAssembler, VectorIndexer from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() import matplotlib.pyplot as plt # This is the final feature data file. testing_table = 'testing_data' model_type = 'RandomForest' # Use 'DecisionTree' or 'GBTClassifier' or 'RandomForest' # + dbutils.widgets.removeAll() dbutils.widgets.text("Testing_table",testing_table) dbutils.widgets.text("Model", model_type) dbutils.widgets.text("start_date", '2015-11-30') dbutils.widgets.text("to_date", '2016-02-01') # - # # Prepare the Training/Testing data # A fundamental practice in machine learning is to calibrate and test your model parameters on data that has not been used to train the model. Evaluation of the model requires splitting the available data into a training portion, a calibration portion and an evaluation portion. Typically, 80% of data is used to train the model and 10% each to calibrate any parameter selection and evaluate your model. # # In general random splitting can be used, but since time series data have an inherent correlation between observations. For predictive maintenance problems, a time-dependent spliting strategy is often a better approach to estimate performance. For a time-dependent split, a single point in time is chosen, the model is trained on examples up to that point in time, and validated on the examples after that point. This simulates training on current data and score data collected in the future data after the splitting point is not known. However, care must be taken on labels near the split point. In this case, feature records within 7 days of the split point can not be labeled as a failure, since that is unobserved data. # # In the following code blocks, we create a data set to test the model. #print(spark.catalog.listDatabases()) spark.catalog.setCurrentDatabase("default") exists = False for tbl in spark.catalog.listTables(): if tbl.name == dbutils.widgets.get("Testing_table"): exists = True break if not exists: dbutils.notebook.run("2a_feature_engineering", 600, {"features_table": dbutils.widgets.get("Testing_table"), "start_date": dbutils.widgets.get("start_date"), "to_date": dbutils.widgets.get("to_date")}) # # Classification models # # A particular problem in predictive maintenance is machine failures are usually rare occurrences compared to normal operation. This is fortunate for the business as maintenance and saftey issues are few, but causes an imbalance in the label distribution. This imbalance leads to poor performance as algorithms tend to classify majority class examples at the expense of minority class, since the total misclassification error is much improved when majority class is labeled correctly. This causes low recall or precision rates, although accuracy can be high. It becomes a larger problem when the cost of false alarms is very high. To help with this problem, sampling techniques such as oversampling of the minority examples can be used. These methods are not covered in this notebook. Because of this, it is also important to look at evaluation metrics other than accuracy alone. # # We will build and compare two different classification model approaches: # # - **Decision Tree Classifier**: Decision trees and their ensembles are popular methods for the machine learning tasks of classification and regression. Decision trees are widely used since they are easy to interpret, handle categorical features, extend to the multiclass classification setting, do not require feature scaling, and are able to capture non-linearities and feature interactions. # # - **Random Forest Classifier**: A random forest is an ensemble of decision trees. Random forests combine many decision trees in order to reduce the risk of overfitting. Tree ensemble algorithms such as random forests and boosting are among the top performers for classification and regression tasks. # # We will to compare these models in the AML Workbench _runs_ screen. The next code block creates the model. You can choose between a _DecisionTree_ or _RandomForest_ by setting the 'model_type' variable. We have also included a series of model hyperparameters to guide your exploration of the model space. # + model_pipeline = PipelineModel.load("dbfs:/storage/models/" + dbutils.widgets.get("Model") + ".pqt") print("Model loaded") model_pipeline # - # To evaluate this model, we predict the component failures over the test data set. Since the test set has been created from data the model has not been seen before, it simulates future data. The evaluation then can be generalize to how the model could perform when operationalized and used to score the data in real time. # + test_data = spark.table(dbutils.widgets.get("Testing_table")) # define list of input columns for downstream modeling # We'll use the known label, and key variables. label_var = ['label_e'] key_cols =['machineID','dt_truncated'] # Then get the remaing feature names from the data input_features = test_data.columns # We'll use the known label, key variables and # a few extra columns we won't need. remove_names = label_var + key_cols + ['failure','model_encoded','model' ] # Remove the extra names if that are in the input_features list input_features = [x for x in input_features if x not in set(remove_names)] #input_features # assemble features va = VectorAssembler(inputCols=(input_features), outputCol='features') # assemble features test_data = va.transform(test_data).select('machineID','dt_truncated','label_e','features').cache() # set maxCategories so features with > 10 distinct values are treated as continuous. featureIndexer = VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=10).fit(test_data) # fit on whole dataset to include all labels in index labelIndexer = StringIndexer(inputCol="label_e", outputCol="indexedLabel").fit(test_data) testing = test_data print(testing.count()) # make predictions. The Pipeline does all the same operations on the test data predictions = model_pipeline.transform(testing) # Create the confusion matrix for the multiclass prediction results # This result assumes a decision boundary of p = 0.5 conf_table = predictions.stat.crosstab('indexedLabel', 'prediction') confuse = conf_table.toPandas() confuse.head() # - # The confusion matrix lists each true component failure in rows and the predicted value in columns. Labels numbered 0.0 corresponds to no component failures. Labels numbered 1.0 through 4.0 correspond to failures in one of the four components in the machine. As an example, the third number in the top row indicates how many days we predicted component 2 would fail, when no components actually did fail. The second number in the second row, indicates how many days we correctly predicted a component 1 failure within the next 7 days. # # We read the confusion matrix numbers along the diagonal as correctly classifying the component failures. Numbers above the diagonal indicate the model incorrectly predicting a failure when non occured, and those below indicate incorrectly predicting a non-failure for the row indicated component failure. # # When evaluating classification models, it is convenient to reduce the results in the confusion matrix into a single performance statistic. However, depending on the problem space, it is impossible to always use the same statistic in this evaluation. Below, we calculate four such statistics. # # - **Accuracy**: reports how often we correctly predicted the labeled data. Unfortunatly, when there is a class imbalance (a large number of one of the labels relative to others), this measure is biased towards the largest class. In this case non-failure days. # # Because of the class imbalance inherint in predictive maintenance problems, it is better to look at the remaining statistics instead. Here positive predictions indicate a failure. # # - **Precision**: Precision is a measure of how well the model classifies the truely positive samples. Precision depends on falsely classifying negative days as positive. # # - **Recall**: Recall is a measure of how well the model can find the positive samples. Recall depends on falsely classifying positive days as negative. # # - **F1**: F1 considers both the precision and the recall. F1 score is the harmonic average of precision and recall. An F1 score reaches its best value at 1 (perfect precision and recall) and worst at 0. # # These metrics make the most sense for binary classifiers, though they are still useful for comparision in our multiclass setting. Below we calculate these evaluation statistics for the selected classifier, and post them back to the AML workbench run time page for tracking between experiments. # + # select (prediction, true label) and compute test error # select (prediction, true label) and compute test error # True positives - diagonal failure terms tp = confuse['1.0'][1]+confuse['2.0'][2]+confuse['3.0'][3]+confuse['4.0'][4] # False positves - All failure terms - True positives fp = np.sum(np.sum(confuse[['1.0', '2.0','3.0','4.0']])) - tp # True negatives tn = confuse['0.0'][0] # False negatives total of non-failure column - TN fn = np.sum(np.sum(confuse[['0.0']])) - tn # Accuracy is diagonal/total acc_n = tn + tp acc_d = np.sum(np.sum(confuse[['0.0','1.0', '2.0','3.0','4.0']])) acc = acc_n/acc_d # Calculate precision and recall. prec = tp/(tp+fp) rec = tp/(tp+fn) # Print the evaluation metrics to the notebook print("Accuracy = %g" % acc) print("Precision = %g" % prec) print("Recall = %g" % rec ) print("F1 = %g" % (2.0 * prec * rec/(prec + rec))) print("") # + importances = model_pipeline.stages[2] x = range(34) fig = plt.figure(1) ax = fig.add_subplot(111) plt.bar(x, list(importances.featureImportances.values)) plt.xticks(x) plt.xlabel('') ax.set_xticklabels(input_features, rotation = 90, ha="left") #plt.gcf().subplots_adjust(bottom=0.50) plt.tight_layout() display() # input_features # - # Remember that this is a simulated data set. We would expect a model built on real world data to behave very differently. The accuracy may still be close to one, but the precision and recall numbers would be much lower. # # # Conclusion # # The next step is to build the batch scoreing operations. The `3b_model_scoring` notebook takes parameters to define the data to be scored, and using the model created here, calulates the probability of component failure in the machine population specified.
notebooks/2b_model_testing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.12 64-bit (''brady'': conda)' # name: python3 # --- # + # %matplotlib inline import matplotlib.pyplot as plt import obspy import pandas as pd from obspy.core import UTCDateTime as udt import h5py POROTOMO_CONTINUOUS_NODAL_WAVEFORM_PATH = "https://nrel-pds-porotomo.s3.amazonaws.com/Nodal" def fetch_waveform(remote_path, remote_filename): url = remote_path + remote_filename return obspy.read(url)[0] # - cat = pd.read_pickle("../data/processed/meq_cat.pkl") # cat quaketimes = cat["DateTime"].apply(udt).to_list()[:-1] evids = cat.index.to_list()[:-1] # ## Most events are on 3/14/2016, onoe on 3/16/2016. One after the injection data coverage on 6/17/2016. # # ## Pull waveforms from 3/14 to start filename_data = pd.read_pickle("../data/processed/continuous_waveform_filenames.pkl") march14_files = filename_data[filename_data["date"]=="2016-3-14"] march14_files st1 = fetch_waveform(POROTOMO_CONTINUOUS_NODAL_WAVEFORM_PATH, march14_files.loc[17]["filename"]) st1.plot(type="dayplot");plt.show() meq1 = st1.slice(udt(cat.iloc[0]["DateTime"]), udt(cat.iloc[0]["DateTime"])+10) meq1.plot(); plt.show() st1 = fetch_waveform(march14_files.loc[17]["filename"], POROTOMO_CONTINUOUS_NODAL_WAVEFORM_PATH) # ### Need # # Continuous trace encompassing the quake(s) # Filter high pass at 0.1 Hz - length of template window # # For each quake, for each station, for each component: # - clip the quake at the event time and 10 seconds after # # Calculate moveout times: # Distance from event to each station # - station location # - event location # Wave speed # # # + # create templates # save into hdf5 file # file # |- templates # |- eventid # |- station # |- channel with h5py.File("/Volumes/T7/data/fmf_templates/templates.h5") as f: for i, quake in enumerate(quaketimes): evid = evids[i] # now select all files from the day of the quake files = filename_data[filename_data["date"]==quake.date.isoformat()] for file in files.to_dict(orient="records"): # - # + # To save downloads, slice each quake template from one download # Do by day so it works # 2016-03-14 templates = {} templates["waveforms"] = [] templates["station"] = [] templates["channel"] = [] templates["evid"] = [] badfiles = [] for file in filename_data[filename_data["date"]=="2016-03-14"].to_dict(orient="records"): try: waveform = fetch_waveform(POROTOMO_CONTINUOUS_NODAL_WAVEFORM_PATH, file["filename"]) for i, t0 in enumerate(quaketimes): templates["waveforms"].append(waveform.slice(t0, t0 + 10)) templates["evid"].append(evids[i]) templates["station"] = file["station"] templates["channel"] = file["channel"] print(file["filename"]) except Exception as e: print("Bad file: ", file["filename"]) print(e) badfiles.append(file["filename"]) # - filename_data[filename_data["date"]=="2016-03-14"]
notebooks/inspect_known_events.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # User Churn Prediction # ## Introducation # In this project, we use machine learning models to identify customers who are likely to stop using telecommunication service in the future. Furthermore, we analyze top factors that influence user retention. # # The analysis is important becasue we want to find if we can predict user behaviors and check the accuracy of prediction. Besides, we also want to understand the reasons behind users' behaviors. Using the results of the analysis, cell phone plan service providers can use it to improve their service, attract and retain more customers to stay in the business. # ## Background # User churn is also called customer attrition, or customer turn over. User churn prediction is a widely used analysis in business. # # Banks, telephone service companies, Internet service providers, etc., often perform user churn analysis and use customer churn rate as one of their key business metrics. It is because the cost of retaining an existing customer is far less than acquiring a new one. Companies from these sectors often have customer service branches which perform the analysis and use the result to guide the attempt to win back defecting clients. For these reasons, user churn is extensively studied in Operational Research, Business Intelligence, management, and advertising. # ## Analysis Method and Process # <ul> # <li>[Step 1: Data Exploration](#Step-1:-Data-Exploration) # <li>[Step 2: Feature Preprocessing](#Step-2:-Feature-Preprocessing) # <li>[Step 3: Model Training and Results Evaluation](#Step-3:-Model-Training-and-Result-Evaluation) # <li>[Step 4: Feature Selection](#Step-4:-Feature-Selection) # </ul> # ### Step 1: Data Exploration # The purpose of this step is to understand the dataset and clean messy data. To understand the dataset, we took a slice of data and simply examined the values. Also various data visualizations are used, for example, scatter plot and box plot, to check data distribution. To clean messy data, the step checks missing data, identify outliers, and manually split, combine, and change some data field. # #### Step 1.1: Understand the Raw Dataset # Data is from [UIC machine learning repository](https://archive.ics.uci.edu/ml/datasets.html). # UCI dataset is a part of Open Science and, specifically, Open Data program. The churn dataset uses [Open Data Commons Open Database License (ODbL)](https://en.wikipedia.org/wiki/Open_Database_License) # # + import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np pd.set_option('display.max_columns', None) churn_df = pd.read_csv('data/churn.all') # - churn_df.head() print "Num of rows: " + str(churn_df.shape[0]) # row count print "Num of columns: " + str(churn_df.shape[1]) # col count # #### Step 1.2: Data cleaning # We found there are extra white space before the "voice_mail_plan"variable. We removed extra whitespace and prepared the feature for further analysis. churn_df['voice_mail_plan'][4] churn_df['voice_mail_plan'] = churn_df['voice_mail_plan'].map(lambda x: x.strip()) churn_df['intl_plan'] = churn_df['intl_plan'].map(lambda x: x.strip()) churn_df['churned'] = churn_df['churned'].map(lambda x: x.strip()) # x.strip remove space # #### Step 1.3: Understand the features # Here we checked features' distributions and correlations between features. Visualizations are used extensively as a part of human-centered considerations, as we want to not only get a good result, but also understand the data and modeling process. # + # %matplotlib inline import matplotlib.pyplot as plt import seaborn as sb sb.distplot(churn_df['total_intl_charge'], kde=False) # + corr = churn_df[["account_length", "number_vmail_messages", "total_day_minutes", "total_day_calls", "total_day_charge", "total_eve_minutes", "total_eve_calls", "total_eve_charge", "total_night_minutes", "total_night_calls", "total_intl_minutes", "total_intl_calls", "total_intl_charge"]].corr() sb.heatmap(corr) # - corr from scipy.stats import pearsonr print pearsonr(churn_df['total_day_minutes'], churn_df['number_vmail_messages'])[0] # ### Step 2: Feature Preprocessing # Step 2 includes labelling categorical variables using one hot encoding. There are binary fields which are tranferred into 0 or 1. There are also fields not needed for the modeling. They are dropped in this step. Lastly, scaling features to normal is needed before feeding the features into the model. churn_df.head() y = np.where(churn_df['churned'] == 'True.',1,0) to_drop = ['state','area_code','phone_number','churned'] churn_feat_space = churn_df.drop(to_drop, axis=1) yes_no_cols = ["intl_plan","voice_mail_plan"] churn_feat_space[yes_no_cols] = churn_feat_space[yes_no_cols] == 'yes' X = churn_feat_space.as_matrix().astype(np.float) churn_feat_space[yes_no_cols] [0:10] X X.shape churn_feat_space.head() X # Scale the data to normal using StandardScaler. Prepare the features for modeling. # + from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X = scaler.fit_transform(X) print "Feature space holds %d observations and %d features" % X.shape print "Unique target labels:", np.unique(y) # - X.shape X[:,16] # ### Step 3: Model Training and Result Evaluation # This is the most important part of the analysis process. I started with the simple linear regression, and then try Logistic regression, K-nearest neighbor (k-NN), and Random Forest algorithms. I used k-fold cross validation, tuned hyper parameters, and evaluated the results using Confusion Matrix. # #### Step 3.1: K-fold Cross-Validation X y # + from sklearn.cross_validation import KFold def run_cv(X,y,clf_class,**kwargs): # Construct a kfolds object kf = KFold(len(y),n_folds=5,shuffle=True) y_pred = y.copy() clf = clf_class(**kwargs) # Iterate through folds for train_index, test_index in kf: X_train, X_test = X[train_index], X[test_index] y_train = y[train_index] clf.fit(X_train,y_train) y_pred[test_index] = clf.predict(X_test) return y_pred # - # #### Step 3.2: Run Three Supervised Learning Models and Calculate Accuracy # In this step, we ran three models (Logistic regression, KNN, and Random Forest) and compared their performance. # + from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression def accuracy(y_true,y_pred): return np.mean(y_true == y_pred) LR_CV_result = run_cv(X,y,LogisticRegression) RF_CV_result = run_cv(X,y,RandomForestClassifier) KNN_CV_result = run_cv(X,y,KNeighborsClassifier) # - print "Logistic Regression (L2 is default): " + str(accuracy(y, LR_CV_result)) print "Random forest: " + str(accuracy(y, RF_CV_result)) print "K-nearest-neighbors: " + str(accuracy(y, KNN_CV_result)) churn_df_LR_CV = churn_df churn_df_LR_CV['LR_Predicted_churned'] = LR_CV_result == 1 churn_df_LR_CV[churn_df_LR_CV.columns[-2:]].head(10) # #### Step 3.3: Use Grid Search to Find Optimal Parameters # #### Step 3.3.1: Find Optimal Parameters - LogisticRegression # We used grid search cross validation to find best penalty method (l1 or l2) and best hyperparameter. def print_grid_search_metrics(gs): print "Best score: %0.3f" % gs.best_score_ print "Best parameters set:" best_parameters = gs.best_params_ for param_name in sorted(parameters.keys()): print("\t%s: %r" % (param_name, best_parameters[param_name])) from sklearn.grid_search import GridSearchCV parameters = { 'penalty':('l1', 'l2'), 'C':(1, 5, 10) } Grid_LR = GridSearchCV(LogisticRegression(),parameters, cv=5, verbose=1, refit=False) Grid_LR.fit(X, y) print_grid_search_metrics(Grid_LR) from sklearn.cross_validation import cross_val_score score = cross_val_score(LogisticRegression(C=1,penalty='l1'), X, y, cv=5) print "Logistic Regression 5-fold cross validation accuracy: " + str(np.mean(score)) # #### Step 3.3.2: Find Optimal Parameters - KNN from sklearn.grid_search import GridSearchCV parameters = { 'n_neighbors':[3,5,7,10] } Grid_KNN = GridSearchCV(KNeighborsClassifier(),parameters, cv=5, verbose=1, refit=False) Grid_KNN.fit(X, y) print_grid_search_metrics(Grid_KNN) from sklearn.cross_validation import cross_val_score score = cross_val_score(KNeighborsClassifier(n_neighbors=5),X,y,cv=5) print "5-fold cross validation accuracy: " + str(np.mean(score)) # #### Step 3.4: Calculate Confusion Matrix (Precision, Recall, Accuracy) # In this setep, we evaluated model performance using Confusion Matrix. # + from sklearn.metrics import confusion_matrix from sklearn.metrics import precision_score from sklearn.metrics import recall_score def cal_evaluation(classifier, cm): tp = cm[0][0] fp = cm[0][1] fn = cm[1][0] tn = cm[1][1] accuracy = (tp + tn) / (tp + fp + fn + tn + 0.0) precision = tp / (tp + fp + 0.0) recall = tp / (tp + fn + 0.0) print classifier print "Accuracy is " + str(accuracy) print "Precision is " + str(precision) print "Recall is " + str(recall) def draw_confusion_matrices(confusion_matricies,class_names): class_names = class_names.tolist() for cm in confusion_matrices: classifier, cm = cm[0], cm[1] cal_evaluation(classifier, cm) fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(cm, interpolation='nearest',cmap=plt.get_cmap('Reds')) plt.title('Confusion matrix for %s' % classifier) fig.colorbar(cax) ax.set_xticklabels([''] + class_names) ax.set_yticklabels([''] + class_names) plt.xlabel('Predicted') plt.ylabel('True') plt.show() y = np.array(y) class_names = np.unique(y) confusion_matrices = [ ("Random Forest", confusion_matrix(y,RF_CV_result)), ("K-Nearest-Neighbors", confusion_matrix(y,KNN_CV_result)), ("Logisitic Regression", confusion_matrix(y,LR_CV_result)) ] # - # %matplotlib inline draw_confusion_matrices(confusion_matrices,class_names) # ### Step 4: Feature Selection # In this step, feature importance are calculated, and then be used to answer the second research question, which factors are the most influential on user decisions. I used both feature importance and recursive feature elimination (RFE) to select the most important features. # #### Step 4.1 - Compare Feature Importances forest = RandomForestClassifier() forest.fit(X, y) importances = forest.feature_importances_ print("Feature importance ranking by Random Forest Model:") for k,v in sorted(zip(map(lambda x: round(x, 4), importances), churn_feat_space.columns), reverse=True): print v + ": " + str(k) # From above results, we can see features total_day_minutes, total_day_charge, number_customer_service_calls, and intl_plan are the most influential on user decisions. # # #### Step 4.2 - Use Recursive Feature Elimination (RFE) # The goal of recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features and print out the most important ones. from sklearn.feature_selection import RFE LRmodel_l2 = LogisticRegression(penalty="l2") rfe_l2 = RFE(LRmodel_l2, n_features_to_select=1) rfe_l2.fit(X, y) print "Logistic Regression (L2) RFE Result" for k,v in sorted(zip(map(lambda x: round(x, 4), rfe_l2.ranking_), churn_feat_space.columns)): print v + ": " + str(k) # The results from RFE are similar to the above results from feature importances of Random Forest model. # ## Findings # * Past user behaviors can effectively predict future customer churn decision. # * Usage features related to calls (e.g. total_day_charge) has a larger effect on user decision compared to usage features related to text, voice mail, etc. # * The most influential features on user decisions are: total_day_minutes, total_day_charge, number_customer_service_calls, and intl_plan. # ## Discussion # Major limitations of the studies are the validity and size of the dataset. The Customer churn data is from a major machine learning database. The data files state that the data are "artificial based on claims similar to real world". Little is known on how the dataset is simulated/collected and processed. Based on the analysis in step 1, the dataset is in an aritifically good quality. There are few outliers and missing data. Variables follow near normal distributions. The quality of the dataset looks too good to be a reprensentive of real data. # # For the size of the dataset, there are 5000 observations in the main churn dataset. It is not a huge dataset. The size needs to be taken into consideration in avoid of overfitting or too complicated model. Additional dataset with more obervations and features would be needed for further analysis. # # Further studies include using a more representative and a large dataset. Also including timestamp so that time series analysis could be preformed. # ## Conclusion # We can use past user behaviros to predict if the user is going to continue using the service in the next month or not. # Top factors affecting users' decision to continue using the service or not are: total_day_minutes, total_day_charge, number_customer_service_calls, and intl_plan. # # This data analysis project is an exmple of human-centered data analysis on human produced data but without a direct contact with human. I try to consider and analyze human factors during the analysis process. It includes an emphasis on the interpretability of models and process instead of only focus on the model performance results. # ## References # [UW HCDS Class](https://wiki.communitydata.cc/HCDS_(Fall_2017) # # [Definition of Customer Churn](https://en.wikipedia.org/wiki/Customer_attrition) # # [A Meta-Analysis of Churn Studies](https://medium.com/the-saas-growth-blog/a-meta-analysis-of-churn-studies-4269b3c725f6) # # [9 Case Studies That’ll Help You Reduce SaaS Churn](https://conversionxl.com/blog/reduce-churn/) # # [The World's Largest Study on SaaS Churn](https://blog.profitwell.com/saas-churn-benchmarks-mrr-churn-study) # # [40 Customer Retention Statistics You Need to Know](https://www.getfeedback.com/blog/40-stats-churn-customer-satisfaction/)
User Churn Prediction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- def login(): email=driver.find_element_by_id('email') email.clear() sleep(1) email.send_keys('<EMAIL>') sleep(1) password=driver.find_element_by_id('pass') password.clear() sleep(1) password.send_keys('<PASSWORD>') sleep(1) # + from openpyxl import load_workbook from bs4 import BeautifulSoup from selenium import webdriver from time import sleep import csv from random import randint import json, io from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException from selenium.webdriver.common.action_chains import ActionChains import urllib import urllib3 import requests import json, io from bs4 import BeautifulSoup urllib3.disable_warnings() header = {'User-Agent':'Mozilla/6.0'} chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--user-agent="Mozilla/6.0') chrome_options.add_argument("user-data-dir=selenium") driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'chromedriver.exe') cookies = json.load(open('cookiesdict.txt')) for cookie in cookies: driver.add_cookie(cookie) # + ggg=[] for i in range(9): if i%2==1: ggg.append(i) # - datasaver1=[] # + driver.get('http://facebook.com') # login() # driver.find_element_by_id('loginbutton').click() search=driver.find_element_by_name('q') search.clear() search.send_keys('Meiragtx') sleep(1) # driver.find_element_by_css_selector('#js_0 > form > button').click() driver.find_elements_by_tag_name('button')[0].click() sleep(1) driver.find_element_by_link_text('Posts').click() sleep(1) driver.find_element_by_link_text('See All').click() sleep(2) for h in ggg: if driver.find_elements_by_class_name("_6-cm")[h].text != '': driver.find_elements_by_class_name("_6-cm")[h].click() sleep(2) datasaver0=[] so1=BeautifulSoup(driver.page_source, 'lxml') userContentWrapper=so1.find_all('div',class_="_5pcr userContentWrapper")[0] h5content=userContentWrapper.find_all('h5')[0] Name=h5content.text datasaver0.append(Name) print 'Name:',Name profile_link=h5content.find_all('a')[1].get('href') print 'profile_link:',profile_link datasaver0.append(profile_link) Post_time=userContentWrapper.find(class_="timestampContent").text print 'Post_time:',Post_time datasaver0.append(Post_time) pstxt=userContentWrapper.find_all('p') for q in range(len(pstxt)): print (pstxt[q].text) datasaver0.append(pstxt[q].text) if pstxt[q].find('a') is not None: if '/hashtag' not in pstxt[q].find('a').get('href'): print 'http://facebook.com'+pstxt[q].find('a').get('href') datasaver0.append('http://facebook.com'+pstxt[q].find('a').get('href')) rel_theater=userContentWrapper.find_all('a',rel="theater") for m in range(len(rel_theater)): print rel_theater[m].get('href') datasaver0.append(rel_theater) post_url=userContentWrapper.find_all(class_="_3n1k")[0].find('a').get('href') print post_url datasaver0.append(post_url) Total_Likes0=userContentWrapper.find_all(class_="_3dlg") if len(Total_Likes0)>0: Total_Likes=Total_Likes0[0].text print 'Total_Likes:' ,Total_Likes datasaver0.append(Total_Likes) Total_Comments0=userContentWrapper.find_all(class_="_1whp _4vn2") if len(Total_Comments0)>0: Total_Comments=Total_Comments0[0].text print 'Total_Comments:',Total_Comments datasaver0.append(Total_Comments) Total_shares0=userContentWrapper.find_all(class_="_355t _4vn2") if len(Total_shares0)>0: Total_shares=Total_shares0[0].text print 'Total_shares:',Total_shares datasaver0.append(Total_shares) driver.refresh() sleep(1) datasaver1.append(datasaver0) print '--------------------------------------------------' # -
facebook.com/facebook.com.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Probabilistic Programming # %matplotlib inline import os import matplotlib.pyplot as plt import numpy as np from scipy import stats import daft from IPython.display import Image import pystan import seaborn as sns import warnings warnings.simplefilter("ignore",category=FutureWarning) from scipy.optimize import minimize # ## Domain specific languages (DSL) # # A simplified computer language for working in a specific domain. Some examples of DSLs that you are already familiar with include # # - regular expressions for working with text # - SQL for working with relational databases # - LaTeX for typesetting documents # # Probabilistic programming languages are DSLs for dealing with models involving random variables and uncertainty. We will introduce the `Stan` probabilistic programming languages in this notebook. # ### Stan and PyStan references # # - [Paper describing Stan](http://www.stat.columbia.edu/~gelman/research/unpublished/stan-resubmit-JSS1293.pdf) # - [Stan documentation](http://mc-stan.org/users/documentation/index.html) # - [Stan examples](https://github.com/stan-dev/example-models/wiki) # - [PyStan docs](http://pystan.readthedocs.org/en/latest/) # - [PyStan GitHub page](https://github.com/stan-dev/pystan) # ### Other packages for probabilistic programming # # There several alternative packages for probabilistic programming in Python. You might like to explore them by recreating the PyStan examples shown in this notebooks using the following: # # - [PyMC3](https://github.com/pymc-devs/pymc3) # - [Edward](http://edwardlib.org) # - [ZhuSuan](https://github.com/thu-ml/zhusuan) # ## Examples # In general, the problem is set up like this: # # - We have some observed outcomes $y$ that we want to model # - The model is formulated as a probability distribution with some parameters $\theta$ to be estimated # - We want to estimate the posterior distribution of the model parameters given the data # $$ # P(\theta \mid y) = \frac{P(y \mid \theta) \, P(\theta)}{\int P(y \mid \theta^*) \, P(\theta^*) \, d\theta^*} # $$ # - For formulating a specification using probabilistic programming, it is often useful to think of how we would simulated a draw from the model # ### Coin bias # We toss a coin $n$ times, observed the number of times $y$ it comes up heads, and want to estimate the expected proportion of times $\theta$ that it comes up heads. An appropriate likelihood is the binomial, and it is convenient to use the $\beta$ distribution as the prior. In this case, the posterior is also a beta distribution, and there is a simple closed form formula: if the prior is $\beta(a, b)$ and we observe $y$ heads and $n-y$ tails in $n$ tosses, then the posterior is $\beta(a+y, a+(n-y)$. # #### Graphical model # + pgm = daft.PGM(shape=[2.5, 3.0], origin=[0, -0.5]) pgm.add_node(daft.Node("alpha", r"$\alpha$", 0.5, 2, fixed=True)) pgm.add_node(daft.Node("beta", r"$\beta$", 1.5, 2, fixed=True)) pgm.add_node(daft.Node("p", r"$p$", 1, 1)) pgm.add_node(daft.Node("n", r"$n$", 2, 0, fixed=True)) pgm.add_node(daft.Node("y", r"$y$", 1, 0, observed=True)) pgm.add_edge("alpha", "p") pgm.add_edge("beta", "p") pgm.add_edge("n", "y") pgm.add_edge("p", "y") pgm.render() plt.close() pgm.figure.savefig("bias.png", dpi=300) pass # - Image("bias.png", width=400) # #### Analytical solution # # Illustrating what $y$, $\theta$, posterior, likelihood, prior, MLE and MAP refer to. # + n = 100 h = 61 p = h/n rv = stats.binom(n, p) mu = rv.mean() a, b = 10, 10 prior = stats.beta(a, b) post = stats.beta(h+a, n-h+b) ci = post.interval(0.95) thetas = np.linspace(0, 1, 200) plt.plot(thetas, prior.pdf(thetas), label='Prior', c='blue') plt.plot(thetas, post.pdf(thetas), label='Posterior', c='red') plt.plot(thetas, n*stats.binom(n, thetas).pmf(h), label='Likelihood', c='green') plt.axvline((h+a-1)/(n+a+b-2), c='red', linestyle='dashed', alpha=0.4, label='MAP') plt.axvline(mu/n, c='green', linestyle='dashed', alpha=0.4, label='MLE') plt.xlabel(r'$\theta$', fontsize=14) plt.legend(loc='upper left') plt.show() pass # - # ## Using `stan` # ### Coin bias # #### Data data = { 'n': 100, 'y': 61, } # #### Model code = """ data { int<lower=0> n; // number of tosses int<lower=0> y; // number of heads } transformed data {} parameters { real<lower=0, upper=1> p; } transformed parameters {} model { p ~ beta(2, 2); y ~ binomial(n, p); } generated quantities {} """ # #### Compile the C++ model sm = pystan.StanModel(model_code=code) print(sm.model_cppcode) # #### MAP fit_map = sm.optimizing(data=data) fit_map.keys() fit_map.get('p') fit = sm.sampling(data=data, iter=1000, chains=4) # Summarizing the MCMC fit print(fit.stansummary()) # ### Interpreting `n_eff` and `Rhat` # #### Effective sample size # # $$ # \hat{n}_{eff} = \frac{mn}{1 + 2 \sum_{t=1}^T \hat{\rho}_t} # $$ # # where $m$ is the number of chains, $n$ the number of steps per chain, $T$ the time when the autocorrelation first becomes negative, and $\hat{\rho}_t$ the autocorrelation at lag $t$. # ##### Gelman-Rubin $\widehat{R}$ # # $$ # \widehat{R} = \frac{\widehat{V}}{W} # $$ # # where $W$ is the within-chain variance and $\widehat{V}$ is the posterior variance estimate for the pooled traces. Values greater than one indicate that one or more chains have not yet converged. # # Discrad burn-in steps for each chain. The idea is to see if the starting values of each chain come from the same distribution as the stationary state. # # - $W$ is the number of chains $m \times$ the variacne of each individual chain # - $B$ is the number of steps $n \times$ the variance of the chain means # - $\widehat{V}$ is the weigthed average $(1 - \frac{1}{n})W + \frac{1}{n}B$ # # The idea is that $\widehat{V}$ is an unbiased estimator of $W$ if the starting values of each chain come from the same distribution as the stationary state. Hence if $\widehat{R}$ differs significantly from 1, there is probably no convergence and we need more iterations. This is done for each parameter $\theta$. # #### $\widehat{R}$ is a measure of chain convergence ps = fit.extract(None, permuted=False) fit.model_pars ps.shape fig, axes = plt.subplots(2,2) for i, ax in enumerate(axes.ravel()): ax.plot(ps[:, i, 0]) ax.set_title('Chain %d' % (i+1)) plt.tight_layout() # #### Plotting fit.plot() pass # #### Extracting parameters params = fit.extract() p = params['p'] plt.subplot(121) plt.hist(p, 20, alpha=0.5) plt.subplot(122) plt.plot(p, alpha=0.5) pass # ### Coin toss as Bernoulli model # + # %%file bernoulli_model.stan data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { theta ~ beta(1,1); for (n in 1:N) y[n] ~ bernoulli(theta); } # - y = np.random.choice([0,1], 100, p=[0.6, 0.4]) data = { 'N': len(y), 'y': y } sm = pystan.StanModel('bernoulli_model.stan') fit = sm.sampling(data=data, iter=1000, chains=4) fit fit.plot() pass # #### MAP opt = sm.optimizing(data) opt # The MAP maximizes the log probability of the model. xi = np.linspace(0, 1, 100) plt.plot(xi, [fit.log_prob(np.log(x) - np.log(1-x)) for x in xi]) pass # Stan automatically transforms variables so as to work with unconstrained optimization. Knowing this, we can try to replicate the optimization procedure. p0 = 0.1 x0 = np.log(p0) - np.log(1 - p0) sol = minimize(fun=lambda x: -fit.log_prob(x), x0=x0) sol np.exp(sol.x)/(1 + np.exp(sol.x)) # ### Linear regression # # Another simple example of a probabilistic model is linear regression # # $$ # y = ax + b + \epsilon # $$ # # with $\epsilon \sim N(0, \sigma^2)$. # # We can think of the simulation model as sampling $y$ from the probability distribution # # $$ # y \sim N(ax + b, \sigma^2) # $$ # # and the parameter $\theta = (a, b, \sigma)$ is to be estimated (as posterior probability, MLE or MAP). To complete the model, we need to specify prior distributions for $a$, $b$ and $\sigma$. For example, if the observations $y$ are standardized to have zero mean and unit standard distribution, we can use # # $$ # a \sim N(0, 10) \\ # b \sim N(0, 10) \\ # \sigma \sim \vert{N(0, 1)} # $$ # # To get a more robust fit that is less sensitive to outliers, we can use a student-T distribution for $y$ # # $$ # y \sim t(ax + b, \sigma^2, \nu) # $$ # # with an extra parameter $\nu$ for the degrees of freedom for which we also need to specify a prior. # + # Instantiate the PGM. pgm = daft.PGM(shape=[4.0, 3.0], origin=[-0.3, -0.7]) # Hierarchical parameters. pgm.add_node(daft.Node("alpha", r"$\alpha$", 0.5, 2)) pgm.add_node(daft.Node("beta", r"$\beta$", 1.5, 2)) pgm.add_node(daft.Node("sigma", r"$\sigma$", 0, 0)) # Deterministic variable. pgm.add_node(daft.Node("mu", r"$\mu_n$", 1, 1)) # Data. pgm.add_node(daft.Node("x", r"$x_n$", 2, 1, observed=True)) pgm.add_node(daft.Node("y", r"$y_n$", 1, 0, observed=True)) # Add in the edges. pgm.add_edge("alpha", "mu") pgm.add_edge("beta", "mu") pgm.add_edge("x", "mu") pgm.add_edge("mu", "y") pgm.add_edge("sigma", "y") # And a plate. pgm.add_plate(daft.Plate([0.5, -0.5, 2, 2], label=r"$n = 1, \cdots, N$", shift=-0.1, rect_params={'color': 'white'})) # Render and save. pgm.render() plt.close() pgm.figure.savefig("lm.png", dpi=300) # - Image(filename="lm.png", width=400) # ### Linear model # + # %%file linear.stan data { int<lower=0> N; real x[N]; real y[N]; } parameters { real alpha; real beta; real<lower=0> sigma; // half-normal distribution } transformed parameters { real mu[N]; for (i in 1:N) { mu[i] = alpha + beta*x[i]; } } model { alpha ~ normal(0, 10); beta ~ normal(0, 1); sigma ~ normal(0, 1); y ~ normal(mu, sigma); } # + n = 11 _a = 6 _b = 2 x = np.linspace(0, 1, n) y = _a + _b*x + np.random.randn(n) data = { 'N': n, 'x': x, 'y': y } # - # #### Saving and reloading compiled models # # Since Stan models take a while to compile, we will define two convenience functions to save and load them. For example, this will allow reuse of the mode in a different session or notebook without recompilation. # + import pickle def save(filename, x): with open(filename, 'wb') as f: pickle.dump(x, f, protocol=pickle.HIGHEST_PROTOCOL) def load(filename): with open(filename, 'rb') as f: return pickle.load(f) # - model_name = 'linear' filename = '%s.pkl' % model_name if not os.path.exists(filename): sm = pystan.StanModel('%s.stan' % model_name) save(filename, sm) else: sm = load(filename) # We can inspect the original model from the loaded compiled version. print(sm.model_code) fit = sm.sampling(data) fit # #### Re-using the model on a new data set # + n = 121 _a = 2 _b = 1 x = np.linspace(0, 1, n) y = _a*x + _b + np.random.randn(n) data = { 'N': n, 'x': x, 'y': y } # - fit2 = sm.sampling(data) print(fit2.stansummary(pars=['alpha', 'beta', 'sigma'])) # ### Hierarchical models # Gelman's book has an example where the dose of a drug may be affected to the number of rat deaths in an experiment. # # | Dose (log g/ml) | # Rats | # Deaths | # |-----------------|--------|----------| # | -0.896 | 5 | 0 | # | -0.296 | 5 | 1 | # | -0.053 | 5 | 3 | # | 0.727 | 5 | 5 | # # We will model the number of deaths as a random sample from a binomial distribution, where $n$ is the number of rats and $p$ the probability of a rat dying. We are given $n = 5$, but we believe that $p$ may be related to the drug dose $x$. As $x$ increases the number of rats dying seems to increase, and since $p$ is a probability, we use the following model: # # $$ # y \sim \text{Bin}(n, p) \\ # \text{logit}(p) = \alpha + \beta x \\ # \alpha \sim \mathcal{N}(0, 5) \\ # \beta \sim \mathcal{N}(0, 10) # $$ # # where we set vague priors for $\alpha$ and $\beta$, the parameters for the logistic model. # **Exercise**: Create the plate diagram for this model using `daft`. # ### Hierarchical model in Stan data = dict( N = 4, x = [-0.896, -0.296, -0.053, 0.727], y = [0, 1, 3, 5], n = [5, 5, 5, 5], ) # + # %%file dose.stan data { int<lower=0> N; int<lower=0> n[N]; real x[N]; int<lower=0> y[N]; } parameters { real alpha; real beta; } transformed parameters { real <lower=0, upper=1> p[N]; for (i in 1:N) { p[i] = inv_logit(alpha + beta*x[i]); } } model { alpha ~ normal(0, 5); beta ~ normal(0, 10); for (i in 1:N) { y ~ binomial(n, p); } } # - model_name = 'dose' filename = '%s.pkl' % model_name if not os.path.exists(filename): sm = pystan.StanModel('%s.stan' % model_name) save(filename, sm) else: sm = load(filename) fit = sm.sampling(data=data) fit alpha, beta, *probs = fit.get_posterior_mean() a = alpha.mean() b = beta.mean() # #### Logistic function # # $$ # f(x) = \frac{e^z}{1 + e^z} # $$ def logistic(a, b, x): """Logistic function.""" return np.exp(a + b*x)/(1 + np.exp(a + b*x)) xi = np.linspace(min(data['x']), max(data['x']), 100) plt.plot(xi, logistic(a, b, xi)) plt.scatter(data['x'], [y_/n_ for (y_, n_) in zip(data['y'], data['n'])], c='red') pass # #### Sampling from prior # + # %%file dose_prior.stan data { int<lower=0> N; int<lower=0> n[N]; real x[N]; } parameters { real alpha; real beta; } transformed parameters { real <lower=0, upper=1> p[N]; for (i in 1:N) { p[i] = inv_logit(alpha + beta*x[i]); } } model { alpha ~ normal(0, 5); beta ~ normal(0, 10); } # - sm = pystan.StanModel('dose_prior.stan') fit_prior = sm.sampling(data=data) alpha, beta, *probs, lp = fit_prior.get_posterior_mean() a = alpha.mean() b = beta.mean() p = [prob.mean() for prob in probs] p y = np.random.binomial(5, p) y xi = np.linspace(min(data['x']), max(data['x']), 100) plt.plot(xi, logistic(a, b, xi)) plt.scatter(data['x'], [y_/n_ for (y_, n_) in zip(y, data['n'])], c='red') pass # #### Sampling from posterior # + # %%file dose_post.stan data { int<lower=0> N; int<lower=0> n[N]; real x[N]; int<lower=0> y[N]; } parameters { real alpha; real beta; } transformed parameters { real <lower=0, upper=1> p[N]; for (i in 1:N) { p[i] = inv_logit(alpha + beta*x[i]); } } model { alpha ~ normal(0, 5); beta ~ normal(0, 10); for (i in 1:N) { y ~ binomial(n, p); } } generated quantities { int<lower=0> yp[N]; for (i in 1:N) { yp[i] = binomial_rng(n[i], p[i]); } } # - sm = pystan.StanModel('dose_post.stan') fit_post = sm.sampling(data=data) yp = fit_post.extract('yp')['yp'] yp.shape np.c_[data['x'], yp.T[:, :6]]
notebooks/S11_Probabilistic_Programming.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/tonychang04/Sarcastic-Headlines-Detector/blob/main/Logistic_Regression.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="__F_gTpfA-pJ" # ## Logistic Regression Model # ## Accuracy: 86% # + colab={"base_uri": "https://localhost:8080/"} id="GnLJJVx16DeK" outputId="a9a84bed-1086-4143-dd64-978af48b17b4" from google.colab import files from google.colab import drive import pandas as pd import numpy as np import matplotlib.pyplot as plt import string import nltk from nltk.corpus import stopwords from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix #drive.mount('/content/drive') nltk.download('stopwords') # + colab={"base_uri": "https://localhost:8080/", "height": 362} id="K4pabrEP-bdx" outputId="42470bcf-6789-4a08-b8ed-a63858921ffc" #/content/Sarcasm_Headlines_Dataset.json df1 = pd.read_json('/Sarcasm_Headlines_Dataset.json', lines = True) df2 = pd.read_json('/Sarcasm_Headlines_Dataset_v2.json', lines = True) frames = [df1, df2] df = pd.concat(frames) # merged two json files into 1 dataframe file df.head(10) # + colab={"base_uri": "https://localhost:8080/", "height": 312} id="j2QretvdJgid" outputId="a6a8f7dd-47a3-45a2-cbcd-7aa73273cb3f" # Some data visualizations... ones = len(df[df['is_sarcastic'] == 1]) zeros = len(df[df['is_sarcastic'] == 0]) output = ['0','1'] plt.bar(output[0], [zeros]) plt.bar(output[1], [ones]) plt.legend(output) plt.xlabel('Sarcastic(1) or Not Sarcastic(0)') plt.ylabel('Number of Headlines') plt.title('Number of Sarcastic/Non-Sarcastic headlines') # + colab={"base_uri": "https://localhost:8080/"} id="Cf84Yd-HHoSB" outputId="97ecb977-86b2-43aa-9295-ef27023fa331" print(stopwords.words('english')) # + id="6SVsBHC0apE1" # some other visualizations... (average length of the headlines - sarcastic && nonsarcastic) # takes a while to get the valuse, just use the numbers below to make the graph def find_average_length(df, len_sar, len_non_sar): for i in range(len(df)): if int(df[['is_sarcastic']].iloc[i]) == 0: len_non_sar += int(df[['headline']].iloc[i].str.len()) else: len_sar += int(df[['headline']].iloc[i].str.len()) sarcastic = len_sar / ones non_sarcastic = len_non_sar / zeros return sarcastic, non_sarcastic sarcastic, non_sarcastic = find_average_length(df, 0, 0) #sarcastic = 64.08620553671425 #non_sarcastic = 59.55862529195863 # + id="lJ9enYPgXs8O" # run it as needed sarcastic = 64.08620553671425 non_sarcastic = 59.55862529195863 # + colab={"base_uri": "https://localhost:8080/", "height": 312} id="YIwrde6QcLzb" outputId="075fc1ea-8a07-426c-fd77-08f093d23156" fig = plt.figure() ax = fig.add_subplot(111) labels = ['sarcastic','non-sarcastic'] values = [sarcastic, non_sarcastic] plt.bar(labels[0], values[0], color=(0.2, 0.4, 0.6, 0.6)) plt.bar(labels[1], values[1], color=(0.3, 0.8, 0.7, 0.6)) for i, v in enumerate(values): ax.text(i, v+1, "%d" %v, ha="center") plt.ylim(0, 75) plt.legend(labels) plt.xlabel('Sarcastic or Non-sarcastic') plt.ylabel('Average number of characters') plt.title('Average length of the headlines') # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="QcIvy1AXBZWg" outputId="13691fcd-a9c0-48d5-c12a-d269a02cbaae" # Removing Stop words def text_process_for_ML(mess): nopunc = [char for char in mess if char not in string.punctuation] nopunc = ''.join(nopunc) #print(nopunc) #print(no_stop_words) return [word for word in nopunc.split() if word.lower() not in stopwords.words('english')] def text_process(mess): nopunc = [char for char in mess if char not in string.punctuation] nopunc = ''.join(nopunc) #print(nopunc) no_stop_words = [word for word in nopunc.split() if word.lower() not in stopwords.words('english')] #print(no_stop_words) return ' '.join(no_stop_words) df['processed_headline'] = df['headline'].apply(text_process) df.head() # + id="K11j1qQpT52k" colab={"base_uri": "https://localhost:8080/"} outputId="c788d4e7-3c7b-4193-ea39-7eb980998047" #logistic regression model # https://www.kaggle.com/mrudhuhas/text-classification-spacy/execution from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline X_train_2, X_test_2, Y_train_2, Y_test_2 = train_test_split(df['processed_headline'], df['is_sarcastic'], test_size=0.33, random_state=42) #train the model classifier_lr = Pipeline([('tfidf',TfidfVectorizer()), ('clf',LogisticRegression(solver='saga'))]) classifier_lr.fit(X_train_2,Y_train_2) # + colab={"base_uri": "https://localhost:8080/"} id="y_qy-CsaHSEK" outputId="9732595e-7a65-4620-aa87-96d0650199c7" #Predicting y_pred = classifier_lr.predict(X_test_2) yt_pred = classifier_lr.predict(X_train_2) #Analyzing from sklearn.metrics import accuracy_score cm = confusion_matrix(Y_test_2,y_pred) print(f'Confusion Matrix :\n {cm}\n') print(f'Test Set Accuracy Score :\n {accuracy_score(Y_test_2,y_pred)}\n') print(f'Train Set Accuracy Score :\n {accuracy_score(Y_train_2,yt_pred)}\n') print(f'Classification Report :\n {classification_report(Y_test_2,y_pred)}')
Logistic_Regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Groupby # # The groupby method allows you to group rows of data together based on a column e.g ID and call aggregate functions on the row values e.g sum, average e.t.c import pandas as pd # Create dataframe from a key:value pair store 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, index=['R1','R2','R3','R4','R5','R6']) df.index.name = 'Index' df # ** Now you can use the .groupby() method to group rows together based off of a column name. For instance let's group based off of Company. This will create a DataFrameGroupBy object:** grp_by_co = df.groupby("Company") grp_by_co # And then call aggregate methods off the object: grp_by_co.mean() # Pandas will ignore non-numeric columns when attempting to use numeric aggregation functions. Returns a df of companies with thieir mean sales. df.groupby('Company').mean() # The short method # More examples of aggregate methods: df.groupby('Company').std() df.groupby('Company').std().loc['FB'] # The result is always a DataFrame so the df methods can also be used on the result. Retrieves a row in the df where the row value = 'FB' df.groupby('Company').min() # min() will work on both alphanumeric cols, returning the min sales values for each co and also the person whose name is lowest placed alphabetically in ascending order. # Letters have numeric unicode representation that Python uses to compare letters 'a' > 'b' 'a' < 'b' 'a' == 'A' ord('a') ord('b') ord('A') df df.groupby('Company').max() grp_by_co.count() # Returns the company data values frequency in each col. grp_by_co.describe() # Returns useful statisitcs about a DataFrame desc_data = grp_by_co.describe().transpose() desc_data desc_data['GOOG'] # Fetch on a column from above df desc_data.transpose() # Fetch on a row basis desc_data.loc['GOOG'] # # Great Job!
Python/data_science/data_analysis/03-Python-for-Data-Analysis-Pandas/05-Groupby.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd import matplotlib.pyplot as plt #data1=pd.read_csv('bs140513_032310.csv') data1=pd.read_csv('D:\\DataScienceCompetitions\\AI4Hackathon\\synthetic-data-from-a-financial-payment-system\\bs140513_032310.csv') data1.head() #zipcodeOri and zipMerchant doesn't have any predictive power, zero variance(unique value) data1=data1.drop(columns=['zipcodeOri', 'zipMerchant','customer','merchant']) data1.shape data1.head() X=data1.iloc[:,:-1].values y=data1.iloc[:, 5].values from sklearn.preprocessing import LabelEncoder, OneHotEncoder # + labelencoder_X1=LabelEncoder() X[:,1]=labelencoder_X1.fit_transform(X[:,1]) labelencoder_X2=LabelEncoder() X[:,2]=labelencoder_X2.fit_transform(X[:,2]) labelencoder_X3=LabelEncoder() X[:,3]=labelencoder_X3.fit_transform(X[:,3]) # - # Encoding categorical data onehotencoder = OneHotEncoder(categorical_features=[1,2,3]) X = onehotencoder.fit_transform(X).toarray() from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test= train_test_split(X, y, test_size=0.2, random_state=0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # # DecisionTree from sklearn.tree import DecisionTreeClassifier classifier_DT=DecisionTreeClassifier(criterion='entropy', random_state=0) classifier_DT.fit(X_train, y_train) y_pred=classifier_DT.predict(X_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred)) # # Random Forest from sklearn.ensemble import RandomForestClassifier classifier_RF=RandomForestClassifier(n_estimators=100, criterion='entropy', random_state=0) classifier_RF.fit(X_train, y_train) y_pred=classifier_RF.predict(X_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred)) # # SVM(Kernal=Poly) from sklearn.svm import SVC classifier_pl=SVC(kernel='poly', random_state=0) classifier_pl.fit(X_train, y_train) y_pred=classifier_pl.predict(X_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred)) # # ANN import keras from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout classifier = Sequential() len(X_train[1]) # + classifier.add(Dense(units = 16, kernel_initializer = 'uniform', activation = 'relu', input_dim = 29)) #classifier.add(Dropout(p = 0.2)) classifier.add(Dense(units = 32, kernel_initializer = 'uniform', activation = 'relu')) #classifier.add(Dropout(p = 0.2)) classifier.add(Dense(units = 32, kernel_initializer = 'uniform', activation = 'relu')) #classifier.add(Dropout(p = 0.2)) classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # - classifier.summary() classifier.fit(X_train, y_train, batch_size = 100, epochs = 30) y_pred=classifier.predict(X_test) y_pred=[np.round(x[0]) for x in y_pred] from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred)) # # XGBoost from xgboost import XGBClassifier classifier_xg = XGBClassifier() classifier_xg.fit(X_train, y_train) y_pred=classifier_xg.predict(X_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred)) # # Cross Validation from sklearn.model_selection import cross_val_score accuracies = cross_val_score(estimator = classifier_xg, X=X_train, y=y_train, cv =10) accuracies.mean() accuracies # # SVM Kernal=Linear from sklearn.svm import SVC classifier=SVC(kernel='linear', random_state=0) classifier.fit(X_train, y_train) y_pred=classifier.predict(X_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred)) # # Logistic Regression from sklearn.linear_model import LogisticRegression classifier_lr=LogisticRegression(random_state=0) classifier_lr.fit(X_train, y_train) y_pred=classifier_lr.predict(X_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred)) # # KNN Classifier from sklearn.neighbors import KNeighborsClassifier classifier_knn=KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2) classifier_knn.fit(X_train, y_train) y_pred=classifier_knn.predict(X_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred)) # # Naive Bayes from sklearn.naive_bayes import GaussianNB classifier_NB = GaussianNB() classifier_NB.fit(X_train, y_train) y_pred=classifier_NB.predict(X_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, y_pred) cm from sklearn.metrics import roc_auc_score roc_auc_score(y_test, y_pred) from sklearn.metrics import classification_report print(classification_report(y_test,y_pred))
Models/Model_Building_Part4.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Introduction to ZSE and Useing Zeolite Frameworks # Here I will show you how to call any zeolite framework in as an ASE atoms object, and some of the basic operations ZSE can perform. # ## zse.collections # Every zeolite framework listed on the [IZA Database](https://asia.iza-structure.org/IZA-SC/ftc_table.php) as of January of 2020 is included in ZSE. \ # You don't have to use the structure files provided by ZSE, you can use your own as well. from zse.collections import * from ase.visualize import view # ## collections.framework( ) # # The framework command calls zeolite structure files from an included database. \ # Just input the IZA framework code of the zeolite you want to use. z = framework('CHA') view(z) # <img src="figures/cha.png" style="width: 400px;"/> # ## collections.get_all_fws( ) # This command will return a list of every framework included in ZSE. \ # This is handy if you wanted to iterate through all the frameworks. # get list of all codes fws = get_all_fws() # iterate over list for some actions # in this case, I'll create a trajectory of every structure file traj = [framework(x) for x in fws] view(traj) # ## collections.get_ring_sizes( ) # This command will get the list of the ring sizes included in a particular framework. \ # Many other functions in ZSE rely on this information. # the CHA framework contains 8-, 6-, and 4-membered rings (MR) ring_sizes = get_ring_sizes('CHA') print(ring_sizes) # ## zse.utilities # These are some basic utilities to get information about a framework. \ # Other functions in ZSE rely on on these utilities. from zse.utilities import * # ## utilities.get_tsites( ) # This will provide the unique T-sites, their multiplicity, and an atom index for an example in your framework. # + z = framework('TON') tsites, tmults, tinds = get_tsites('TON') # print the information print('T-site \t Multiplicity \t Index') for ts,tm,ti in zip(tsites,tmults,tinds): print('{0} \t {1} \t\t {2}'.format(ts,tm,ti)) # - # ## utilities.get_osites( ) # Same as above, but will get the information for each unique oxygen site. # + z = framework('TON') osites, omults, oinds = get_osites('TON') # print the information print('O-site \t Multiplicity \t Index') for os,om,oi in zip(osites,omults,oinds): print('{0} \t {1} \t\t {2}'.format(os,om,oi)) # - # ## utilities.site_labels( ) # This function will get all the site labels as a dictionary for you entire atoms object. \ # The dictionary key:value pairs are index:site_label. \ # This will work for atoms objects provided by ZSE, or if you have your own zeolite atoms object as well. # ### Inputs # **z** is the atoms object you want labels for \ # **'TON'** is the IZA framework code for the zeolite you are using # + z = framework('TON') labels = site_labels(z,'TON') # let's make sure we get results that match the last two functions # this should be a T1 print('atom index 48: ',labels[48]) # this should be an O4 print('atom index 24: ',labels[24]) # -
examples/01_introduction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- #Imports # %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn # + from sklearn.datasets import make_blobs X, y = make_blobs(n_samples=500, centers=4, random_state=8, cluster_std=2.4) #Scatter plot the points plt.figure(figsize=(10,10)) plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='jet') # - from sklearn.tree import DecisionTreeClassifier def visualize_tree(classifier, X, y, boundaries=True,xlim=None, ylim=None): ''' Visualizes a Decision Tree. INPUTS: Classifier Model, X, y, optional x/y limits. OUTPUTS: Meshgrid visualization for boundaries of the Decision Tree ''' # Fit the X and y data to the tree classifier.fit(X, y) # Automatically set the x and y limits to the data (+/- 0.1) if xlim is None: xlim = (X[:, 0].min() - 0.1, X[:, 0].max() + 0.1) if ylim is None: ylim = (X[:, 1].min() - 0.1, X[:, 1].max() + 0.1) # Assign the variables x_min, x_max = xlim y_min, y_max = ylim # Create a mesh grid xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) # Define the Z by the predictions (this will color in the mesh grid) Z = classifier.predict(np.c_[xx.ravel(), yy.ravel()]) # Reshape based on meshgrid Z = Z.reshape(xx.shape) # Plot the figure (use) plt.figure(figsize=(10,10)) plt.pcolormesh(xx, yy, Z, alpha=0.2, cmap='jet') # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='jet') #Set Limits plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) def plot_boundaries(i, xlim, ylim): ''' Plots the Decision Boundaries ''' if i < 0: return # Shorter variable name tree = classifier.tree_ # Recursively go through nodes of tree to plot boundaries. if tree.feature[i] == 0: plt.plot([tree.threshold[i], tree.threshold[i]], ylim, '-k') plot_boundaries(tree.children_left[i], [xlim[0], tree.threshold[i]], ylim) plot_boundaries(tree.children_right[i], [tree.threshold[i], xlim[1]], ylim) elif tree.feature[i] == 1: plt.plot(xlim, [tree.threshold[i], tree.threshold[i]], '-k') plot_boundaries(tree.children_left[i], xlim, [ylim[0], tree.threshold[i]]) plot_boundaries(tree.children_right[i], xlim, [tree.threshold[i], ylim[1]]) # Random Forest vs Single Tree if boundaries: plot_boundaries(0, plt.xlim(), plt.ylim()) # + # Set model variable clf = DecisionTreeClassifier(max_depth=2,random_state=0) # Show Boundaries visualize_tree(clf,X,y) # + # Set model variable clf = DecisionTreeClassifier(max_depth=4,random_state=0) # Show Boundaries visualize_tree(clf,X,y) # + from sklearn.ensemble import RandomForestClassifier # n_estimators clf = RandomForestClassifier(n_estimators=100,random_state=0) # Get rid of boundaries to avoid error visualize_tree(clf,X,y,boundaries=False) # + from sklearn.ensemble import RandomForestRegressor x = 10 * np.random.rand(100) def sin_model(x, sigma=0.2): ''' Generate random sinusoidal data for regression analysis. Does SciKit-Learn have this? ''' noise = sigma * np.random.randn(len(x)) return np.sin(5 * x) + np.sin(0.5 * x) + noise # Call y for data with x y = sin_model(x) # Plot x vs y plt.figure(figsize=(16,8)) plt.errorbar(x, y, 0.1, fmt='o') # + # X points xfit = np.linspace(0, 10, 1000) # Model rfr = RandomForestRegressor(100) # Fit Model (Format array for y with [:,None]) rfr.fit(x[:, None], y) # Set predicted points yfit = rfr.predict(xfit[:, None]) # Set real poitns (the model function) ytrue = sin_model(xfit, 0) # Plot plt.figure(figsize=(16,8)) plt.errorbar(x, y, 0.1, fmt='o') plt.plot(xfit, yfit, '-r'); plt.plot(xfit, ytrue, '-k', alpha=0.5); # -
Decision Tree Random Forest.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/taniokah/DL-Basic-Seminar/blob/master/Yolov3_Test_for_Movies2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="GqaefNaLujDY" colab_type="code" outputId="7d83093f-c105-4379-d51f-bd0c6dd43399" colab={"base_uri": "https://localhost:8080/", "height": 34} # %matplotlib inline import cv2 # opencvのインポート import matplotlib.pyplot as plt # matplotlib(描画用) print(cv2.__version__) # + id="UUr7SazXunDI" colab_type="code" outputId="909c8565-f273-4d9e-9f86-adeec4d272b4" colab={"base_uri": "https://localhost:8080/", "height": 275} # #!pip install pytube # !pip install youtube-dl # !pip install ffmpeg # + id="A4Fm4KvWupG4" colab_type="code" colab={} # !rm -rf screen_caps # !mkdir screen_caps # + id="eMT0Jvz5ut-X" colab_type="code" colab={} # https://knooto.info/youtube-dl/#%E5%88%A9%E7%94%A8%E5%8F%AF%E8%83%BD%E3%81%AA%E5%BD%A2%E5%BC%8F%E3%81%AE%E4%B8%80%E8%A6%A7%E3%82%92%E5%87%BA%E5%8A%9B%E3%81%99%E3%82%8B # !youtube-dl https://youtu.be/l00CwQ6HI_o -F # + id="PQ7qt9CyyzbF" colab_type="code" outputId="0207f190-e0fb-4c45-94f8-413d3d917148" colab={"base_uri": "https://localhost:8080/", "height": 85} # !youtube-dl https://youtu.be/l00CwQ6HI_o -f 313 # + id="ykq3CVcezGNa" colab_type="code" colab={} import sys import cv2 import numpy as np #動画ファイルを読み込む #file_name = u"20190217 徳島大学医学部 vs 吉野クラブ 2nd No2.mp4" #file_name = u"20190224 鹿屋体育大学 vs 鹿児島高専 1st.mp4" file_name = u"/content/20190224 鹿屋体育大学 vs 鹿児島高専 1st.webm" cap = cv2.VideoCapture(file_name) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) print(str(width) + ', ' + str(height)) fps = cap.get(cv2.CAP_PROP_FPS) #(width, height) = (1280, 720) print(str(width) + ', ' + str(height)) fourcc = cv2.VideoWriter_fourcc(*'MP4V') writer = cv2.VideoWriter('T20190224_1st.mp4', fourcc, fps, (width, height), True) frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) print('frame_count = ' + str(frame_count)) frame_rate = int(cap.get(cv2.CAP_PROP_FPS)) print('frame_rate = ' + str(frame_rate)) #while True: for i in range(frame_count): #_, frame = cap.read() ret, frame = cap.read() if not ret: break pts1 = np.float32([[1110, 486], [2700, 486], [-90, 1080], [3870, 1080]]) pts2 = np.float32([[0, 0], [width, 0], [0, height], [width, height]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) result = cv2.warpPerspective(frame, matrix, (width, height)) #cv2.circle(frame, (1110, 486), 5, (0, 0, 255), -1) #cv2.circle(frame, (2700, 486), 5, (0, 255, 0), -1) #cv2.circle(frame, (-90, 1080), 5, (255, 0, 0), -1) #cv2.circle(frame, (3870, 1080), 5, (0, 255, 255), -1) #cv2.imshow("Frame", frame) #cv2.imshow("Perspective transformation", result) writer.write(result) key = cv2.waitKey(1) if key == 27: break sys.stdout.write("\r%d" % i) sys.stdout.flush() cv2.destroyAllWindows() writer.release() cap.release() print('done') # + id="qHUrEH9R39kF" colab_type="code" outputId="ff0c25dc-b360-48b8-a207-a454096c3ad4" colab={"base_uri": "https://localhost:8080/", "height": 479} # !pip install numpy # !pip install yolov3 # + id="CNRhKNfu390y" colab_type="code" outputId="756395cb-29bd-4208-ce7f-a74242521029" colab={"base_uri": "https://localhost:8080/", "height": 102} # !git clone https://github.com/qqwweee/keras-yolo3.git # + id="330Mpm3R4AHZ" colab_type="code" outputId="8f093e74-71ed-414b-aaa1-d6bd0b5ad508" colab={"base_uri": "https://localhost:8080/", "height": 1000} # %cd keras-yolo3 # !wget https://pjreddie.com/media/files/yolov3.weights # !python convert.py yolov3.cfg yolov3.weights model_data/yolo.h5 # + id="rzUAkyyPy0Z-" colab_type="code" outputId="8e198751-1c23-45f0-990b-0003ed2d7736" colab={"base_uri": "https://localhost:8080/", "height": 97} # -*- coding: utf-8 -*- """ Class definition of YOLO_v3 style detection model on image and video """ import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" import colorsys import os from timeit import default_timer as timer import numpy as np from keras import backend as K from keras.models import load_model from keras.layers import Input from PIL import Image, ImageFont, ImageDraw from yolo3.model import yolo_eval, yolo_body, tiny_yolo_body from yolo3.utils import letterbox_image import os from keras.utils import multi_gpu_model class YOLO(object): _defaults = { "model_path": 'model_data/yolo.h5', "anchors_path": 'model_data/yolo_anchors.txt', "classes_path": 'model_data/coco_classes.txt', "score" : 0.3, "iou" : 0.45, "model_image_size" : (416, 416), "gpu_num" : 1, } @classmethod def get_defaults(cls, n): if n in cls._defaults: return cls._defaults[n] else: return "Unrecognized attribute name '" + n + "'" def __init__(self, **kwargs): self.__dict__.update(self._defaults) # set up default values self.__dict__.update(kwargs) # and update with user overrides self.class_names = self._get_class() self.anchors = self._get_anchors() self.sess = K.get_session() self.boxes, self.scores, self.classes = self.generate() def _get_class(self): classes_path = os.path.expanduser(self.classes_path) with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def _get_anchors(self): anchors_path = os.path.expanduser(self.anchors_path) with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2) def generate(self): model_path = os.path.expanduser(self.model_path) assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.' # Load model, or construct model and load weights. num_anchors = len(self.anchors) num_classes = len(self.class_names) is_tiny_version = num_anchors==6 # default setting try: self.yolo_model = load_model(model_path, compile=False) except: self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) \ if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes) self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match else: assert self.yolo_model.layers[-1].output_shape[-1] == \ num_anchors/len(self.yolo_model.output) * (num_classes + 5), \ 'Mismatch between model and given anchor and class sizes' print('{} model, anchors, and classes loaded.'.format(model_path)) # Generate colors for drawing bounding boxes. hsv_tuples = [(x / len(self.class_names), 1., 1.) for x in range(len(self.class_names))] self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) self.colors = list( map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors)) np.random.seed(10101) # Fixed seed for consistent colors across runs. np.random.shuffle(self.colors) # Shuffle colors to decorrelate adjacent classes. np.random.seed(None) # Reset seed to default. # Generate output tensor targets for filtered bounding boxes. self.input_image_shape = K.placeholder(shape=(2, )) if self.gpu_num>=2: self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num) boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors, len(self.class_names), self.input_image_shape, score_threshold=self.score, iou_threshold=self.iou) return boxes, scores, classes def detect_image(self, image, isDetect = True): start = timer() if self.model_image_size != (None, None): assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required' assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required' boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size))) else: new_image_size = (image.width - (image.width % 32), image.height - (image.height % 32)) boxed_image = letterbox_image(image, new_image_size) image_data = np.array(boxed_image, dtype='float32') #print(image_data.shape) image_data /= 255. image_data = np.expand_dims(image_data, 0) # Add batch dimension. if isDetect == True: out_boxes, out_scores, out_classes = self.sess.run( [self.boxes, self.scores, self.classes], feed_dict={ self.yolo_model.input: image_data, self.input_image_shape: [image.size[1], image.size[0]], K.learning_phase(): 0 }) self.cache_boxes = out_boxes self.cache_scores = out_scores self.cache_classes = out_classes else: out_boxes = self.cache_boxes out_scores = self.cache_scores out_classes = self.cache_classes if isDetect == True: print('Found {} boxes for {}'.format(len(out_boxes), 'img')) font = ImageFont.truetype(font='font/FiraMono-Medium.otf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32')) thickness = (image.size[0] + image.size[1]) // 300 for i, c in reversed(list(enumerate(out_classes))): predicted_class = self.class_names[c] box = out_boxes[i] score = out_scores[i] label = '{} {:.2f}'.format(predicted_class, score) draw = ImageDraw.Draw(image) label_size = draw.textsize(label, font) top, left, bottom, right = box top = max(0, np.floor(top + 0.5).astype('int32')) left = max(0, np.floor(left + 0.5).astype('int32')) bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32')) right = min(image.size[0], np.floor(right + 0.5).astype('int32')) if isDetect == True: print(label, (left, top), (right, bottom)) if top - label_size[1] >= 0: text_origin = np.array([left, top - label_size[1]]) else: text_origin = np.array([left, top + 1]) # My kingdom for a good redistributable image drawing library. for i in range(thickness): draw.rectangle( [left + i, top + i, right - i, bottom - i], outline=self.colors[c]) draw.rectangle( [tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c]) draw.text(text_origin, label, fill=(0, 0, 0), font=font) del draw end = timer() if isDetect == True: print(end - start) return image def close_session(self): self.sess.close() def detect_video(yolo, video_path, output_path="", skip=1): import cv2 vid = cv2.VideoCapture(video_path) if not vid.isOpened(): raise IOError("Couldn't open webcam or video") #video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC)) video_FourCC = cv2.VideoWriter_fourcc(*"mp4v") video_frame = vid.get(cv2.CAP_PROP_FRAME_COUNT) video_fps = vid.get(cv2.CAP_PROP_FPS) video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)), int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))) isOutput = True if output_path != "" else False if isOutput: print("!!! TYPE:", type(output_path), type(video_FourCC), type(video_fps), type(video_size)) print(output_path) out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size) accum_time = 0 curr_fps = 0 fps = "FPS: ??" prev_time = timer() count = 0 #while True: while count < int(video_frame): return_value, frame = vid.read() image = Image.fromarray(frame) if count % skip == 0: image = yolo.detect_image(image, True) print('(' + str(count) + '/' + str(int(video_frame)) + ')') else: image = yolo.detect_image(image, False) result = np.asarray(image) curr_time = timer() exec_time = curr_time - prev_time prev_time = curr_time accum_time = accum_time + exec_time curr_fps = curr_fps + 1 if accum_time > 1: accum_time = accum_time - 1 fps = "FPS: " + str(curr_fps) curr_fps = 0 cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.50, color=(255, 0, 0), thickness=2) #cv2.namedWindow("result", cv2.WINDOW_NORMAL) #cv2.imshow("result", result) if isOutput: out.write(result) count += 1 if cv2.waitKey(1) & 0xFF == ord('q'): break if isOutput: out.release() vid.release yolo.close_session() # + id="5DS8KCwby-AZ" colab_type="code" outputId="9a3a1004-30f1-475d-834a-dc53d3bf5445" colab={"base_uri": "https://localhost:8080/", "height": 252} # yolo_video.py import sys import argparse from yolo import YOLO, detect_video from PIL import Image import matplotlib.pyplot as plt def detect_img(yolo): while True: img = input('Input image filename:') try: image = Image.open(img) plt.show() except: print('Open Error! Try again!') continue else: r_image = yolo.detect_image(image) r_image.save(img + '_yolo.jpg') yolo.close_session() FLAGS = None if __name__ == '__main__': # class YOLO defines the default value, so suppress any default here parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) ''' Command line options ''' parser.add_argument( '--model', type=str, help='path to model weight file, default ' + YOLO.get_defaults("model_path") ) parser.add_argument( '--anchors', type=str, help='path to anchor definitions, default ' + YOLO.get_defaults("anchors_path") ) parser.add_argument( '--classes', type=str, help='path to class definitions, default ' + YOLO.get_defaults("classes_path") ) parser.add_argument( '--gpu_num', type=int, help='Number of GPU to use, default ' + str(YOLO.get_defaults("gpu_num")) ) parser.add_argument( '--image', default=False, action="store_true", help='Image detection mode, will ignore all positional arguments' ) ''' Command line positional arguments -- for video detection mode ''' parser.add_argument( "--input", nargs='?', type=str,required=False,default='./path2your_video', help = "Video input path" ) parser.add_argument( "--output", nargs='?', type=str, default="", help = "[Optional] Video output path" ) parser.add_argument( "--skip", nargs='?', type=int, default=1, help = "[Optional] Video detect skip steps" ) FLAGS = parser.parse_args() if FLAGS.image: """ Image detection mode, disregard any remaining command line arguments """ print("Image detection mode") if "input" in FLAGS: print(" Ignoring remaining command line arguments: " + FLAGS.input + "," + FLAGS.output) detect_img(YOLO(**vars(FLAGS))) elif "input" in FLAGS: detect_video(YOLO(**vars(FLAGS)), FLAGS.input, FLAGS.output, FLAGS.skip) else: print("Must specify at least video_input_path. See usage with --help.") # + id="RLHJWZxo5Crh" colab_type="code" colab={} import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" # !python yolo_video.py --input '/content/20190224 鹿屋体育大学 vs 鹿児島高専 1st-l00CwQ6HI_o.mp4' --output /content/yolov3.mp4 # + id="sndu4o1pPqEX" colab_type="code" outputId="04036880-5314-4a7f-faaf-a27997132c86" colab={"base_uri": "https://localhost:8080/", "height": 240} from PIL import Image im = Image.open('/content/DSC_0194.JPG') import matplotlib.pyplot as plt plt.imshow(im) plt.show() # + id="YYbFYWI7U0og" colab_type="code" outputId="12c902e0-3388-4f4e-d200-b6864d26df04" colab={"base_uri": "https://localhost:8080/", "height": 1000} # !python yolo_video.py --image # + id="al0Zi8QuVEDT" colab_type="code" outputId="55c59fb7-af3a-4bad-f1db-9072c07f27d1" colab={"base_uri": "https://localhost:8080/", "height": 240} im = Image.open('/content/DSC_0194.JPG' + '_yolo.jpg') import matplotlib.pyplot as plt plt.imshow(im) plt.show() # + id="yzC03ZHL55lT" colab_type="code" outputId="18e9ed3b-9e9d-442e-b6a1-5cd244fec06d" colab={"base_uri": "https://localhost:8080/", "height": 428} # !python yolo_video.py --skip 10 --input /content/Untitled2.mp4 --output /content/Untitled2_yolo.mp4 > /content/Untitled2.mp4.log # + id="ragyiabzvhn5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 428} outputId="166b0ecc-bc8e-4f8c-f38a-fcb36dac1094" # !python yolo_video.py --skip 10 --input /content/Untitled.mp4 --output /content/Untitled_yolo.mp4 > Untitled_yolo.log # + id="bO05PNYS6ReR" colab_type="code" colab={} # !ffmpeg -i '/content/20190224 鹿屋体育大学 vs 鹿児島高専 1st-l00CwQ6HI_o.webm' -vcodec copy -acodec aac -ab 256k '/content/20190224 鹿屋体育大学 vs 鹿児島高専 1st-l00CwQ6HI_o.mp4' # + id="mWaQctamzAgL" colab_type="code" colab={} # !python yolo_video.py --input '/content/20190224 鹿屋体育大学 vs 鹿児島高専 1st-l00CwQ6HI_o.mp4' --output '/content/20190224 鹿屋体育大学 vs 鹿児島高専 1st-l00CwQ6HI_o_yolo.mp4' # + id="29V2UN0y87MB" colab_type="code" colab={} # !python yolo_video.py --step 20 --input '/content/20190224_vs_1st_trans_tKwSQIfV5q0_1080p.mp4' --output '/content/20190224_vs_1st_trans_tKwSQIfV5q0_1080p_yolo.mp4' > /content/20190224_vs_1st_trans_tKwSQIfV5q0_1080p.log
Yolov3_Test_for_Movies2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" id="5q-f8vrBMlKw" outputId="c26ebd17-93bc-4436-d47d-26e53dfba065" # import the dataset from keras.datasets import boston_housing (train_data, train_targets), (test_data, test_targets) = boston_housing.load_data() # + colab={} colab_type="code" id="UChMsKVkMtxa" # Normalizing the data mean = train_data.mean(axis=0) train_data -= mean std = train_data.std(axis=0) train_data /= std test_data -= mean test_data /= std # + colab={} colab_type="code" id="LmV3QzowMz5T" from keras import models from keras import layers # Define the structure of the model def build_model(): model = models.Sequential() model.add(layers.Dense(128, activation='relu', input_shape=(train_data.shape[1],))) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(1)) # mean square error is our loss and mean absolute error is our metric # Compile the model, configure the optimizer model.compile(optimizer='rmsprop', loss='mse', metrics=['mae']) return model # + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="af9z4-9MM2EF" outputId="30326b33-32db-4260-e031-20abf392293a" import numpy as np # K-fold validation k = 4 num_val_samples = len(train_data) // k num_epochs = 100 all_scores = [] for i in range(k): print('processing fold #', i) val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples] val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples] partial_train_data = np.concatenate( [train_data[:i * num_val_samples], train_data[(i + 1) * num_val_samples:]], axis=0) partial_train_targets = np.concatenate( [train_targets[:i * num_val_samples], train_targets[(i + 1) * num_val_samples:]], axis=0) model = build_model() model.fit(partial_train_data, partial_train_targets, epochs=num_epochs, batch_size=1, verbose=0) val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0) all_scores.append(val_mae) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="9e-6WKeIM6AV" outputId="c82095ed-994d-4e7a-86bd-cf6600bc309c" # mean average errors on validation set across all the 100 epochs all_scores # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="lpLdGI9uNU-f" outputId="26034b8d-cdb5-44a3-f032-d5012bac4b80" # mean np.mean(all_scores) # + colab={"base_uri": "https://localhost:8080/", "height": 85} colab_type="code" id="2j7vHsliNXe9" outputId="3b3b50de-48ed-4a03-9cbd-4301c5975707" # Saving the validation logs at each fold num_epochs = 500 all_mae_histories = [] for i in range(k): print('processing fold #', i) val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples] val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples] partial_train_data = np.concatenate( [train_data[:i * num_val_samples], train_data[(i + 1) * num_val_samples:]], axis=0) partial_train_targets = np.concatenate( [train_targets[:i * num_val_samples], train_targets[(i + 1) * num_val_samples:]], axis=0) model = build_model() history = model.fit(partial_train_data, partial_train_targets, validation_data=(val_data, val_targets), epochs=num_epochs, batch_size=1, verbose=0) mae_history = history.history['val_mean_absolute_error'] all_mae_histories.append(mae_history) # + colab={} colab_type="code" id="HxCTinFzN8Yt" # compute the average of the per-epoch MAE scores for all folds average_mae_history = [ np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)] # + colab={"base_uri": "https://localhost:8080/", "height": 361} colab_type="code" id="6j1r73WsN_TC" outputId="1bb8e771-7d68-471f-d477-5ddc5f16d28e" import matplotlib.pyplot as plt # Plotting Validation MAE by epoch, excluding the first 10 data points (using the moving average) def smooth_curve(points, factor=0.9): smoothed_points = [] for point in points: if smoothed_points: previous = smoothed_points[-1] smoothed_points.append(previous * factor + point * (1 - factor)) else: smoothed_points.append(point) return smoothed_points smooth_mae_history = smooth_curve(average_mae_history[10:]) plt.plot(range(1, len(smooth_mae_history) + 1), smooth_mae_history) plt.xlabel('Epochs') plt.ylabel('Validation MAE') plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 2754} colab_type="code" id="8AUfhkcaOGCI" outputId="ba51f8e4-f8dd-4ad9-baa0-b8a7ed35b147" # According the the graph (Figure 5), validation MAE stops improving significantly after 80 epochs. # so lets train the model for 80 epochs model = build_model() # Training the final model model.fit(train_data, train_targets, epochs=80, batch_size=16, verbose=1) test_mse_score, test_mae_score = model.evaluate(test_data, test_targets) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="88-YKM5BOHwI" outputId="c8a631ba-b699-4910-a90a-9d79cb525560" # Test mean square error test_mse_score # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="fkP5hakdOMUe" outputId="e093acd7-dbc8-4d1c-f7a6-aff3492583d6" # Test mean absolute error test_mae_score # + colab={} colab_type="code" id="TmW7QsXhQfdx"
The_Boston_Housing_Price.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"} # # Tracking Failure Origins # # The question of "Where does this value come from?" is fundamental for debugging. Which earlier variables could possibly have influenced the current erroneous state? And how did their values come to be? # # When programmers read code during debugging, they scan it for potential _origins_ of given values. This can be a tedious experience, notably, if the origins spread across multiple separate locations, possibly even in different modules. In this chapter, we thus investigate means to _determine such origins_ automatically – by collecting data and control dependencies during program execution. # + slideshow={"slide_type": "skip"} from bookutils import YouTubeVideo YouTubeVideo("sjf3cOR0lcI") # + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"} # **Prerequisites** # # * You should have read the [Introduction to Debugging](Intro_Debugging). # * To understand how to compute dependencies automatically (the second half of this chapter), you will need # * advanced knowledge of Python semantics # * knowledge on how to instrument and transform code # * knowledge on how an interpreter works # + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "skip"} import bookutils # + slideshow={"slide_type": "skip"} from bookutils import quiz, next_inputs, print_content # + [markdown] slideshow={"slide_type": "skip"} # ## Synopsis # <!-- Automatically generated. Do not edit. --> # # To [use the code provided in this chapter](Importing.ipynb), write # # ```python # >>> from debuggingbook.Slicer import <identifier> # ``` # # and then make use of the following features. # # # This chapter provides a `Slicer` class to automatically determine and visualize dynamic dependencies. When we say that a variable $x$ depends on a variable $y$ (written $x \leftarrow y$), we distinguish two kinds of dependencies: # # * **data dependencies**: $x$ obtains its value from a computation involving the value of $y$. # * **control dependencies**: $x$ obtains its value because of a computation involving the value of $y$. # # Such dependencies are crucial for debugging, as they allow to determine the origins of individual values (and notably incorrect values). # # To determine dynamic dependencies in a function `func` and its callees `func1`, `func2`, etc., use # # ```python # with Slicer(func, func1, func2) as slicer: # <Some code involving func()> # ``` # # and then `slicer.graph()` or `slicer.code()` to examine dependencies. # # Here is an example. The `demo()` function computes some number from `x`: # # ```python # >>> def demo(x): # >>> z = x # >>> while x <= z <= 64: # >>> z *= 2 # >>> return z # ``` # By using `with Slicer(demo)`, we first instrument `demo()` and then execute it: # # ```python # >>> with Slicer(demo) as slicer: # >>> demo(10) # ``` # After execution is complete, you can output `slicer` to visualize the dependencies as graph. Data dependencies are shown as black solid edges; control dependencies are shown as grey dashed edges. We see how the parameter `x` flows into `z`, which is returned after some computation that is control dependent on a `<test>` involving `z`. # # ```python # >>> slicer # ``` # # ![](PICS/Slicer-synopsis-1.svg) # # An alternate representation is `slicer.code()`, annotating the instrumented source code with (backward) dependencies. Data dependencies are shown with `<=`, control dependencies with `<-`; locations (lines) are shown in parentheses. # # ```python # >>> slicer.code() # # * 1 def demo(x): # * 2 z = x # <= x (1) # * 3 while x <= z <= 64: # <= x (1), z (4), z (2) # * 4 z *= 2 # <= z (4), z (2); <- <test> (3) # * 5 return z # <= z (4) # ``` # Dependencies can also be retrieved programmatically. The `dependencies()` method returns a `Dependencies` object encapsulating the dependency graph. # # The method `all_vars()` returns all variables in the dependency graph. Each variable is encoded as a pair (_name_, _location_) where _location_ is a pair (_codename_, _lineno_). # # ```python # >>> slicer.dependencies().all_vars() # # {('<demo() return value>', (<function __main__.demo(x)>, 5)), # ('<test>', (<function __main__.demo(x)>, 3)), # ('x', (<function __main__.demo(x)>, 1)), # ('z', (<function __main__.demo(x)>, 2)), # ('z', (<function __main__.demo(x)>, 4))} # ``` # `code()` and `graph()` methods can also be applied on dependencies. The method `backward_slice(var)` returns a backward slice for the given variable. To retrieve where `z` in Line 2 came from, use: # # ```python # >>> _, start_demo = inspect.getsourcelines(demo) # >>> start_demo # # 1 # # >>> slicer.dependencies().backward_slice(('z', (demo, start_demo + 1))).graph() # ``` # # ![](PICS/Slicer-synopsis-2.svg) # # Here are the classes defined in this chapter. A `Slicer` instruments a program, using a `DependencyTracker` at run time to collect `Dependencies`. # # # ![](PICS/Slicer-synopsis-3.svg) # # # + [markdown] button=false new_sheet=true run_control={"read_only": false} slideshow={"slide_type": "slide"} # ## Dependencies # # In the [Introduction to debugging](Intro_Debugging.ipynb), we have seen how faults in a program state propagate to eventually become visible as failures. This induces a debugging strategy called _tracking origins_: # + [markdown] button=false new_sheet=true run_control={"read_only": false} slideshow={"slide_type": "subslide"} # 1. We start with a single faulty state _f_ – the failure # 2. We determine f's _origins_ – the parts of earlier states that could have caused the faulty state _f_ # 3. For each of these origins _e_, we determine whether they are faulty or not # 4. For each of the faulty origins, we in turn determine _their_ origins. # 5. If we find a part of the state that is faulty, yet has only correct origins, we have found the defect. # + [markdown] button=false new_sheet=true run_control={"read_only": false} slideshow={"slide_type": "subslide"} # In all generality, a "part of the state" can be anything that can influence the program – some configuration setting, some database content, or the state of a device. Almost always, though, it is through _individual variables_ that a part of the state manifests itself. # # The good news is that variables do not take arbitrary values at arbitrary times – instead, they are set and accessed at precise moments in time, as determined by the program's semantics. This allows us to determine their _origins_ by reading program code. # + [markdown] button=false new_sheet=true run_control={"read_only": false} slideshow={"slide_type": "fragment"} # Let us assume you have a piece of code that reads as follows. The `middle()` function is supposed to return the "middle" number of three values `x`, `y`, and `z` – that is, the one number that neither is the minimum nor the maximum. # + slideshow={"slide_type": "subslide"} def middle(x, y, z): if y < z: if x < y: return y elif x < z: return y else: if x > y: return y elif x > z: return x return z # + [markdown] slideshow={"slide_type": "fragment"} # In most cases, `middle()` runs just fine: # + slideshow={"slide_type": "subslide"} m = middle(1, 2, 3) m # + [markdown] slideshow={"slide_type": "fragment"} # In others, however, it returns the wrong value: # + slideshow={"slide_type": "fragment"} m = middle(2, 1, 3) m # + [markdown] slideshow={"slide_type": "subslide"} # This is a typical debugging situation: You see a value that is erroneous; and you want to find out where it came from. # # * In our case, we see that the erroneous value was returned from `middle()`, so we identify the five `return` statements in `middle()` that the value could have come from. # * The value returned is the value of `y`, and neither `x`, `y`, nor `z` are altered during the execution of `middle()`. Hence, it must be one of the three `return y` statements that is the origin of `m`. But which one? # # For our small example, we can fire up an interactive debugger and simply step through the function; this reveals us the conditions evaluated and the `return` statement executed. # + slideshow={"slide_type": "skip"} from Debugger import Debugger # minor dependency # + slideshow={"slide_type": "subslide"} # ignore next_inputs(["step", "step", "step", "step", "quit"]); # + slideshow={"slide_type": "subslide"} with Debugger(): middle(2, 1, 3) # + [markdown] slideshow={"slide_type": "subslide"} # We now see that it was the second `return` statement that returned the incorrect value. But why was it executed after all? To this end, we can resort to the `middle()` source code and have a look at those conditions that caused the `return y` statement to be executed. Indeed, the conditions `y < z`, `x > y`, and finally `x < z`again are _origins_ of the returned value – and in turn have `x`, `y`, and `z` as origins. # + [markdown] slideshow={"slide_type": "subslide"} # In our above reasoning about origins, we have encountered two kinds of origins: # # * earlier _data values_ (such as the value of `y` being returned) and # * earlier _control conditions_ (such as the `if` conditions governing the `return y` statement). # # The later parts of the state that can be influenced by such origins are said to be _dependent_ on these origins. Speaking of variables, a variable $x$ _depends_ on the value of a variable $y$ (written as $x \leftarrow y$) if a change in $y$ could affect the value of $x$. # + [markdown] slideshow={"slide_type": "subslide"} # We distinguish two kinds of dependencies $x \leftarrow y$, aligned with the two kinds of origins as outlined above: # # * **Data dependency**: $x$ obtains its value from a computation involving the value of $y$. In our example, `m` is data dependent on the return value of `middle()`. # * **Control dependency**: $x$ obtains its value because of a computation involving the value of $y$. In our example, the value returned by `return y` is control dependent on the several conditions along its path, which involve `x`, `y`, and `z`. # + [markdown] slideshow={"slide_type": "fragment"} # Let us examine these dependencies in more detail. # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Visualizing Dependencies # + [markdown] slideshow={"slide_type": "fragment"} # Note: This is an excursion, diverting away from the main flow of the chapter. Unless you know what you are doing, you are encouraged to skip this part. # + [markdown] slideshow={"slide_type": "fragment"} # To illustrate our examples, we introduce a `Dependencies` class that captures dependencies between variables at specific locations. # + [markdown] slideshow={"slide_type": "subslide"} # #### A Class for Dependencies # + [markdown] slideshow={"slide_type": "fragment"} # `Dependencies` holds two dependency graphs. `data` holds data dependencies, `control` holds control dependencies. # + slideshow={"slide_type": "subslide"} class Dependencies(object): def __init__(self, data=None, control=None): """ Create a dependency graph from `data` and `control`. Both `data` and `control` are dictionaries holding _nodes_ as keys and sets of nodes as values. Each node comes as a tuple (variable_name, location) where `variable_name` is a string and `location` is a pair (function, lineno) where `function` is a callable and `lineno` is a line number denoting a unique location in the code. """ if data is None: data = {} if control is None: control = {} self.data = data self.control = control for var in self.data: self.control.setdefault(var, set()) for var in self.control: self.data.setdefault(var, set()) self.validate() # + [markdown] slideshow={"slide_type": "subslide"} # Each of the two is organized as a dictionary holding _nodes_ as keys and lists of nodes as values. Each node comes as a tuple # # ```python # (variable_name, location) # ``` # # where `variable_name` is a string and `location` is a pair # # # ```python # (func, lineno) # ``` # # denoting a unique location in the code. # + [markdown] slideshow={"slide_type": "subslide"} # The `validate()` method checks for consistency. # + slideshow={"slide_type": "fragment"} class Dependencies(Dependencies): def validate(self): """Check dependency structure.""" assert isinstance(self.data, dict) assert isinstance(self.control, dict) for node in (self.data.keys()) | set(self.control.keys()): var_name, location = node assert isinstance(var_name, str) func, lineno = location assert callable(func) assert isinstance(lineno, int) # + [markdown] slideshow={"slide_type": "subslide"} # In this chapter, for many purposes, we need to lookup a function's location, source code, or simply definition. The class `StackInspector` provides a number of convenience functions for this purpose. # + [markdown] slideshow={"slide_type": "fragment"} # When we access or execute functions, we do so in the caller's environment, not ours. The `caller_globals()` method acts as replacement for `globals()`. # + [markdown] slideshow={"slide_type": "fragment"} # The method `caller_frame()` walks up the current call stack and returns the topmost frame invoking a method or function from the current class. # + slideshow={"slide_type": "skip"} import inspect from types import FunctionType # + slideshow={"slide_type": "subslide"} class StackInspector(object): def caller_frame(self): """Return the frame of the caller.""" # Walk up the call tree until we leave the current class frame = inspect.currentframe() while ('self' in frame.f_locals and isinstance(frame.f_locals['self'], self.__class__)): frame = frame.f_back return frame def caller_globals(self): """Return the globals() environment of the caller.""" return self.caller_frame().f_globals def caller_locals(self): """Return the locals() environment of the caller.""" return self.caller_frame().f_locals # + [markdown] slideshow={"slide_type": "subslide"} # `caller_location()` returns the caller's function and its location. It does a fair bit of magic to retrieve nested functions, by looking through global and local variables until a match is found. This may be simplified in the future. # + slideshow={"slide_type": "subslide"} class StackInspector(StackInspector): def caller_location(self): """Return the location (func, lineno) of the caller.""" return self.caller_function(), self.caller_frame().f_lineno def search_frame(self, name): """Return a pair (`frame`, `item`) in which the function `name` is defined as `item`.""" frame = self.caller_frame() while frame: item = None if name in frame.f_globals: item = frame.f_globals[name] if name in frame.f_locals: item = frame.f_locals[name] if item and callable(item): return frame, item frame = frame.f_back return None, None def search_func(self, name): """Search in callers for a definition of the function `name`""" frame, func = self.search_frame(name) return func def caller_function(self): """Return the calling function""" frame = self.caller_frame() name = frame.f_code.co_name func = self.search_func(name) if func: return func if not name.startswith('<'): warnings.warn(f"Couldn't find {name} in caller") try: # Create new function from given code return FunctionType(frame.f_code, globals=frame.f_globals, name=name) except TypeError: # Unsuitable code for creating a function # Last resort: Return some function return self.unknown except Exception as exc: # Any other exception warnings.warn(f"Couldn't create function for {name} " f" ({type(exc).__name__}: {exc})") return self.unknown def unknown(): pass # + [markdown] slideshow={"slide_type": "subslide"} # We make the `StackInspector` methods available as part of the `Dependencies` class. # + ipub={"ignore": true} slideshow={"slide_type": "fragment"} class Dependencies(Dependencies, StackInspector): pass # + [markdown] slideshow={"slide_type": "fragment"} # The `source()` method returns the source code for a given node. # + slideshow={"slide_type": "skip"} import warnings # + ipub={"ignore": true} slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def _source(self, node): # Return source line, or '' (name, location) = node func, lineno = location if not func: # No source return '' try: source_lines, first_lineno = inspect.getsourcelines(func) except OSError: warnings.warn(f"Couldn't find source " f"for {func} ({func.__name__})") return '' try: line = source_lines[lineno - first_lineno].strip() except IndexError: return '' return line def source(self, node): """Return the source code for a given node.""" line = self._source(node) if line: return line (name, location) = node func, lineno = location code_name = func.__name__ if code_name.startswith('<'): return code_name else: return f'<{code_name}()>' # + slideshow={"slide_type": "subslide"} test_deps = Dependencies() test_deps.source(('z', (middle, 1))) # + [markdown] slideshow={"slide_type": "subslide"} # #### Drawing Dependencies # + [markdown] slideshow={"slide_type": "fragment"} # Both data and control form a graph between nodes, and cam be visualized as such. We use the `graphviz` package for creating such visualizations. # + ipub={"ignore": true} slideshow={"slide_type": "skip"} from graphviz import Digraph, nohtml # + [markdown] slideshow={"slide_type": "fragment"} # `make_graph()` sets the basic graph attributes. # + slideshow={"slide_type": "skip"} import html # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): NODE_COLOR = 'peachpuff' FONT_NAME = 'Fira Mono, Courier, monospace' def make_graph(self, name="dependencies", comment="Dependencies"): return Digraph(name=name, comment=comment, graph_attr={ }, node_attr={ 'style': 'filled', 'shape': 'box', 'fillcolor': self.NODE_COLOR, 'fontname': self.FONT_NAME }, edge_attr={ 'fontname': self.FONT_NAME }) # + [markdown] slideshow={"slide_type": "subslide"} # `graph()` returns a graph visualization. # + slideshow={"slide_type": "fragment"} class Dependencies(Dependencies): def graph(self): """Draw dependencies.""" self.validate() g = self.make_graph() self.draw_dependencies(g) self.add_hierarchy(g) return g # In Jupyter, render dependencies as graph def _repr_svg_(self): return self.graph()._repr_svg_() # + [markdown] slideshow={"slide_type": "subslide"} # The main part of graph drawing takes place in two methods, `draw_dependencies()` and `add_hierarchy()`. # + [markdown] slideshow={"slide_type": "fragment"} # `draw_dependencies()` processes through the graph, adding nodes and edges from the dependencies. # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def all_vars(self): all_vars = set() for var in self.data: all_vars.add(var) for source in self.data[var]: all_vars.add(source) for var in self.control: all_vars.add(var) for source in self.control[var]: all_vars.add(source) return all_vars # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def draw_dependencies(self, g): for var in self.all_vars(): g.node(self.id(var), label=self.label(var), tooltip=self.tooltip(var)) if var in self.data: for source in self.data[var]: g.edge(self.id(source), self.id(var)) if var in self.control: for source in self.control[var]: g.edge(self.id(source), self.id(var), style='dashed', color='grey') # + [markdown] slideshow={"slide_type": "subslide"} # `draw_dependencies()` makes use of a few helper functions. # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def id(self, var): """Return a unique ID for `var`.""" id = "" # Avoid non-identifier characters for c in repr(var): if c.isalnum() or c == '_': id += c if c == ':' or c == ',': id += '_' return id def label(self, var): """Render node `var` using HTML style.""" (name, location) = var source = self.source(var) title = html.escape(name) if name.startswith('<'): title = f'<I>{title}</I>' label = f'<B>{title}</B>' if source: label += (f'<FONT POINT-SIZE="9.0"><BR/><BR/>' f'{html.escape(source)}' f'</FONT>') label = f'<{label}>' return label def tooltip(self, var): """Return a tooltip for node `var`.""" (name, location) = var func, lineno = location return f"{func.__name__}:{lineno}" # + [markdown] slideshow={"slide_type": "subslide"} # In the second part of graph drawing, `add_hierarchy()` adds invisible edges to ensure that nodes with lower line numbers are drawn above nodes with higher line numbers. # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def add_hierarchy(self, g): """Add invisible edges for a proper hierarchy.""" functions = self.all_functions() for func in functions: last_var = None last_lineno = 0 for (lineno, var) in functions[func]: if last_var is not None and lineno > last_lineno: g.edge(self.id(last_var), self.id(var), style='invis') last_var = var last_lineno = lineno return g # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def all_functions(self): functions = {} for var in self.all_vars(): (name, location) = var func, lineno = location if func not in functions: functions[func] = [] functions[func].append((lineno, var)) for func in functions: functions[func].sort() return functions # + [markdown] slideshow={"slide_type": "fragment"} # Here comes the graph in all its glory: # + slideshow={"slide_type": "subslide"} def middle_deps(): return Dependencies({('z', (middle, 1)): set(), ('y', (middle, 1)): set(), ('x', (middle, 1)): set(), ('<test>', (middle, 2)): {('y', (middle, 1)), ('z', (middle, 1))}, ('<test>', (middle, 3)): {('y', (middle, 1)), ('x', (middle, 1))}, ('<test>', (middle, 5)): {('z', (middle, 1)), ('x', (middle, 1))}, ('<middle() return value>', (middle, 6)): {('y', (middle, 1))}}, {('z', (middle, 1)): set(), ('y', (middle, 1)): set(), ('x', (middle, 1)): set(), ('<test>', (middle, 2)): set(), ('<test>', (middle, 3)): {('<test>', (middle, 2))}, ('<test>', (middle, 5)): {('<test>', (middle, 3))}, ('<middle() return value>', (middle, 6)): {('<test>', (middle, 5))}}) # + slideshow={"slide_type": "fragment"} middle_deps() # + [markdown] slideshow={"slide_type": "subslide"} # #### Slices # # The method `backward_slice(*critera, mode='cd')` returns a subset of dependencies, following dependencies backward from the given *slicing criteria* `criteria`. These criteria can be # # * variable names (such as `<test>`); or # * `(function, lineno)` pairs (such as `(middle, 3)`); or # * `(var_name, (function, lineno))` (such as `(`x`, (middle, 1))`) locations. # # The extra parameter `mode` controls which dependencies are to be followed: # # * **`d`** = data dependencies # * **`c`** = control dependencies # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def expand_criteria(self, criteria): """Return list of vars matched by `criteria`.""" all_vars = [] for criterion in criteria: criterion_var = None criterion_func = None criterion_lineno = None if isinstance(criterion, str): criterion_var = criterion elif len(criterion) == 2 and callable(criterion[0]): criterion_func, criterion_lineno = criterion elif len(criterion) == 2 and isinstance(criterion[0], str): criterion_var = criterion[0] criterion_func, criterion_lineno = criterion[1] else: raise ValueError("Invalid argument") for var in self.all_vars(): (var_name, location) = var func, lineno = location name_matches = (criterion_func is None or criterion_func == func or criterion_func.__name__ == func.__name__) location_matches = (criterion_lineno is None or criterion_lineno == lineno) var_matches = (criterion_var is None or criterion_var == var_name) if name_matches and location_matches and var_matches: all_vars.append(var) return all_vars def backward_slice(self, *criteria, mode="cd", depth=-1): """Create a backward slice from nodes `criteria`. `mode` can contain 'c' (draw control dependencies) and 'd' (draw data dependencies) (default: 'cd')""" data = {} control = {} queue = self.expand_criteria(criteria) seen = set() while len(queue) > 0 and depth != 0: var = queue[0] queue = queue[1:] seen.add(var) if 'd' in mode: # Follow data dependencies data[var] = self.data[var] for next_var in data[var]: if next_var not in seen: queue.append(next_var) else: data[var] = set() if 'c' in mode: # Follow control dependencies control[var] = self.control[var] for next_var in control[var]: if next_var not in seen: queue.append(next_var) else: control[var] = set() depth -= 1 return Dependencies(data, control) # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "subslide"} # ### Data Dependencies # # Here is an example of a data dependency in our `middle()` program. The value `y` returned by `middle()` comes from the value `y` as originally passed as argument. We use arrows $x \leftarrow y$ to indicate that a variable $x$ depends on an earlier variable $y$: # + slideshow={"slide_type": "fragment"} # ignore middle_deps().backward_slice('<middle() return value>', mode='d') # + [markdown] slideshow={"slide_type": "fragment"} # Here, we can see that the value `y` in the return statement is data dependent on the value of `y` as passed to `middle()`. An alternate interpretation of this graph is a *data flow*: The value of `y` in the upper node _flows_ into the value of `y` in the lower node. # + [markdown] slideshow={"slide_type": "subslide"} # Since we consider the values of variables at specific locations in the program, such data dependencies can also be interpreted as dependencies between _statements_ – the above `return` statement thus is data dependent on the initialization of `y` in the upper node. # + [markdown] slideshow={"slide_type": "subslide"} # ### Control Dependencies # # Here is an example of a control dependency. The execution of the above `return` statement is controlled by the earlier test `x < z`. We use grey dashed lines to indicate control dependencies: # + slideshow={"slide_type": "fragment"} # ignore middle_deps().backward_slice('<middle() return value>', mode='c', depth=1) # + [markdown] slideshow={"slide_type": "fragment"} # This test in turn is controlled by earlier tests, so the full chain of control dependencies looks like this: # + slideshow={"slide_type": "fragment"} # ignore middle_deps().backward_slice('<middle() return value>', mode='c') # + [markdown] slideshow={"slide_type": "subslide"} # ### Dependency Graphs # # As the above `<test>` values (and their statements) are in turn also dependent on earlier data, namely the `x`, `y`, and `z` values as originally passed. We can draw all data and control dependencies in a single graph, called a _program dependency graph_: # + slideshow={"slide_type": "fragment"} # ignore middle_deps() # + [markdown] slideshow={"slide_type": "fragment"} # This graph now gives us an idea on how to proceed to track the origins of the `middle()` return value at the bottom. Its value can come from any of the origins – namely the initialization of `y` at the function call, or from the `<test>` that controls it. This test in turn depends on `x` and `z` and their associated statements, which we now can check one after the other. # + [markdown] slideshow={"slide_type": "subslide"} # Note that all these dependencies in the graph are _dynamic_ dependencies – that is, they refer to statements actually evaluated in the run at hand, as well as the decisions made in that very run. There also are _static_ dependency graphs coming from static analysis of the code; but for debugging, _dynamic_ dependencies specific to the failing run are more useful. # + [markdown] slideshow={"slide_type": "subslide"} # ### Showing Dependencies with Code # # While a graph gives us a representation about which possible data and control flows to track, integrating dependencies with actual program code results in a compact representation that is easy to reason about. # + [markdown] slideshow={"slide_type": "subslide"} # #### Excursion: Listing Dependencies # + [markdown] slideshow={"slide_type": "subslide"} # To show dependencies as text, we introduce a method `format_var()` that shows a single node (a variable) as text. By default, a node is referenced as # # ```python # NAME (FUNCTION:LINENO) # ``` # # However, within a given function, it makes no sense to re-state the function name again and again, so we have a shorthand # # ```python # NAME (LINENO) # ``` # # to state a dependency to variable `NAME` in line `LINENO`. # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def format_var(self, var, current_func=None): """Return string for `var` in `current_func`.""" name, location = var func, lineno = location if func == current_func or func.__name__ == current_func.__name__: return f"{name} ({lineno})" else: return f"{name} ({func.__name__}:{lineno})" # + [markdown] slideshow={"slide_type": "fragment"} # `format_var()` is used extensively in the `__str__()` string representation of dependencies, listing all nodes and their data (`<=`) and control (`<-`) dependencies. # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def __str__(self): """Return string representation of dependencies""" self.validate() out = "" for func in self.all_functions(): code_name = func.__name__ if out != "": out += "\n" out += f"{code_name}():\n" all_vars = list(set(self.data.keys()) | set(self.control.keys())) all_vars.sort(key=lambda var: var[1][1]) for var in all_vars: (name, location) = var var_func, var_lineno = location var_code_name = var_func.__name__ if var_code_name != code_name: continue all_deps = "" for (source, arrow) in [(self.data, "<="), (self.control, "<-")]: deps = "" for data_dep in source[var]: if deps == "": deps = f" {arrow} " else: deps += ", " deps += self.format_var(data_dep, func) if deps != "": if all_deps != "": all_deps += ";" all_deps += deps if all_deps == "": continue out += (" " + self.format_var(var, func) + all_deps + "\n") return out # + [markdown] slideshow={"slide_type": "subslide"} # Here is a compact string representation of dependencies. We see how the (last) `middle() return value` has a data dependency to `y` in Line 1, and to the `<test>` in Line 5. # + slideshow={"slide_type": "fragment"} print(middle_deps()) # + [markdown] slideshow={"slide_type": "fragment"} # The `__repr__()` method shows a raw form of dependencies, useful for creating dependencies from scratch. # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def repr_var(self, var): name, location = var func, lineno = location return f"({repr(name)}, ({func.__name__}, {lineno}))" def repr_deps(self, var_set): if len(var_set) == 0: return "set()" return ("{" + ", ".join(f"{self.repr_var(var)}" for var in var_set) + "}") def repr_dependencies(self, vars): return ("{\n " + ",\n ".join( f"{self.repr_var(var)}: {self.repr_deps(vars[var])}" for var in vars) + "}") def __repr__(self): # Useful for saving and restoring values return (f"Dependencies(\n" + f" data={self.repr_dependencies(self.data)},\n" + f" control={self.repr_dependencies(self.control)})") # + slideshow={"slide_type": "subslide"} print(repr(middle_deps())) # + [markdown] slideshow={"slide_type": "subslide"} # An even more useful representation comes when integrating these dependencies as comments into the code. The method `code(item_1, item_2, ...)` lists the given (function) items, including their dependencies; `code()` lists _all_ functions contained in the dependencies. # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def code(self, *items, mode='cd'): """List `items` on standard output, including dependencies as comments. If `items` is empty, all included functions are listed. `mode` can contain 'c' (draw control dependencies) and 'd' (draw data dependencies) (default: 'cd').""" if len(items) == 0: items = self.all_functions().keys() for i, item in enumerate(items): if i > 0: print() self._code(item, mode) # + slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def _code(self, item, mode): # The functions in dependencies may be (instrumented) copies # of the original function. Find the function with the same name. func = item for fn in self.all_functions(): if fn == item or fn.__name__ == item.__name__: func = fn break all_vars = self.all_vars() slice_locations = set(location for (name, location) in all_vars) source_lines, first_lineno = inspect.getsourcelines(func) n = first_lineno for line in source_lines: line_location = (func, n) if line_location in slice_locations: prefix = "* " else: prefix = " " print(f"{prefix}{n:4} ", end="") comment = "" for (mode_control, source, arrow) in [ ('d', self.data, '<='), ('c', self.control, '<-') ]: if mode_control not in mode: continue deps = "" for var in source: name, location = var if location == line_location: for dep_var in source[var]: if deps == "": deps = arrow + " " else: deps += ", " deps += self.format_var(dep_var, item) if deps != "": if comment != "": comment += "; " comment += deps if comment != "": line = line.rstrip() + " # " + comment print_content(line.rstrip(), '.py') print() n += 1 # + [markdown] slideshow={"slide_type": "subslide"} # #### End of Excursion # + [markdown] slideshow={"slide_type": "subslide"} # The following listing shows such an integration. For each executed line (`*`), we see its data (`<=`) and control (`<-`) dependencies, listing the associated variables and line numbers. The comment # # ```python # # <= y (1); <- <test> (5) # ``` # # for Line 6, for instance, states that the return value is data dependent on the value of `y` in Line 1, and control dependent on the test in Line 5. # # Again, one can easily follow these dependencies back to track where a value came from (data dependencies) and why a statement was executed (control dependency). # + slideshow={"slide_type": "subslide"} # ignore middle_deps().code() # + [markdown] slideshow={"slide_type": "subslide"} # One important aspect of dependencies is that they not only point to specific sources and causes of failures – but that they also _rule out_ parts of program and state as failures. # # * In the above code, Lines 8 and later have no influence on the output, simply because they were not executed. # * Furthermore, we see that we can start our investigation with Line 6, because that is the last one executed. # * The data dependencies tell us that no statement has interfered with the value of `y` between the function call and its return. # * Hence, the error must be in the conditions and the final `return` statement. # # With this in mind, recall that our original invocation was `middle(2, 1, 3)`. Why and how is the above code wrong? # + slideshow={"slide_type": "subslide"} quiz("Which of the following `middle()` code lines should be fixed?", [ "Line 2: `if y < z:`", "Line 3: `if x < y:`", "Line 5: `elif x < z:`", "Line 6: `return z`", ], (1 ** 0 + 1 ** 1) ** (1 ** 2 + 1 ** 3)) # + [markdown] slideshow={"slide_type": "fragment"} # Indeed, from the controlling conditions, we see that `y < z`, `x >= y`, and `x < z` all hold. Hence, `y <= x < z` holds, and it is `x`, not `y`, that should be returned. # + [markdown] slideshow={"slide_type": "slide"} # ## Slices # # Given a dependency graph for a particular variable, we can identify the subset of the program that could have influenced it – the so-called _slice_. In the above code listing, these code locations are highlighted with `*` characters. Only these locations are part of the slice. # + [markdown] slideshow={"slide_type": "subslide"} # Slices are central to debugging for two reasons: # # * First, they _rule out_ those locations of the program that could _not_ have an effect on the failure. Hence, these locations need not be investigated as it comes to searching for the defect. Nor do they need to be considered for a fix, as any change outside of the program slice by construction cannot affect the failure. # * Second, they bring together possible origins that may be scattered across the code. Many dependencies in program code are _non-local_, with references to functions, classes, and modules defined in other locations, files, or libraries. A slice brings together all those locations in a single whole. # + [markdown] slideshow={"slide_type": "subslide"} # Here is an example of a slice – this time for our well-known `remove_html_markup()` function from [the introduction to debugging](Intro_Debugging.ipynb): # + slideshow={"slide_type": "skip"} from Intro_Debugging import remove_html_markup # + slideshow={"slide_type": "subslide"} print_content(inspect.getsource(remove_html_markup), '.py') # + [markdown] slideshow={"slide_type": "subslide"} # When we invoke `remove_html_markup()` as follows... # + slideshow={"slide_type": "fragment"} remove_html_markup('<foo>bar</foo>') # + [markdown] slideshow={"slide_type": "fragment"} # ... we obtain the following dependencies: # + slideshow={"slide_type": "fragment"} # ignore def remove_html_markup_deps(): return Dependencies({('s', (remove_html_markup, 136)): set(), ('tag', (remove_html_markup, 137)): set(), ('quote', (remove_html_markup, 138)): set(), ('out', (remove_html_markup, 139)): set(), ('c', (remove_html_markup, 141)): {('s', (remove_html_markup, 136))}, ('<test>', (remove_html_markup, 144)): {('quote', (remove_html_markup, 138)), ('c', (remove_html_markup, 141))}, ('tag', (remove_html_markup, 145)): set(), ('<test>', (remove_html_markup, 146)): {('quote', (remove_html_markup, 138)), ('c', (remove_html_markup, 141))}, ('<test>', (remove_html_markup, 148)): {('c', (remove_html_markup, 141))}, ('<test>', (remove_html_markup, 150)): {('tag', (remove_html_markup, 147)), ('tag', (remove_html_markup, 145))}, ('tag', (remove_html_markup, 147)): set(), ('out', (remove_html_markup, 151)): {('out', (remove_html_markup, 151)), ('c', (remove_html_markup, 141)), ('out', (remove_html_markup, 139))}, ('<remove_html_markup() return value>', (remove_html_markup, 153)): {('<test>', (remove_html_markup, 146)), ('out', (remove_html_markup, 151))}}, {('s', (remove_html_markup, 136)): set(), ('tag', (remove_html_markup, 137)): set(), ('quote', (remove_html_markup, 138)): set(), ('out', (remove_html_markup, 139)): set(), ('c', (remove_html_markup, 141)): set(), ('<test>', (remove_html_markup, 144)): set(), ('tag', (remove_html_markup, 145)): {('<test>', (remove_html_markup, 144))}, ('<test>', (remove_html_markup, 146)): {('<test>', (remove_html_markup, 144))}, ('<test>', (remove_html_markup, 148)): {('<test>', (remove_html_markup, 146))}, ('<test>', (remove_html_markup, 150)): {('<test>', (remove_html_markup, 148))}, ('tag', (remove_html_markup, 147)): {('<test>', (remove_html_markup, 146))}, ('out', (remove_html_markup, 151)): {('<test>', (remove_html_markup, 150))}, ('<remove_html_markup() return value>', (remove_html_markup, 153)): set()}) # + slideshow={"slide_type": "fragment"} # ignore remove_html_markup_deps().graph() # + [markdown] slideshow={"slide_type": "subslide"} # Again, we can read such a graph _forward_ (starting from, say, `s`) or _backward_ (starting from the return value). Starting forward, we see how the passed string `s` flows into the `for` loop, breaking `s` into individual characters `c` that are then checked on various occasions, before flowing into the `out` return value. We also see how the various `if` conditions are all influenced by `c`, `tag`, and `quote`. # + slideshow={"slide_type": "fragment"} quiz("Why does the first line `tag = False` not influence anything?", [ "Because the input contains only tags", "Because `tag` is set to True with the first character", "Because `tag` is not read by any variable", "Because the input contains no tags", ], (1 << 1 + 1 >> 1)) # + [markdown] slideshow={"slide_type": "subslide"} # Which are the locations that set `tag` to True? To this end, we compute the slice of `tag` at `tag = True`: # + slideshow={"slide_type": "subslide"} # ignore tag_deps = Dependencies({('tag', (remove_html_markup, 145)): set(), ('<test>', (remove_html_markup, 144)): {('quote', (remove_html_markup, 138)), ('c', (remove_html_markup, 141))}, ('quote', (remove_html_markup, 138)): set(), ('c', (remove_html_markup, 141)): {('s', (remove_html_markup, 136))}, ('s', (remove_html_markup, 136)): set()}, {('tag', (remove_html_markup, 145)): {('<test>', (remove_html_markup, 144))}, ('<test>', (remove_html_markup, 144)): set(), ('quote', (remove_html_markup, 138)): set(), ('c', (remove_html_markup, 141)): set(), ('s', (remove_html_markup, 136)): set()}) tag_deps # + [markdown] slideshow={"slide_type": "subslide"} # We see where the value of `tag` comes from: from the characters `c` in `s` as well as `quote`, which all cause it to be set. Again, we can combine these dependencies and the listing in a single, compact view. Note, again, that there are no other locations in the code that could possibly have affected `tag` in our run. # + slideshow={"slide_type": "subslide"} # ignore tag_deps.code() # + slideshow={"slide_type": "subslide"} quiz("How does the slice of `tag = True` change " "for a different value of `s`?", [ "Not at all", "If `s` contains a quote, the `quote` slice is included, too", "If `s` contains no HTML tag, the slice will be empty" ], [1, 2, 3][1:]) # + [markdown] slideshow={"slide_type": "fragment"} # Indeed, our dynamic slices reflect dependencies as they occurred within a single execution. As the execution changes, so do the dependencies. # + [markdown] slideshow={"slide_type": "slide"} # ## Tracking Techniques # # For the remainder of this chapter, let us investigate means to _determine such dependencies_ automatically – by _collecting_ them during program execution. The idea is that with a single Python call, we can collect the dependencies for some computation, and present them to programmers – as graphs or as code annotations, as shown above. # + [markdown] slideshow={"slide_type": "fragment"} # To track dependencies, for every variable, we need to keep track of its _origins_ – where it obtained its value, and which tests controlled its assignments. There are two ways to do so: # # * Wrapping Data Objects # * Wrapping Data Accesses # + [markdown] slideshow={"slide_type": "subslide"} # ### Wrapping Data Objects # + [markdown] slideshow={"slide_type": "subslide"} # One way to track origins is to _wrap_ each value in a class that stores both a value and the origin of the value. If a variable `x` is initialized to zero in Line 3, for instance, we could store it as # ``` # x = (value=0, origin=<Line 3>) # ``` # and if it is copied in, say, Line 5 to another variable `y`, we could store this as # ``` # y = (value=0, origin=<Line 3, Line 5>) # ``` # Such a scheme would allow us to track origins and dependencies right within the variable. # + [markdown] slideshow={"slide_type": "subslide"} # In a language like Python, it is actually possibly to subclass from basic types. Here's how we create a `MyInt` subclass of `int`: # + slideshow={"slide_type": "fragment"} class MyInt(int): def __new__(cls, value, *args, **kwargs): return super(cls, cls).__new__(cls, value) def __repr__(self): return f"{int(self)}" # + slideshow={"slide_type": "fragment"} x = MyInt(5) # + [markdown] slideshow={"slide_type": "fragment"} # We can access `x` just like any integer: # + slideshow={"slide_type": "fragment"} x, x + 1 # + [markdown] slideshow={"slide_type": "fragment"} # However, we can also add extra attributes to it: # + slideshow={"slide_type": "fragment"} x.origin = "Line 5" # + slideshow={"slide_type": "subslide"} x.origin # + [markdown] slideshow={"slide_type": "subslide"} # Such a "wrapping" scheme has the advantage of _leaving program code untouched_ – simply pass "wrapped" objects instead of the original values. However, it also has a number of drawbacks. # # * First, we must make sure that the "wrapper" objects are still compatible with the original values – notably by converting them back whenever needed. (What happens if an internal Python function expects an `int` and gets a `MyInt` instead?) # * Second, we have to make sure that origins do not get lost during computations – which involves overloading operators such as `+`, `-`, `*`, and so on. (Right now, `MyInt(1) + 1` gives us an `int` object, not a `MyInt`.) # * Third, we have to do this for _all_ data types of a language, which is pretty tedious. # * Fourth and last, however, we want to track whenever a value is assigned to another variable. Python has no support for this, and thus our dependencies will necessarily be incomplete. # + [markdown] slideshow={"slide_type": "subslide"} # ### Wrapping Data Accesses # + [markdown] slideshow={"slide_type": "subslide"} # An alternate way of tracking origins is to _instrument_ the source code such that all _data read and write operations are tracked_. That is, the original data stays unchanged, but we change the code instead. # # In essence, for every occurrence of a variable `x` being _read_, we replace it with # # ```python # _data.get('x', x) # returns x # ``` # # and for every occurrence of a value being _written_ to `x`, we replace the value with # # ```python # _data.set('x', value) # returns value # ``` # # and let the `_data` object track these reads and writes. # # Hence, an assignment such as # # ```python # a = b + c # ``` # # would get rewritten to # # ```python # a = _data.set('a', _data.get('b', b) + _data.get('c', c)) # ``` # # and with every access to `_data`, we would track # # 1. the current _location_ in the code, and # 2. whether the respective variable was read or written. # # For the above statement, we could deduce that `b` and `c` were read, and `a` was written – which makes `a` data dependent on `b` and `c`. # + [markdown] slideshow={"slide_type": "subslide"} # The advantage of such instrumentation is that it works with _arbitrary objects_ (in Python, that is) – we do not case whether `a`, `b`, and `c` would be integers, floats, strings, lists. or any other type for which `+` would be defined. Also, the code semantics remain entirely unchanged. # # The disadvantage, however, is that it takes a bit of effort to exactly separate reads and writes into individual groups, and that a number of language features have to be handled separately. This is what we do in the remainder of this chapter. # + [markdown] slideshow={"slide_type": "slide"} # ## A Data Tracker # # To implement `_data` accesses as shown above, we introduce the `DataTracker` class. As its name suggests, it keeps track of variables being read and written, and provides methods to determine the code location where this tool place. # + slideshow={"slide_type": "fragment"} class DataTracker(object): def __init__(self, log=False): """Initialize. If `log` is set, turn on logging.""" self.log = log # + slideshow={"slide_type": "fragment"} class DataTracker(DataTracker, StackInspector): pass # + [markdown] slideshow={"slide_type": "subslide"} # `set()` is invoked when a variable is set, as in # # ```python # pi = _data.set('pi', 3.1415) # ``` # # By default, we simply log the access. # + slideshow={"slide_type": "subslide"} class DataTracker(DataTracker): def set(self, name, value, loads=None): """Track setting `name` to `value`.""" if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: setting {name}") return value # + [markdown] slideshow={"slide_type": "fragment"} # `get()` is invoked when a variable is retrieved, as in # # ```python # print(_data.get('pi', pi)) # ``` # By default, we simply log the access. # + slideshow={"slide_type": "subslide"} class DataTracker(DataTracker): def get(self, name, value): """Track getting `value` from `name`.""" if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: getting {name}") return value # + slideshow={"slide_type": "fragment"} class DataTracker(DataTracker): def __repr__(self): return super().__repr__() # + [markdown] slideshow={"slide_type": "fragment"} # Here's an example of a logging `DataTracker`: # + slideshow={"slide_type": "subslide"} _test_data = DataTracker(log=True) x = _test_data.set('x', 1) # + slideshow={"slide_type": "fragment"} _test_data.get('x', x) # + [markdown] slideshow={"slide_type": "slide"} # ## Instrumenting Source Code # # How do we transform source code such that read and write accesses to variables would be automatically rewritten? To this end, we inspect the internal representation of source code, namely the _abstract syntax trees_ (ASTs). An AST represents the code as a tree, with specific node types for each syntactical element. # + slideshow={"slide_type": "skip"} import ast import astor # + slideshow={"slide_type": "skip"} from bookutils import show_ast # + [markdown] slideshow={"slide_type": "fragment"} # Here is the tree representation for our `middle()` function. It starts with a `FunctionDef` node at the top (with the name `"middle"` and the three arguments `x`, `y`, `z` as children), followed by a subtree for each of the `If` statements, each of which contains a branch for when their condition evaluates to`True` and a branch for when their condition evaluates to `False`. # + slideshow={"slide_type": "subslide"} middle_tree = ast.parse(inspect.getsource(middle)) show_ast(middle_tree) # + [markdown] slideshow={"slide_type": "fragment"} # At the very bottom of the tree, you can see a number of `Name` nodes, referring individual variables. These are the ones we want to transform. # + [markdown] slideshow={"slide_type": "subslide"} # ### Tracking Variable Access # # Our goal is to _traverse_ the tree, identify all `Name` nodes, and convert them to respective `_data` accesses. # To this end, we manipulate the AST through the Python modules `ast` and `astor`. The [official Python `ast` reference](http://docs.python.org/3/library/ast) is complete, but a bit brief; the documentation ["Green Tree Snakes - the missing Python AST docs"](https://greentreesnakes.readthedocs.io/en/latest/) provides an excellent introduction. # + [markdown] slideshow={"slide_type": "fragment"} # The Python `ast` class provides a class `NodeTransformer` that allows such transformations. Subclassing from it, we provide a method `visit_Name()` that will be invoked for all `Name` nodes – and replace it by a new subtree from `make_get_data()`: # + slideshow={"slide_type": "skip"} from ast import NodeTransformer, NodeVisitor # + slideshow={"slide_type": "fragment"} DATA_TRACKER = '_data' # + slideshow={"slide_type": "subslide"} class TrackGetTransformer(NodeTransformer): def visit_Name(self, node): self.generic_visit(node) if node.id in dir(__builtins__): # Do not change built-in names return node if node.id == DATA_TRACKER: # Do not change own accesses return node if not isinstance(node.ctx, Load): # Only change loads (not stores, not deletions) return node new_node = make_get_data(node.id) ast.copy_location(new_node, node) return new_node # + [markdown] slideshow={"slide_type": "subslide"} # Our function `make_get_data(id, method)` returns a new subtree equivalent to the Python code `_data.method('id', id)`. # + slideshow={"slide_type": "skip"} from ast import Module, Name, Load, Store, Tuple, \ Attribute, With, withitem, keyword, Call, Expr # + slideshow={"slide_type": "fragment"} # Starting with Python 3.8, these will become Constant. # from ast import Num, Str, NameConstant # Use `ast.Num`, `ast.Str`, and `ast.NameConstant` for compatibility # + slideshow={"slide_type": "fragment"} def make_get_data(id, method='get'): return Call(func=Attribute(value=Name(id=DATA_TRACKER, ctx=Load()), attr=method, ctx=Load()), args=[ast.Str(s=id), Name(id=id, ctx=Load())], keywords=[]) # + [markdown] slideshow={"slide_type": "fragment"} # This is the tree that `make_get_data()` produces: # + slideshow={"slide_type": "fragment"} show_ast(Module(body=[make_get_data("x")])) # + [markdown] slideshow={"slide_type": "subslide"} # How do we know that this is a correct subtree? We can carefully read the [official Python `ast` reference](http://docs.python.org/3/library/ast) and then proceed by trial and error (and apply [delta debugging](DeltaDebugger.ipynb) to determine error causes). Or – pro tip! – we can simply take a piece of Python code, parse it and use `ast.dump()` to print out how to construct the resulting AST: # + slideshow={"slide_type": "fragment"} print(ast.dump(ast.parse("_data.get('x', x)"))) # + [markdown] slideshow={"slide_type": "fragment"} # If you compare the above output with the code of `make_get_data()`, above, you will find out where the source of `make_get_data()` comes from. # + [markdown] slideshow={"slide_type": "fragment"} # Let us put `TrackGetTransformer` to action. Its `visit()` method calls `visit_Name()`, which then in turn transforms the `Name` nodes as we want it. This happens in place. # + slideshow={"slide_type": "subslide"} TrackGetTransformer().visit(middle_tree); # + [markdown] slideshow={"slide_type": "fragment"} # To see the effect of our transformations, we introduce a method `dump_tree()` which outputs the tree – and also compiles it to check for any inconsistencies. # + slideshow={"slide_type": "fragment"} def dump_tree(tree): print_content(astor.to_source(tree), '.py') ast.fix_missing_locations(tree) # Must run this before compiling _ = compile(tree, '<dump_tree>', 'exec') # + [markdown] slideshow={"slide_type": "fragment"} # We see that our transformer has properly replaced all # + slideshow={"slide_type": "subslide"} dump_tree(middle_tree) # + [markdown] slideshow={"slide_type": "subslide"} # Let us now execute this code together with the `DataTracker()` class we previously introduced. The class `DataTrackerTester()` takes a (transformed) tree and a function. Using it as # # ```python # with DataTrackerTester(tree, func): # func(...) # ``` # # first executes the code in _tree_ (possibly instrumenting `func`) and then the `with` body. At the end, `func` is restored to its previous (non-instrumented) version. # + slideshow={"slide_type": "subslide"} class DataTrackerTester(object): def __init__(self, tree, func, log=True): # We pass the source file of `func` such that we can retrieve it # when accessing the location of the new compiled code self.code = compile(tree, inspect.getsourcefile(func), 'exec') self.func = func self.log = log def make_data_tracker(self): return DataTracker(log=self.log) def __enter__(self): """Rewrite function""" tracker = self.make_data_tracker() globals()[DATA_TRACKER] = tracker exec(self.code, globals()) return tracker def __exit__(self, exc_type, exc_value, traceback): """Restore function""" globals()[self.func.__name__] = self.func del globals()[DATA_TRACKER] # + [markdown] slideshow={"slide_type": "subslide"} # Here is our `middle()` function: # + slideshow={"slide_type": "fragment"} print_content(inspect.getsource(middle), '.py', start_line_number=1) # + [markdown] slideshow={"slide_type": "subslide"} # And here is our instrumented `middle_tree` executed with a `DataTracker` object. We see how the `middle()` tests access one argument after another. # + slideshow={"slide_type": "fragment"} with DataTrackerTester(middle_tree, middle): middle(2, 1, 3) # + [markdown] slideshow={"slide_type": "fragment"} # After `DataTrackerTester` is done, `middle` is reverted to its non-instrumented version: # + slideshow={"slide_type": "subslide"} middle(2, 1, 3) # + [markdown] slideshow={"slide_type": "fragment"} # For a complete picture of what happens during executions, we implement a number of additional code transformers. # + [markdown] slideshow={"slide_type": "fragment"} # For each assignment statement `x = y`, we change it to `x = _data.set('x', y)`. This allows to __track assignments__. # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Tracking Assignments # + [markdown] slideshow={"slide_type": "fragment"} # For the remaining transformers, we follow the same steps as for `TrackGetTransformer`, except that our `visit_...()` methods focus on different nodes, and return different subtrees. Here, we focus on assignment nodes. # + [markdown] slideshow={"slide_type": "fragment"} # We want to transform assignments `x = value` into `_data.set('x', value)` to track assignments to `x`. # + [markdown] slideshow={"slide_type": "fragment"} # If the left hand side of the assignment is more complex, as in `x[y] = value`, we want to ensure the read access to `x` and `y` is also tracked. By transforming `x[y] = value` into `_data.set('x', value, loads=(x, y))`, we ensure that `x` and `y` are marked as read (as the otherwise ignored `loads` argument would be changed to `_data.get()` calls for `x` and `y`). # + [markdown] slideshow={"slide_type": "fragment"} # Using `ast.dump()`, we reveal what the corresponding syntax tree has to look like: # + slideshow={"slide_type": "subslide"} print(ast.dump(ast.parse("_data.set('x', value, loads=(a, b))"))) # + [markdown] slideshow={"slide_type": "fragment"} # Using this structure, we can write a function `make_set_data()` which constructs such a subtree. # + slideshow={"slide_type": "subslide"} def make_set_data(id, value, loads=None, method='set'): """Construct a subtree _data.`method`('`id`', `value`). If `loads` is set to [X1, X2, ...], make it _data.`method`('`id`', `value`, loads=(X1, X2, ...)) """ keywords=[] if loads: keywords = [ keyword(arg='loads', value=Tuple( elts=[Name(id=load, ctx=Load()) for load in loads], ctx=Load() )) ] new_node = Call(func=Attribute(value=Name(id=DATA_TRACKER, ctx=Load()), attr=method, ctx=Load()), args=[ast.Str(s=id), value], keywords=keywords) ast.copy_location(new_node, value) return new_node # + [markdown] slideshow={"slide_type": "subslide"} # The problem is, however: How do we get the name of the variable being assigned to? The left hand side of an assignment can be a complex expression such as `x[i]`. We use the leftmost name of the left hand side as name to be assigned to. # + slideshow={"slide_type": "subslide"} class LeftmostNameVisitor(NodeVisitor): def __init__(self): super().__init__() self.leftmost_name = None def visit_Name(self, node): if self.leftmost_name is None: self.leftmost_name = node.id self.generic_visit(node) def leftmost_name(tree): visitor = LeftmostNameVisitor() visitor.visit(tree) return visitor.leftmost_name # + slideshow={"slide_type": "subslide"} leftmost_name(ast.parse('a[x] = 25')) # + [markdown] slideshow={"slide_type": "fragment"} # Python also allows _tuple assignments_, as in `(a, b, c) = (1, 2, 3)`. We extract all variables being stored (that is, expressions whose `ctx` attribute is `Store()`) and extract their (leftmost) names. # + slideshow={"slide_type": "subslide"} class StoreVisitor(NodeVisitor): def __init__(self): super().__init__() self.names = set() def visit(self, node): if hasattr(node, 'ctx') and isinstance(node.ctx, Store): name = leftmost_name(node) if name is not None: self.names.add(name) self.generic_visit(node) def store_names(tree): visitor = StoreVisitor() visitor.visit(tree) return visitor.names # + slideshow={"slide_type": "subslide"} store_names(ast.parse('a[x], b[y], c = 1, 2, 3')) # + [markdown] slideshow={"slide_type": "fragment"} # For complex assignments, we also want to access the names read in the left hand side of an expression. # + slideshow={"slide_type": "subslide"} class LoadVisitor(NodeVisitor): def __init__(self): super().__init__() self.names = set() def visit(self, node): if hasattr(node, 'ctx') and isinstance(node.ctx, Load): name = leftmost_name(node) if name is not None: self.names.add(name) self.generic_visit(node) def load_names(tree): visitor = LoadVisitor() visitor.visit(tree) return visitor.names # + slideshow={"slide_type": "subslide"} load_names(ast.parse('a[x], b[y], c = 1, 2, 3')) # + [markdown] slideshow={"slide_type": "fragment"} # With this, we can now define `TrackSetTransformer` as a transformer for regular assignments. Note that in Python, an assignment can have multiple targets, as in `a = b = c`; we assign the data dependencies of `c` to them all. # + slideshow={"slide_type": "subslide"} class TrackSetTransformer(NodeTransformer): def visit_Assign(self, node): value = astor.to_source(node.value) if value.startswith(DATA_TRACKER + '.set'): return node # Do not apply twice for target in node.targets: loads = load_names(target) for store_name in store_names(target): node.value = make_set_data(store_name, node.value, loads=loads) loads = set() return node # + [markdown] slideshow={"slide_type": "subslide"} # The special form of "augmented assign" needs special treatment. We change statements of the form `x += y` to `x += _data.augment('x', y)`. # + slideshow={"slide_type": "fragment"} class TrackSetTransformer(TrackSetTransformer): def visit_AugAssign(self, node): value = astor.to_source(node.value) if value.startswith(DATA_TRACKER): return node # Do not apply twice id = leftmost_name(node.target) node.value = make_set_data(id, node.value, method='augment') return node # + [markdown] slideshow={"slide_type": "fragment"} # The corresponding `augment()` method uses a combination of `set()` and `get()` to reflect the semantics. # + slideshow={"slide_type": "subslide"} class DataTracker(DataTracker): def augment(self, name, value): """Track augmenting `name` with `value`.""" self.set(name, self.get(name, value)) return value # + [markdown] slideshow={"slide_type": "fragment"} # Here's both of these transformers in action. Our original function has a number of assignments: # + slideshow={"slide_type": "fragment"} def assign_test(x): fourty_two = forty_two = 42 a, b, c = 1, 2, 3 c[d[x]].attr = 47 foo *= bar + 1 # + slideshow={"slide_type": "fragment"} assign_tree = ast.parse(inspect.getsource(assign_test)) # + slideshow={"slide_type": "subslide"} TrackSetTransformer().visit(assign_tree) dump_tree(assign_tree) # + [markdown] slideshow={"slide_type": "fragment"} # If we later apply our transformer for data accesses, we can see that we track all variable reads and writes. # + slideshow={"slide_type": "subslide"} TrackGetTransformer().visit(assign_tree) dump_tree(assign_tree) # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "fragment"} # Each return statement `return x` is transformed to `return _data.set('<return_value>', x)`. This allows to __track return values__. # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Tracking Return Values # + [markdown] slideshow={"slide_type": "fragment"} # Our `TrackReturnTransformer` also makes use of `make_set_data()`. # + slideshow={"slide_type": "subslide"} class TrackReturnTransformer(NodeTransformer): def __init__(self): self.function_name = None super().__init__() def visit_FunctionDef(self, node): outer_name = self.function_name self.function_name = node.name # Save current name self.generic_visit(node) self.function_name = outer_name return node def visit_AsyncFunctionDef(self, node): return self.visit_FunctionDef(node) def return_value(self, tp="return"): if self.function_name is None: return f"<{tp} value>" else: return f"<{self.function_name}() {tp} value>" def visit_return_or_yield(self, node, tp="return"): if node.value is not None: value = astor.to_source(node.value) if not value.startswith(DATA_TRACKER + '.set'): node.value = make_set_data(self.return_value(tp), node.value) return node def visit_Return(self, node): return self.visit_return_or_yield(node, tp="return") def visit_Yield(self, node): return self.visit_return_or_yield(node, tp="yield") def visit_YieldFrom(self, node): return self.visit_return_or_yield(node, tp="yield") # + [markdown] slideshow={"slide_type": "subslide"} # This is the effect of `TrackReturnTransformer`. We see that all return values are saved, and thus all locations of the corresponding return statements are tracked. # + slideshow={"slide_type": "subslide"} TrackReturnTransformer().visit(middle_tree) dump_tree(middle_tree) # + slideshow={"slide_type": "subslide"} with DataTrackerTester(middle_tree, middle): middle(2, 1, 3) # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "subslide"} # To track __control dependencies__, for every block controlled by an `if`, `while`, or `for`: # # 1. We wrap their tests in a `_data.test()` wrapper. This allows us to assign pseudo-variables like `<test>` which hold the conditions. # 2. We wrap their controlled blocks in a `with` statement. This allows us to track the variables read right before the `with` (= the controlling variables), and to restore the current controlling variables when the block is left. # # A statement # # ```python # if cond: # body # ``` # # thus becomes # # ```python # if _data.test(cond): # with _data: # body # ``` # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Tracking Control # + [markdown] slideshow={"slide_type": "fragment"} # To modify control statements, we traverse the tree, looking for `If` nodes: # + slideshow={"slide_type": "fragment"} class TrackControlTransformer(NodeTransformer): def visit_If(self, node): self.generic_visit(node) node.test = self.make_test(node.test) node.body = self.make_with(node.body) node.orelse = self.make_with(node.orelse) return node # + [markdown] slideshow={"slide_type": "fragment"} # The subtrees come from helper functions `make_with()` and `make_test()`. Again, all these subtrees are obtained via `ast.dump()`. # + slideshow={"slide_type": "subslide"} class TrackControlTransformer(TrackControlTransformer): def make_with(self, block): """Create a subtree 'with _data: `block`'""" if len(block) == 0: return [] block_as_text = astor.to_source(block[0]) if block_as_text.startswith('with ' + DATA_TRACKER): return block # Do not apply twice new_node = With( items=[ withitem( context_expr=Name(id=DATA_TRACKER, ctx=Load()), optional_vars=None) ], body=block ) ast.copy_location(new_node, block[0]) return [new_node] # + slideshow={"slide_type": "subslide"} class TrackControlTransformer(TrackControlTransformer): def make_test(self, test): test_as_text = astor.to_source(test) if test_as_text.startswith(DATA_TRACKER + '.test'): return test # Do not apply twice new_test = Call(func=Attribute(value=Name(id=DATA_TRACKER, ctx=Load()), attr='test', ctx=Load()), args=[test], keywords=[]) ast.copy_location(new_test, test) return new_test # + [markdown] slideshow={"slide_type": "fragment"} # `while` loops are handled just like `if` constructs. # + slideshow={"slide_type": "subslide"} class TrackControlTransformer(TrackControlTransformer): def visit_While(self, node): self.generic_visit(node) node.test = self.make_test(node.test) node.body = self.make_with(node.body) node.orelse = self.make_with(node.orelse) return node # + [markdown] slideshow={"slide_type": "fragment"} # `for` loops gets a different treatment, as there is no condition that would control the body. Still, we ensure that setting the iterator variable is properly tracked. # + slideshow={"slide_type": "subslide"} class TrackControlTransformer(TrackControlTransformer): # regular `for` loop def visit_For(self, node): self.generic_visit(node) id = astor.to_source(node.target).strip() node.iter = make_set_data(id, node.iter) # Uncomment if you want iterators to control their bodies # node.body = self.make_with(node.body) # node.orelse = self.make_with(node.orelse) return node # `for` loops in async functions def visit_AsyncFor(self, node): return self.visit_For(node) # `for` clause in comprehensions def visit_comprehension(self, node): self.generic_visit(node) id = astor.to_source(node.target).strip() node.iter = make_set_data(id, node.iter) return node # + [markdown] slideshow={"slide_type": "subslide"} # Here is the effect of `TrackControlTransformer`: # + slideshow={"slide_type": "subslide"} TrackControlTransformer().visit(middle_tree) dump_tree(middle_tree) # + [markdown] slideshow={"slide_type": "subslide"} # We extend `DataTracker` to also log these events: # + slideshow={"slide_type": "fragment"} class DataTracker(DataTracker): def test(self, cond): if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: testing condition") return cond # + slideshow={"slide_type": "subslide"} class DataTracker(DataTracker): def __enter__(self): if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: entering block") def __exit__(self, exc_type, exc_value, traceback): if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: exiting block") # + slideshow={"slide_type": "subslide"} with DataTrackerTester(middle_tree, middle): middle(2, 1, 3) # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "subslide"} # We also want to be able to __track calls__ across multiple functions. To this end, we wrap each call # # ```python # func(arg1, arg2, ...) # ``` # # into # # ```python # _data.ret(_data.call(func)(_data.arg(arg1), _data.arg(arg2), ...)) # ``` # # each of which simply pass through their given argument, but which allow to track the beginning of calls (`call()`), the computation of arguments (`arg()`), and the return of the call (`ret()`), respectively. # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Tracking Calls and Arguments # + [markdown] slideshow={"slide_type": "fragment"} # Our `TrackCallTransformer` visits all `Call` nodes, applying the transformations as shown above. # + slideshow={"slide_type": "subslide"} class TrackCallTransformer(NodeTransformer): def make_call(self, node, func, pos=None, kw=None): """Return _data.call(`func`)(`node`)""" keywords = [] # `Num()` and `Str()` are deprecated in favor of `Constant()` if pos: keywords.append(keyword(arg='pos', value=ast.Num(pos))) if kw: keywords.append(keyword(arg='kw', value=ast.Str(kw))) return Call(func=Attribute(value=Name(id=DATA_TRACKER, ctx=Load()), attr=func, ctx=Load()), args=[node], keywords=keywords) def visit_Call(self, node): self.generic_visit(node) call_as_text = astor.to_source(node) if call_as_text.startswith(DATA_TRACKER + '.ret'): return node # Already applied func_as_text = astor.to_source(node) if func_as_text.startswith(DATA_TRACKER + '.'): return node # Own function new_args = [] for n, arg in enumerate(node.args): new_args.append(self.make_call(arg, 'arg', pos=n + 1)) node.args = new_args for kw in node.keywords: id = kw.arg if hasattr(kw, 'arg') else None kw.value = self.make_call(kw.value, 'arg', kw=id) node.func = self.make_call(node.func, 'call') return self.make_call(node, 'ret') # + [markdown] slideshow={"slide_type": "subslide"} # Our example function `middle()` does not contain any calls, but here is a function that invokes `middle()` twice: # + slideshow={"slide_type": "fragment"} def test_call(): x = middle(1, 2, z=middle(1, 2, 3)) return x # + slideshow={"slide_type": "fragment"} call_tree = ast.parse(inspect.getsource(test_call)) dump_tree(call_tree) # + [markdown] slideshow={"slide_type": "fragment"} # If we invoke `TrackCallTransformer` on this testing function, we get the following transformed code: # + slideshow={"slide_type": "fragment"} TrackCallTransformer().visit(call_tree); # + slideshow={"slide_type": "subslide"} dump_tree(call_tree) # + slideshow={"slide_type": "fragment"} def f(): return math.isclose(1, 1.0) # + slideshow={"slide_type": "fragment"} f_tree = ast.parse(inspect.getsource(f)) dump_tree(f_tree) # + slideshow={"slide_type": "fragment"} TrackCallTransformer().visit(f_tree); # + slideshow={"slide_type": "subslide"} dump_tree(f_tree) # + [markdown] slideshow={"slide_type": "fragment"} # As before, our default `arg()`, `ret()`, and `call()` methods simply log the event and pass through the given value. # + slideshow={"slide_type": "subslide"} class DataTracker(DataTracker): def arg(self, value, pos=None, kw=None): if self.log: caller_func, lineno = self.caller_location() info = "" if pos: info += f" #{pos}" if kw: info += f" {repr(kw)}" print(f"{caller_func.__name__}:{lineno}: pushing arg{info}") return value # + slideshow={"slide_type": "subslide"} class DataTracker(DataTracker): def ret(self, value): if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: returned from call") return value # + slideshow={"slide_type": "fragment"} class DataTracker(DataTracker): def call(self, func): if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: calling {func}") return func # + slideshow={"slide_type": "subslide"} dump_tree(call_tree) # + slideshow={"slide_type": "subslide"} with DataTrackerTester(call_tree, test_call): test_call() # + slideshow={"slide_type": "fragment"} test_call() # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "fragment"} # On the receiving end, for each function argument `x`, we insert a call `_data.param('x', x, [position info])` to initialize `x`. This is useful for __tracking parameters across function calls.__ # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Tracking Parameters # + [markdown] slideshow={"slide_type": "fragment"} # Again, we use `ast.dump()` to determine the correct syntax tree: # + slideshow={"slide_type": "fragment"} print(ast.dump(ast.parse("_data.param('x', x, pos=1, last=True)"))) # + slideshow={"slide_type": "subslide"} class TrackParamsTransformer(NodeTransformer): def visit_FunctionDef(self, node): self.generic_visit(node) named_args = [] for child in ast.iter_child_nodes(node.args): if isinstance(child, ast.arg): named_args.append(child) create_stmts = [] for n, child in enumerate(named_args): keywords=[keyword(arg='pos', value=ast.Num(n=n + 1))] if child is node.args.vararg: keywords.append(keyword(arg='vararg', value=ast.Str(s='*'))) if child is node.args.kwarg: keywords.append(keyword(arg='vararg', value=ast.Str(s='**'))) if n == len(named_args) - 1: keywords.append(keyword(arg='last', value=ast.NameConstant(value=True))) create_stmt = Expr( value=Call( func=Attribute(value=Name(id=DATA_TRACKER, ctx=Load()), attr='param', ctx=Load()), args=[ast.Str(s=child.arg), Name(id=child.arg, ctx=Load()) ], keywords=keywords ) ) ast.copy_location(create_stmt, node) create_stmts.append(create_stmt) node.body = create_stmts + node.body return node # + [markdown] slideshow={"slide_type": "subslide"} # This is the effect of `TrackParamsTransformer()`. You see how the first three parameters are all initialized. # + slideshow={"slide_type": "subslide"} TrackParamsTransformer().visit(middle_tree) dump_tree(middle_tree) # + [markdown] slideshow={"slide_type": "subslide"} # By default, the `DataTracker` `param()` method simply calls `set()` to set variables. # + slideshow={"slide_type": "fragment"} class DataTracker(DataTracker): def param(self, name, value, pos=None, vararg="", last=False): if self.log: caller_func, lineno = self.caller_location() info = "" if pos is not None: info += f" #{pos}" print(f"{caller_func.__name__}:{lineno}: initializing {vararg}{name}{info}") return self.set(name, value) # + slideshow={"slide_type": "subslide"} with DataTrackerTester(middle_tree, middle): middle(2, 1, 3) # + slideshow={"slide_type": "subslide"} def args_test(x, *args, **kwargs): print(x, *args, **kwargs) # + slideshow={"slide_type": "fragment"} args_tree = ast.parse(inspect.getsource(args_test)) TrackParamsTransformer().visit(args_tree) dump_tree(args_tree) # + slideshow={"slide_type": "subslide"} with DataTrackerTester(args_tree, args_test): args_test(1, 2, 3) # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "fragment"} # What do we obtain after we have applied all these transformers on `middle()`? We see that the code now contains quite a load of instrumentation. # + slideshow={"slide_type": "subslide"} dump_tree(middle_tree) # + [markdown] slideshow={"slide_type": "subslide"} # And when we execute this code, we see that we can track quite a number of events, while the code semantics stay unchanged. # + slideshow={"slide_type": "subslide"} with DataTrackerTester(middle_tree, middle): m = middle(2, 1, 3) m # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Transformer Stress Test # + [markdown] slideshow={"slide_type": "fragment"} # We stress test our transformers by instrumenting, transforming, and compiling a number of modules. # + slideshow={"slide_type": "skip"} import Assertions # minor dependency import Debugger # minor dependency # + slideshow={"slide_type": "subslide"} for module in [Assertions, Debugger, inspect, ast, astor]: module_tree = ast.parse(inspect.getsource(module)) TrackCallTransformer().visit(module_tree) TrackSetTransformer().visit(module_tree) TrackGetTransformer().visit(module_tree) TrackControlTransformer().visit(module_tree) TrackReturnTransformer().visit(module_tree) TrackParamsTransformer().visit(module_tree) # dump_tree(module_tree) ast.fix_missing_locations(module_tree) # Must run this before compiling module_code = compile(module_tree, '<stress_test>', 'exec') print(f"{repr(module.__name__)} instrumented successfully.") # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "fragment"} # Our next step will now be not only to _log_ these events, but to actually construct _dependencies_ from them. # + [markdown] slideshow={"slide_type": "slide"} # ## Tracking Dependencies # + [markdown] slideshow={"slide_type": "fragment"} # To construct dependencies from variable accesses, we subclass `DataTracker` into `DependencyTracker` – a class that actually keeps track of all these dependencies. Its constructor initializes a number of variables we will discuss below. # + slideshow={"slide_type": "subslide"} class DependencyTracker(DataTracker): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.origins = {} # Where current variables were last set self.data_dependencies = {} # As with Dependencies, above self.control_dependencies = {} self.last_read = [] # List of last read variables self.last_checked_location = (StackInspector.unknown, 1) self._ignore_location_change = False self.data = [[]] # Data stack self.control = [[]] # Control stack self.frames = [{}] # Argument stack self.args = {} # Current args # + [markdown] slideshow={"slide_type": "subslide"} # ### Data Dependencies # # The first job of our `DependencyTracker` is to construct dependencies between _read_ and _written_ variables. # + [markdown] slideshow={"slide_type": "subslide"} # #### Reading Variables # # As in `DataTracker`, the key method of `DependencyTracker` again is `get()`, invoked as `_data.get('x', x)` whenever a variable `x` is read. First and foremost, it appends the name of the read variable to the list `last_read`. # + slideshow={"slide_type": "fragment"} class DependencyTracker(DependencyTracker): def get(self, name, value): """Track a read access for variable `name` with value `value`""" self.check_location() self.last_read.append(name) return super().get(name, value) def check_location(self): pass # More on that below # + slideshow={"slide_type": "subslide"} x = 5 y = 3 # + slideshow={"slide_type": "fragment"} _test_data = DependencyTracker(log=True) _test_data.get('x', x) + _test_data.get('y', y) # + slideshow={"slide_type": "fragment"} _test_data.last_read # + [markdown] slideshow={"slide_type": "subslide"} # #### Checking Locations # + [markdown] slideshow={"slide_type": "fragment"} # However, before appending the read variable to `last_read`, `_data.get()` does one more thing. By invoking `check_location()`, it clears the `last_read` list if we have reached a new line in the execution. This avoids situations such as # # ```python # x # y # z = a + b # ``` # where `x` and `y` are, well, read, but do not affect the last line. Therefore, with every new line, the list of last read lines is cleared. # + slideshow={"slide_type": "subslide"} class DependencyTracker(DependencyTracker): def clear_read(self): """Clear set of read variables""" if self.log: direct_caller = inspect.currentframe().f_back.f_code.co_name caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: " f"clearing read variables {self.last_read} " f"(from {direct_caller})") self.last_read = [] def check_location(self): """If we are in a new location, clear set of read variables""" location = self.caller_location() func, lineno = location last_func, last_lineno = self.last_checked_location if self.last_checked_location != location: if self._ignore_location_change: self._ignore_location_change = False elif func.__name__.startswith('<'): # Entering list comprehension, eval(), exec(), ... pass elif last_func.__name__.startswith('<'): # Exiting list comprehension, eval(), exec(), ... pass else: # Standard case self.clear_read() self.last_checked_location = location # + [markdown] slideshow={"slide_type": "subslide"} # Two methods can suppress this reset of the `last_read` list: # # * `ignore_next_location_change()` suppresses the reset for the next line. This is useful when returning from a function, when the return value is still in the list of "read" variables. # * `ignore_location_change()` suppresses the reset for the current line. This is useful if we already have returned from a function call. # + slideshow={"slide_type": "fragment"} class DependencyTracker(DependencyTracker): def ignore_next_location_change(self): self._ignore_location_change = True def ignore_location_change(self): self.last_checked_location = self.caller_location() # + [markdown] slideshow={"slide_type": "subslide"} # Watch how `DependencyTracker` resets `last_read` when a new line is executed: # + slideshow={"slide_type": "fragment"} _test_data = DependencyTracker() # + slideshow={"slide_type": "fragment"} _test_data.get('x', x) + _test_data.get('y', y) # + slideshow={"slide_type": "fragment"} _test_data.last_read # + slideshow={"slide_type": "fragment"} a = 42 b = -1 _test_data.get('a', a) + _test_data.get('b', b) # + slideshow={"slide_type": "fragment"} _test_data.last_read # + [markdown] slideshow={"slide_type": "subslide"} # #### Setting Variables # # The method `set()` creates dependencies. It is invoked as `_data.set('x', value)` whenever a variable `x` is set. # # First and foremost, it takes the list of variables read `last_read`, and for each of the variables $v$, it takes their origin $o$ (the place where they were last set) and appends the pair ($v$, $o$) to the list of data dependencies. It then does a similar thing with control dependencies (more on these below), and finally marks (in `self.origins`) the current location of $v$. # + slideshow={"slide_type": "skip"} import itertools # + slideshow={"slide_type": "subslide"} class DependencyTracker(DependencyTracker): TEST = '<test>' def set(self, name, value, loads=None): """Add a dependency for `name` = `value`""" def add_dependencies(dependencies, vars_read, tp): """Add origins of `vars_read` to `dependencies`.""" for var_read in vars_read: if var_read in self.origins: if var_read == self.TEST and tp == "data": # Can't have data dependencies on conditions continue origin = self.origins[var_read] dependencies.add((var_read, origin)) if self.log: origin_func, origin_lineno = origin caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: " f"new {tp} dependency: " f"{name} <= {var_read} " f"({origin_func.__name__}:{origin_lineno})") self.check_location() ret = super().set(name, value) location = self.caller_location() add_dependencies(self.data_dependencies.setdefault ((name, location), set()), self.last_read, tp="data") add_dependencies(self.control_dependencies.setdefault ((name, location), set()), itertools.chain.from_iterable(self.control), tp="control") self.origins[name] = location # Reset read info for next line self.last_read = [name] return ret def dependencies(self): """Return dependencies""" return Dependencies(self.data_dependencies, self.control_dependencies) # + [markdown] slideshow={"slide_type": "subslide"} # Let us illustrate `set()` by example. Here's a set of variables read and written: # + slideshow={"slide_type": "fragment"} _test_data = DependencyTracker() x = _test_data.set('x', 1) y = _test_data.set('y', _test_data.get('x', x)) z = _test_data.set('z', _test_data.get('x', x) + _test_data.get('y', y)) # + [markdown] slideshow={"slide_type": "fragment"} # The attribute `origins` saves for each variable where it was last written: # + slideshow={"slide_type": "fragment"} _test_data.origins # + [markdown] slideshow={"slide_type": "fragment"} # The attribute `data_dependencies` tracks for each variable the variables it was read from: # + slideshow={"slide_type": "subslide"} _test_data.data_dependencies # + [markdown] slideshow={"slide_type": "fragment"} # Hence, the above code already gives us a small dependency graph: # + slideshow={"slide_type": "fragment"} # ignore _test_data.dependencies().graph() # + [markdown] slideshow={"slide_type": "subslide"} # In the remainder of this section, we define methods to # # * track control dependencies (`test()`, `__enter__()`, `__exit__()`) # * track function calls and returns (`call()`, `ret()`) # * track function arguments (`arg()`, `param()`) # * check the validity of our dependencies (`validate()`). # # Like our `get()` and `set()` methods above, these work by refining the appropriate methods defined in the `DataTracker` class, building on our `NodeTransformer` transformations. # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Control Dependencies # + [markdown] slideshow={"slide_type": "fragment"} # Let us detail control dependencies. As discussed with `DataTracker()`, we invoke `test()` methods for all control conditions, and place the controlled blocks into `with` clauses. # + [markdown] slideshow={"slide_type": "fragment"} # The `test()` method simply sets a `<test>` variable; this also places it in `last_read`. # + slideshow={"slide_type": "fragment"} class DependencyTracker(DependencyTracker): def test(self, value): """Track a test for condition `value`""" self.set(self.TEST, value) return super().test(value) # + [markdown] slideshow={"slide_type": "fragment"} # When entering a `with` block, the set of `last_read` variables holds the `<test>` variable read. We save it in the `control` stack, with the effect of any further variables written now being marked as controlled by `<test>`. # + slideshow={"slide_type": "subslide"} class DependencyTracker(DependencyTracker): def __enter__(self): """Track entering an if/while/for block""" self.control.append(self.last_read) self.clear_read() super().__enter__() # + [markdown] slideshow={"slide_type": "fragment"} # When we exit the `with` block, we restore earlier `last_read` values, preparing for `else` blocks. # + slideshow={"slide_type": "fragment"} class DependencyTracker(DependencyTracker): def __exit__(self, exc_type, exc_value, traceback): """Track exiting an if/while/for block""" self.clear_read() self.last_read = self.control.pop() self.ignore_next_location_change() super().__exit__(exc_type, exc_value, traceback) # + [markdown] slideshow={"slide_type": "subslide"} # Here's an example of all these parts in action: # + slideshow={"slide_type": "fragment"} _test_data = DependencyTracker() x = _test_data.set('x', 1) y = _test_data.set('y', _test_data.get('x', x)) # + slideshow={"slide_type": "fragment"} if _test_data.test(_test_data.get('x', x) >= _test_data.get('y', y)): with _test_data: z = _test_data.set('z', _test_data.get('x', x) + _test_data.get('y', y)) # + slideshow={"slide_type": "fragment"} _test_data.control_dependencies # + [markdown] slideshow={"slide_type": "subslide"} # The control dependency for `z` is reflected in the dependency graph: # + slideshow={"slide_type": "fragment"} # ignore _test_data.dependencies() # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Calls and Returns # + [markdown] slideshow={"slide_type": "fragment"} # To handle complex expressions involving functions, we introduce a _data stack_. Every time we invoke a function `func` (`call()` is invoked), we save the list of current variables read `last_read` on the `data` stack; when we return (`ret()` is invoked), we restore `last_read`. This also ensures that only those variables read while evaluating arguments will flow into the function call. # + slideshow={"slide_type": "subslide"} class DependencyTracker(DependencyTracker): def call(self, func): """Track a call of function `func`""" super().call(func) if inspect.isgeneratorfunction(func): return self.call_generator(func) # Save context if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: " f"saving read variables {self.last_read}") self.data.append(self.last_read) self.clear_read() self.ignore_next_location_change() self.frames.append(self.args) self.args = {} return func # + slideshow={"slide_type": "subslide"} class DependencyTracker(DependencyTracker): def ret(self, value): """Track a function return""" super().ret(value) if self.in_generator(): return self.ret_generator(value) # Restore old context and add return value ret_name = None for var in self.last_read: if var.startswith("<"): # "<return value>" ret_name = var self.last_read = self.data.pop() if ret_name is not None: self.last_read.append(ret_name) self.ignore_location_change() self.args = self.frames.pop() if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: " f"restored read variables {self.last_read}") return value # + [markdown] slideshow={"slide_type": "subslide"} # Generator functions (those which `yield` a value) are not "called" in the sense that Python transfers control to them; instead, a "call" to a generator function creates a generator that is evaluated on demand. We mark generator function "calls" by saving `None` on the stacks. When the generator function returns the generator, we wrap the generator such that the arguments are being restored when it is invoked. # + slideshow={"slide_type": "skip"} import copy # + slideshow={"slide_type": "subslide"} class DependencyTracker(DependencyTracker): def in_generator(self): """True if we are calling a generator function""" return len(self.data) > 0 and self.data[-1] is None def call_generator(self, func): """Track a call of a generator function""" # Mark the fact that we're in a generator with `None` values self.data.append(None) self.frames.append(None) assert self.in_generator() self.clear_read() return func def ret_generator(self, generator): """Track the return of a generator function""" # Pop the two 'None' values pushed earlier self.data.pop() self.frames.pop() if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: " f"wrapping generator {generator} (args={self.args})") # At this point, we already have collected the args. # The returned generator depends on all of them. for arg in self.args: self.last_read += self.args[arg] # Wrap the generator such that the args are restored # when it is actually invoked, such that we can map them # to parameters. saved_args = copy.deepcopy(self.args) def wrapper(): self.args = saved_args if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: " f"calling generator (args={self.args})") self.ignore_next_location_change() yield from generator return wrapper() # + [markdown] slideshow={"slide_type": "subslide"} # We see an example of how function calls and returns work in conjunction with function arguments, discussed in the next section. # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Function Arguments # + [markdown] slideshow={"slide_type": "fragment"} # Finally, we handle parameters and arguments. The `args` stack holds the current stack of function arguments, holding the `last_read` variable for each argument. # + slideshow={"slide_type": "subslide"} class DependencyTracker(DependencyTracker): def arg(self, value, pos=None, kw=None): """Track passing an argument `value` (with given position `pos` 1..n or keyword `kw`)""" if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: " f"saving args read {self.last_read}") if pos: self.args[pos] = self.last_read if kw: self.args[kw] = self.last_read self.clear_read() return super().arg(value, pos, kw) # + [markdown] slideshow={"slide_type": "subslide"} # When accessing the arguments (with `param()`), we can retrieve this set of read variables for each argument. # + slideshow={"slide_type": "subslide"} class DependencyTracker(DependencyTracker): def param(self, name, value, pos=None, vararg="", last=False): """Track getting a parameter `name` with value `value` (with given position `pos`). vararg parameters are indicated by setting `varargs` to '*' (*args) or '**' (**kwargs)""" self.clear_read() if vararg == '*': # We overapproximate by setting `args` to _all_ positional args for index in self.args: if isinstance(index, int) and index >= pos: self.last_read += self.args[index] elif vararg == '**': # We overapproximate by setting `kwargs` to _all_ passed keyword args for index in self.args: if isinstance(index, str): self.last_read += self.args[index] elif name in self.args: self.last_read = self.args[name] elif pos in self.args: self.last_read = self.args[pos] if self.log: caller_func, lineno = self.caller_location() print(f"{caller_func.__name__}:{lineno}: " f"restored params read {self.last_read}") self.ignore_location_change() ret = super().param(name, value, pos) if last: self.clear_read() return ret # + [markdown] slideshow={"slide_type": "subslide"} # Let us illustrate all these on a small example. # + slideshow={"slide_type": "subslide"} def call_test(): c = 47 def sq(n): return n * n def gen(e): yield e * c def just_x(x, y): return x a = 42 b = gen(a) d = list(b)[0] xs = [1, 2, 3, 4] ys = [sq(elem) for elem in xs if elem > 2] return just_x(just_x(d, y=b), ys[0]) # + slideshow={"slide_type": "subslide"} call_test() # + [markdown] slideshow={"slide_type": "fragment"} # We apply all our transformers on this code: # + slideshow={"slide_type": "subslide"} call_tree = ast.parse(inspect.getsource(call_test)) TrackCallTransformer().visit(call_tree) TrackSetTransformer().visit(call_tree) TrackGetTransformer().visit(call_tree) TrackControlTransformer().visit(call_tree) TrackReturnTransformer().visit(call_tree) TrackParamsTransformer().visit(call_tree) dump_tree(call_tree) # + [markdown] slideshow={"slide_type": "subslide"} # Again, we capture the dependencies: # + slideshow={"slide_type": "fragment"} class DependencyTrackerTester(DataTrackerTester): def make_data_tracker(self): return DependencyTracker(log=self.log) # + slideshow={"slide_type": "fragment"} with DependencyTrackerTester(call_tree, call_test, log=False) as call_deps: call_test() # + [markdown] slideshow={"slide_type": "fragment"} # We see how # # * `a` flows into the generator `b` and into the parameter `e` of `gen()`. # * `xs` flows into `elem` which in turn flows into the parameter `n` of `sq()`. Both flow into `ys`. # * `just_x()` returns only its `x` argument. # + slideshow={"slide_type": "subslide"} call_deps.dependencies() # + [markdown] slideshow={"slide_type": "subslide"} # The `code()` view lists each function separately: # + slideshow={"slide_type": "subslide"} call_deps.dependencies().code() # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "subslide"} # ### Excursion: Diagnostics # + [markdown] slideshow={"slide_type": "fragment"} # To check the dependencies we obtain, we perform some minimal checks on whether a referenced variable actually also occurs in the source code. # + slideshow={"slide_type": "skip"} import re # + ipub={"ignore": true} slideshow={"slide_type": "subslide"} class Dependencies(Dependencies): def validate(self): """Perform a simple syntactic validation of dependencies""" super().validate() for var in self.all_vars(): source = self.source(var) if not source: continue if source.startswith('<'): continue # no source for dep_var in self.data[var] | self.control[var]: dep_name, dep_location = dep_var if dep_name == DependencyTracker.TEST: continue # dependency on <test> if dep_name.endswith(' value>'): if source.find('(') < 0: warnings.warn(f"Warning: {self.format_var(var)} " f"depends on {self.format_var(dep_var)}, " f"but {repr(source)} does not " f"seem to have a call") continue if source.startswith('def'): continue # function call rx = re.compile(r'\b' + dep_name + r'\b') if rx.search(source) is None: warnings.warn(f"{self.format_var(var)} " f"depends on {self.format_var(dep_var)}, " f"but {repr(dep_name)} does not occur " f"in {repr(source)}") # + [markdown] slideshow={"slide_type": "subslide"} # `validate()` is automatically called whenever dependencies are output, so if you see any of its error messages, something may be wrong. # + [markdown] slideshow={"slide_type": "subslide"} # ### End of Excursion # + [markdown] slideshow={"slide_type": "fragment"} # At this point, `DependencyTracker` is complete; we have all in place to track even complex dependencies in instrumented code. # + [markdown] slideshow={"slide_type": "slide"} # ## Slicing Code # + [markdown] slideshow={"slide_type": "subslide"} # Let us now put all these pieces together. We have a means to instrument the source code (our various `NodeTransformer` classes) and a means to track dependencies (the `DependencyTracker` class). Now comes the time to put all these things together in a single tool, which we call `Slicer`. # # The basic idea of `Slicer` is that you can use it as follows: # # ```python # with Slicer(func_1, func_2, ...) as slicer: # func(...) # ``` # # which first _instruments_ the functions given in the constructor (i.e., replaces their definitions with instrumented counterparts), and then runs the code in the body, calling instrumented functions, and allowing the slicer to collect dependencies. When the body returns, the original definition of the instrumented functions is restored. # + [markdown] slideshow={"slide_type": "subslide"} # ### An Instrumenter Base Class # + [markdown] slideshow={"slide_type": "fragment"} # The basic functionality of instrumenting a number of functions (and restoring them at the end of the `with` block) comes in a `Instrumenter` base class. It invokes `instrument()` on all items to instrument; this is to be overloaded in subclasses. # + slideshow={"slide_type": "subslide"} class Instrumenter(StackInspector): def __init__(self, *items_to_instrument, globals=None, log=False): """Create an instrumenter. `items_to_instrument` is a list of items to instrument. `globals` is a namespace to use (default: caller's globals()) """ self.log = log self.items_to_instrument = items_to_instrument if globals is None: globals = self.caller_globals() self.globals = globals def __enter__(self): """Instrument sources""" for item in self.items_to_instrument: self.instrument(item) return self def instrument(self, item): """Instrument `item`. To be overloaded in subclasses.""" if self.log: print("Instrumenting", item) # + [markdown] slideshow={"slide_type": "subslide"} # At the end of the `with` block, we restore the given functions. # + slideshow={"slide_type": "fragment"} class Instrumenter(Instrumenter): def __exit__(self, exc_type, exc_value, traceback): """Restore sources""" self.restore() def restore(self): for item in self.items_to_instrument: self.globals[item.__name__] = item # + [markdown] slideshow={"slide_type": "fragment"} # By default, an `Instrumenter` simply outputs a log message: # + slideshow={"slide_type": "fragment"} with Instrumenter(middle, log=True) as ins: pass # + [markdown] slideshow={"slide_type": "subslide"} # ### The Slicer Class # + [markdown] slideshow={"slide_type": "fragment"} # The `Slicer` class comes as a subclass of `Instrumenter`. It sets its own dependency tracker (which can be overwritten by setting the `dependency_tracker` keyword argument). # + slideshow={"slide_type": "subslide"} class Slicer(Instrumenter): def __init__(self, *items_to_instrument, dependency_tracker=None, globals=None, log=False): """Create a slicer. `items_to_instrument` are Python functions or modules with source code. `dependency_tracker` is the tracker to be used (default: DependencyTracker). `globals` is the namespace to be used (default: caller's `globals()`) `log`=True or `log` > 0 turns on logging""" super().__init__(*items_to_instrument, globals=globals, log=log) if len(items_to_instrument) == 0: raise ValueError("Need one or more items to instrument") if dependency_tracker is None: dependency_tracker = DependencyTracker(log=(log > 1)) self.dependency_tracker = dependency_tracker self.saved_dependencies = None # + [markdown] slideshow={"slide_type": "subslide"} # The `parse()` method parses a given item, returning its AST. # + slideshow={"slide_type": "fragment"} class Slicer(Slicer): def parse(self, item): """Parse `item`, returning its AST""" source_lines, lineno = inspect.getsourcelines(item) source = "".join(source_lines) if self.log >= 2: print_content(source, '.py', start_line_number=lineno) print() print() tree = ast.parse(source) ast.increment_lineno(tree, lineno - 1) return tree # + [markdown] slideshow={"slide_type": "subslide"} # The `transform()` method applies the list of transformers defined earlier in this chapter. # + slideshow={"slide_type": "subslide"} class Slicer(Slicer): def transformers(self): """List of transformers to apply. To be extended in subclasses.""" return [ TrackCallTransformer(), TrackSetTransformer(), TrackGetTransformer(), TrackControlTransformer(), TrackReturnTransformer(), TrackParamsTransformer() ] def transform(self, tree): """Apply transformers on `tree`. May be extended in subclasses.""" # Apply transformers for transformer in self.transformers(): if self.log >= 3: print(transformer.__class__.__name__ + ':') transformer.visit(tree) ast.fix_missing_locations(tree) if self.log >= 3: print_content( astor.to_source(tree, add_line_information=self.log >= 4), '.py') print() print() if 0 < self.log < 3: print_content(astor.to_source(tree), '.py') print() print() return tree # + [markdown] slideshow={"slide_type": "subslide"} # The `execute()` method executes the transformed tree (such that we get the new definitions). We also make the dependency tracker available for the code in the `with` block. # + slideshow={"slide_type": "fragment"} class Slicer(Slicer): def execute(self, tree, item): """Compile and execute `tree`. May be extended in subclasses.""" # We pass the source file of `item` such that we can retrieve it # when accessing the location of the new compiled code code = compile(tree, inspect.getsourcefile(item), 'exec') # Execute the code, resulting in a redefinition of item exec(code, self.globals) self.globals[DATA_TRACKER] = self.dependency_tracker # + [markdown] slideshow={"slide_type": "subslide"} # The `instrument()` method puts all these together, first parsing the item into a tree, then transforming and executing the tree. # + slideshow={"slide_type": "fragment"} class Slicer(Slicer): def instrument(self, item): """Instrument `item`, transforming its source code, and re-defining it.""" super().instrument(item) tree = self.parse(item) tree = self.transform(tree) self.execute(tree, item) # + [markdown] slideshow={"slide_type": "fragment"} # When we restore the original definition (after the `with` block), we save the dependency tracker again. # + slideshow={"slide_type": "subslide"} class Slicer(Slicer): def restore(self): """Restore original code.""" if DATA_TRACKER in self.globals: self.saved_dependencies = self.globals[DATA_TRACKER] del self.globals[DATA_TRACKER] super().restore() # + [markdown] slideshow={"slide_type": "fragment"} # Three convenience functions allow us to see the dependencies as (well) dependencies, as code, and as graph. These simply invoke the respective functions on the saved dependencies. # + slideshow={"slide_type": "subslide"} class Slicer(Slicer): def dependencies(self): """Return collected dependencies.""" if self.saved_dependencies is None: return Dependencies({}, {}) return self.saved_dependencies.dependencies() def code(self, *args, **kwargs): """Show code of instrumented items, annotated with dependencies.""" first = True for item in self.items_to_instrument: if not first: print() self.dependencies().code(item, *args, **kwargs) first = False def graph(self, *args, **kwargs): """Show dependency graph.""" return self.dependencies().graph(*args, **kwargs) def _repr_svg_(self): return self.graph()._repr_svg_() # + [markdown] slideshow={"slide_type": "subslide"} # Let us put `Slicer` into action. We track our `middle()` function: # + slideshow={"slide_type": "fragment"} with Slicer(middle) as slicer: m = middle(2, 1, 3) m # + [markdown] slideshow={"slide_type": "fragment"} # These are the dependencies in string form (used when printed): # + slideshow={"slide_type": "fragment"} print(slicer.dependencies()) # + [markdown] slideshow={"slide_type": "fragment"} # This is the code form: # + slideshow={"slide_type": "subslide"} slicer.code() # + [markdown] slideshow={"slide_type": "fragment"} # And this is the graph form: # + slideshow={"slide_type": "subslide"} slicer # + [markdown] slideshow={"slide_type": "fragment"} # You can also access the raw `repr()` form, which allows you to reconstruct dependencies at any time. (This is how we showed off dependencies at the beginning of this chapter, before even introducing the code that computes them.) # + slideshow={"slide_type": "subslide"} print(repr(slicer.dependencies())) # + [markdown] slideshow={"slide_type": "subslide"} # ### Diagnostics # + [markdown] slideshow={"slide_type": "fragment"} # The `Slicer` constructor accepts a `log` argument (default: False), which can be set to show various intermediate results: # # * `log=True` (or `log=1`): Show instrumented source code # * `log=2`: Also log execution # * `log=3`: Also log individual transformer steps # * `log=4`: Also log source line numbers # + [markdown] slideshow={"slide_type": "slide"} # ## More Examples # + [markdown] slideshow={"slide_type": "fragment"} # Let us demonstrate our `Slicer` class on a few more examples. # + [markdown] slideshow={"slide_type": "subslide"} # ### Square Root # + [markdown] slideshow={"slide_type": "fragment"} # The `square_root()` function from [the chapter on assertions](Assertions.ipynb) demonstrates a nice interplay between data and control dependencies. # + slideshow={"slide_type": "skip"} import math # + slideshow={"slide_type": "skip"} from Assertions import square_root # minor dependency # + [markdown] slideshow={"slide_type": "fragment"} # Here is the original source code: # + slideshow={"slide_type": "subslide"} print_content(inspect.getsource(square_root), '.py') # + [markdown] slideshow={"slide_type": "fragment"} # Turning on logging shows the instrumented version: # + slideshow={"slide_type": "subslide"} with Slicer(square_root, log=True) as root_slicer: y = square_root(2.0) # + [markdown] slideshow={"slide_type": "subslide"} # The dependency graph shows how `guess` and `approx` flow into each other until they are the same. # + slideshow={"slide_type": "fragment"} root_slicer # + [markdown] slideshow={"slide_type": "fragment"} # Again, we can show the code annotated with dependencies: # + slideshow={"slide_type": "subslide"} root_slicer.code() # + [markdown] slideshow={"slide_type": "subslide"} # The astute reader may find that an `assert p` statements do not control the following code, although it would be equivalent to `if not p: raise Exception`. Why is that? # + slideshow={"slide_type": "fragment"} quiz("Why don't `assert` statements induce control dependencies?", [ "We have no special handling of `assert` statements", "We have no special handling of `raise` statements", "Assertions are not supposed to act as controlling mechanisms", "All of the above", ], (1 * 1 << 1 * 1 << 1 * 1) ) # + [markdown] slideshow={"slide_type": "subslide"} # Indeed: we treat assertions as "neutral" in the sense that they do not affect the remainder of the program – if they are turned off, they have no effect; and if they are turned on, the remaining program logic should not depend on them. (Our instrumentation also has no special treatment of `assert`, `raise`, or even `return` statements; the latter two should be handled by our `with` blocks.) # + slideshow={"slide_type": "fragment"} # print(repr(root_slicer)) # + [markdown] slideshow={"slide_type": "subslide"} # ### Removing HTML Markup # + [markdown] slideshow={"slide_type": "fragment"} # Let us come to our ongoing example, `remove_html_markup()`. This is how its instrumented code looks like: # + slideshow={"slide_type": "fragment"} with Slicer(remove_html_markup) as rhm_slicer: s = remove_html_markup("<foo>bar</foo>") # + [markdown] slideshow={"slide_type": "fragment"} # The graph is as discussed in the introduction to this chapter: # + slideshow={"slide_type": "fragment"} rhm_slicer # + slideshow={"slide_type": "fragment"} # print(repr(rhm_slicer.dependencies())) # + slideshow={"slide_type": "subslide"} rhm_slicer.code() # + [markdown] slideshow={"slide_type": "subslide"} # We can also compute slices over the dependencies: # + slideshow={"slide_type": "fragment"} _, start_remove_html_markup = inspect.getsourcelines(remove_html_markup) start_remove_html_markup # + slideshow={"slide_type": "subslide"} slicing_criterion = ('tag', (remove_html_markup, start_remove_html_markup + 9)) tag_deps = rhm_slicer.dependencies().backward_slice(slicing_criterion) tag_deps # + slideshow={"slide_type": "subslide"} # repr(tag_deps) # + [markdown] slideshow={"slide_type": "subslide"} # ### Calls and Augmented Assign # + [markdown] slideshow={"slide_type": "fragment"} # Our last example covers augmented assigns and data flow across function calls. We introduce two simple functions `add_to()` and `mul_with()`: # + slideshow={"slide_type": "fragment"} def add_to(n, m): n += m return n # + slideshow={"slide_type": "fragment"} def mul_with(x, y): x *= y return x # + [markdown] slideshow={"slide_type": "fragment"} # And we put these two together in a single call: # + slideshow={"slide_type": "fragment"} def test_math(): return mul_with(1, add_to(2, 3)) # + slideshow={"slide_type": "fragment"} with Slicer(add_to, mul_with, test_math) as math_slicer: test_math() # + [markdown] slideshow={"slide_type": "subslide"} # The resulting dependence graph nicely captures the data flow between these calls, notably arguments and parameters: # + slideshow={"slide_type": "fragment"} math_slicer # + [markdown] slideshow={"slide_type": "fragment"} # These are also reflected in the code view: # + slideshow={"slide_type": "subslide"} math_slicer.code() # + [markdown] slideshow={"slide_type": "slide"} # ## Things that do not Work # + [markdown] slideshow={"slide_type": "subslide"} # Our slicer (and especially the underlying dependency tracker) is still a proof of concept. A number of Python features are not or only partially supported, and/or hardly tested: # # * __Exceptions__ are not handled. The code assumes that for every `call()`, there is a matching `ret()`; when exceptions break this, dependencies across function calls and arguments may be assigned incorrectly. # * __Multiple definitions on a single line__ as in `x = y; x = 1` are not handled correctly. Our implementation assumes that there is one statement per line. # * __If-Expressions__ (`y = 1 if x else 0`) do not create control dependencies, as there are no statements to control. Neither do `if` clauses in comprehensions. # * __Asynchronous functions__ (`async`, `await`) are not tested. # # In these cases, the instrumentation and the underlying dependency tracker may fail to identify control and/or data flows. The semantics of the code, however, should always stay unchanged. # + [markdown] slideshow={"slide_type": "slide"} # ## Synopsis # + [markdown] slideshow={"slide_type": "fragment"} # This chapter provides a `Slicer` class to automatically determine and visualize dynamic dependencies. When we say that a variable $x$ depends on a variable $y$ (written $x \leftarrow y$), we distinguish two kinds of dependencies: # # * **data dependencies**: $x$ obtains its value from a computation involving the value of $y$. # * **control dependencies**: $x$ obtains its value because of a computation involving the value of $y$. # # Such dependencies are crucial for debugging, as they allow to determine the origins of individual values (and notably incorrect values). # + [markdown] slideshow={"slide_type": "subslide"} # To determine dynamic dependencies in a function `func` and its callees `func1`, `func2`, etc., use # # ```python # with Slicer(func, func1, func2) as slicer: # <Some code involving func()> # ``` # # and then `slicer.graph()` or `slicer.code()` to examine dependencies. # + [markdown] slideshow={"slide_type": "fragment"} # Here is an example. The `demo()` function computes some number from `x`: # + slideshow={"slide_type": "subslide"} def demo(x): z = x while x <= z <= 64: z *= 2 return z # + [markdown] slideshow={"slide_type": "fragment"} # By using `with Slicer(demo)`, we first instrument `demo()` and then execute it: # + slideshow={"slide_type": "fragment"} with Slicer(demo) as slicer: demo(10) # + [markdown] slideshow={"slide_type": "fragment"} # After execution is complete, you can output `slicer` to visualize the dependencies as graph. Data dependencies are shown as black solid edges; control dependencies are shown as grey dashed edges. We see how the parameter `x` flows into `z`, which is returned after some computation that is control dependent on a `<test>` involving `z`. # + slideshow={"slide_type": "subslide"} slicer # + [markdown] slideshow={"slide_type": "fragment"} # An alternate representation is `slicer.code()`, annotating the instrumented source code with (backward) dependencies. Data dependencies are shown with `<=`, control dependencies with `<-`; locations (lines) are shown in parentheses. # + slideshow={"slide_type": "fragment"} slicer.code() # + [markdown] slideshow={"slide_type": "subslide"} # Dependencies can also be retrieved programmatically. The `dependencies()` method returns a `Dependencies` object encapsulating the dependency graph. # + [markdown] slideshow={"slide_type": "fragment"} # The method `all_vars()` returns all variables in the dependency graph. Each variable is encoded as a pair (_name_, _location_) where _location_ is a pair (_codename_, _lineno_). # + slideshow={"slide_type": "fragment"} slicer.dependencies().all_vars() # + [markdown] slideshow={"slide_type": "fragment"} # `code()` and `graph()` methods can also be applied on dependencies. The method `backward_slice(var)` returns a backward slice for the given variable. To retrieve where `z` in Line 2 came from, use: # + slideshow={"slide_type": "subslide"} _, start_demo = inspect.getsourcelines(demo) start_demo # + slideshow={"slide_type": "fragment"} slicer.dependencies().backward_slice(('z', (demo, start_demo + 1))).graph() # + [markdown] slideshow={"slide_type": "fragment"} # Here are the classes defined in this chapter. A `Slicer` instruments a program, using a `DependencyTracker` at run time to collect `Dependencies`. # + slideshow={"slide_type": "fragment"} # ignore from ClassDiagram import display_class_hierarchy # + slideshow={"slide_type": "fragment"} # ignore display_class_hierarchy([Slicer, DependencyTracker, Dependencies], project='debuggingbook') # + [markdown] button=false new_sheet=true run_control={"read_only": false} slideshow={"slide_type": "slide"} # ## Lessons Learned # # * To track the origin of some incorrect value, follow back its _dependencies_: # * _Data dependencies_ indicate where the value came from. # * _Control dependencies_ show why a statement was executed. # * A _slice_ is a subset of the code that could have influenced a specific value. It can be computed by transitively following all dependencies. # * _Instrument code_ to automatically determine and visualize dependencies. # + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"} # ## Next Steps # # In the [next chapter](StatisticalDebugger.ipynb), we will explore how to make use of _multiple_ passing and failing executions. # + [markdown] slideshow={"slide_type": "slide"} # ## Background # # Slicing as computing a subset of a program by means of data and control dependencies was invented by <NAME> \cite{Weiser1981}. In his seminal work "Programmers use Slices when Debugging", \cite{Weiser1982}, Weiser demonstrated how such dependencies are crucial for systematic debugging: # # > When debugging unfamiliar programs programmers use program pieces called _slices_ which are sets of statements related by their flow of data. The statements in a slice are not necessarily textually contiguous, but may be scattered through a program. # # Weiser's slices (and dependencies) were determined _statically_ from program code. Both Korel and Laski \cite{Korel1988} as well as Agrawal and Horgan \cite{Agrawal1990} introduced _dynamic_ program slicing, building on _dynamic_ dependencies, which would be more specific to a given (failing) run. (The `Slicer` we implement in this chapter is a dynamic slicer.) Tip \cite{tip1995} gives a survey on program slicing techniques. Chen et al. \cite{Chen2014} describe and evaluate the first dynamic slicer for Python programs (which is independent from our implementation). # # One examplary application of program slices is [the Whyline](https://github.com/amyjko/whyline) by Ko and Myers \cite{Ko2004}. The Whyline a debugging interface for asking questions about program behavior. It allows to interactively query where a particular variable came from (a data dependency) and why or why not specific things took place (control dependencies). # # In \cite{Soremekun2021}, Soremekun et al. evaluated the performance of slicing as a fault localization mechanism and found that following dependencies was one of the most successful strategies to determine fault locations. Notably, if programmers first examine at most the top five most suspicious locations from [statistical debugging](StatisticalDebugger.ipynb), and then switch to dynamic slices, on average, they will need to examine only 15% (12 lines) of the code. # + [markdown] button=false new_sheet=true run_control={"read_only": false} slideshow={"slide_type": "slide"} # ## Exercises # # + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"} # ### Exercise 1: Forward Slicing # # Extend `Dependencies` with a variant of `backward_slice()` named `forward_slice()` that, instead of computing the dependencies that go _into_ a a location, computes the dependencies that go _out_ of a location. # + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"} # ### Exercise 2: Code with Forward Dependencies # # Create a variant of `Dependencies.code()` that, for each statement `s`, instead of showing a "passive" view (which variables and locations influenced `s`?), shows an "active" view (which variables and locations were influenced by `s`?). For `middle()`, for instance, the first line should show which lines are influenced by `x`, `y`, and `z`, respectively. Use `->` for control flows and `=>` for data flows. # + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"} solution="hidden" solution2="hidden" solution2_first=true solution_first=true # ### Exercise 3: Determine Instrumented Functions Dynamically # # When initializing `Slicer()`, one has to provide the set of functions to be instrumented. This is because the instrumentation has to take place _before_ the code in the `with` block is executed. # # Create a subclass of `Slicer`, called `AutoSlicer` that determines these functions automatically. It would be used as # # ```python # with AutoSlicer() as slicer: # func(...) # ``` # # and proceed in two steps: # # 1. Run the code in the `with` block, using the `Tracer` class from [the chapter on tracing](Tracer.ipynb). Collect the first call to `func()` and its arguments, as well as the names of all subsequent called functions. # 2. Repeat the first call to `func()`, now with all called functions being instrumented as in `Slicer`.
Slicer.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # ## Nome: <NAME> # + [markdown] id="fUe-H1ByPPaU" # # Manipulando dados com Pandas - Lista de Exercícios # # Depois de estudarmos os fundamentos da linguagem Python chegou a hora de explorarmos uma das bibliotecas mais poderosas para análise de dados, o Pandas. # # De acordo com o próprio criador dessa biblioteca, <NAME>, o nome Pandas é derivado de panel data (**dados em painel**), um termo de econometria para conjuntos de dados estruturados. O surgimento da biblioteca, no início de 2008, começou devido a insatisfação de McKinney de obter uma __ferramenta de processamento de dados de alto desempenho__, com recursos flexíveis de manipulação de planilhas e de banco de dados relacionais. # # ![PandaUrl](https://media.giphy.com/media/HDR31jsQUPqQo/giphy.gif "panda") # # Mais informações sobre o Pandas em Português [aqui](https://harve.com.br/blog/programacao-python-blog/pandas-python-vantagens-e-como-comecar/). # # ## Nesta lista abordaremos os seguintes tópicos # # * Download e extração de uma base de dados a partir de uma URL # * Leitura de um arquivo .csv # * Verificações básicas quanto à estrutura da nossa base # * quantidade de linhas e colunas # * tipo de cada coluna # * quantidade de dados faltantes por coluna/linha # * Processamento básico # * remoção de valores faltantes # * conversão de tipo de uma coluna # * substituição de strings # * Criação de uma série (pandas.Series) a partir de um DataFrame (pandas.DataFrame) # * Diferenças entre .loc e .iloc # * Plotar uma série temporal # # ------- # # #### Bons Estudos! # # *Qualquer dúvida não deixe de procurar os monitores nos fóruns!* # # -------- # -------- # + [markdown] id="2B87-gwGCYMD" # ## 0 - Download e extração de uma base de dados a partir de uma URL # # Nesta lista utilizaremos uma base de dados real relacionada ao avanço da COVID-19 no Brasil, mais especificamente aos boletins informativos e casos do coronavírus por município por dia. # # Esta base é atualizada diariamente a partir dos dados das Secretarias de Saúde estaduais e está disponível através do [link](https://brasil.io/dataset/covid19/boletim/). # # Dentro do ambiente do Google Colab podemos usar dois comandos (*wget* e *gzip*) de bash Linux para baixar o arquivo compactado e extrair a base em CSV. # + id="GTZ4328WnA7S" # ! wget 'https://data.brasil.io/dataset/covid19/caso.csv.gz' # ! gzip -d caso.csv.gz # + id="bwrcBo5Umwvo" import pandas as pd import numpy as np # %matplotlib inline # + [markdown] id="1rs7AKUrD8MF" # ## 1 - Leitura de uma base em csv com Pandas # # Substitua a tag `# SEU CÓDIGO AQUI #` pelo comando necessário para cumprir a tarefa. # # Se a leitura for bem sucedida o output exibirá as cinco primeiras linhas da tabela. # + id="UXJeRXUPm0E9" df = pd.read_csv("caso.csv.gz",compression='gzip') df.head() # + [markdown] id="BzDcnlcEFEr4" # ## 2 - Verificações básicas quanto à estrutura da tabela # # - quantidade de linhas e colunas # - tipo de cada coluna # - quantidade de dados faltantes por coluna # + id="Mvulx4Le4aa2" # Exiba o número total de linhas e colunas de df print("Total de linhas: ", len(df.index)) print("Total de colunas: ", len(df.columns)) # + id="YTexmxoPFldW" # Exiba o tipo de cada coluna df.dtypes # + id="Fl2NLLS2FswI" ''' Exiba o total de dados faltantes para cada coluna no seguinte formato: A coluna date possui xxx linhas em branco. A coluna state não possui linhas em branco. A coluna city possui yyy linhas em branco. ... ''' for idx, value in df.isna().sum().iteritems(): if value > 0: print("A coluna ",idx," possui ", value," linhas em branco.") else: print("A coluna ",idx," não possui linhas em branco.") # + [markdown] id="VfeRCAw0JkYr" # ### 3 - Processamento básico # * remoção de valores faltantes # * conversão de tipo de uma coluna # * substituição de strings # # #### Material suplementar # # [Formatos de data e tempo](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) # + id="iXIsstLlJk8h" ''' Remova todas as linhas em que o campo cidade (`city`) esteja em branco (NaN). Faça tal remoção de tal forma a alterar o próprio dataframe sem atribuir o resultado a uma nova variável Obs: No caso desse conjunto de dados, como removemos todas as linhas sem a informação de cidade deveríamos ficar apenas com as informações de cidade e não estado de acordo com a variável `place_type`. Você sabe verificar rapidamente se esta frase está correta? Mostre o código em outra célula. ''' df = df.dropna(subset=['city']) # - print(df['place_type'].value_counts()) # informacao correta temos apenas city # + id="jbFGw3oEPLed" ''' Converta a coluna `date` de string (Objetct) para datetime Obs: Mostre que a conversão de tipo foi bem sucedida em outra célula. ''' df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # - df.dtypes # + id="d0yAOiAtRSr8" ''' Substitua todas as referências a "city" na coluna `place_type` por "cidade" Obs: Mostre que a substituição foi bem sucedida em outra célula. ''' df['place_type'] = 'cidade' # - print(df['place_type'].value_counts()) # substituicao bem sucedida # + [markdown] id="AyKlOOlUVSbg" # ## 4 - Criação de uma série a partir de um DataFrame # # No Pandas uma série é uma estrutura de dados unidimencional que apresenta para cada índice um valor. Uma série é muito similar à estrutura de um dicionário, porém com mais flexibilidade para manipular e editar seus dados. # + id="7DdiDTFfVMKv" ''' Crie uma série chamada `casos_sp` que contenha todos os casos confirmados (coluna `confirmed`) da cidade de São Paulo-SP indexados no tempo (coluna `date`). Exiba um print dos primeiros 10 dias da série. Obs: Mostre o tipo da variável `casos_sp` em outra célula. ''' df_sao_paulo = df.loc[(df['city'] == 'São Paulo') & (df['state'] == 'SP')] # cidade de São Paulo-SP casos_sp = df_sao_paulo.set_index('date')['confirmed'] # indexando pela data a coluna confirmados casos_sp.tail(10) # - type(casos_sp) # tipo da variavel # + [markdown] id="KnsKD8dWZfjb" # ## 5 - Acessando dados com .loc e .iloc # # Muitas vezes queremos inspecionar uma linha ou um conjunto de linhas do nosso dataframe ou series, para esse tipo de query o Pandas conta com duas formas de buscar por indexação, uma baseada no index (.loc) e outra baseada na posição "física" (.iloc). # # `.loc` - é uma busca baseada no index seja ele um inteiro, uma string, uma data ou qualquer outro tipo de dado utilizado para indexar o dataframe ou series. # # `.iloc`- é uma busca baseada no índice númerico da linha ou conjunto de linhas que desejamos acessar, ou seja, só aceita números inteiros ou intervalos de inteiros (ex: .iloc[15:30]). # # # #### Material suplementar # # Caso a série retorne vazia, veja como resolver este problema no [StackOverflow](https://stackoverflow.com/questions/29370057/select-dataframe-rows-between-two-dates). # + id="ZVmwA5Gjcl3Z" ''' Exiba em tela o número de mortes por COVID na cidade de Macaé-RJ entre os dias 04/04/2021 e 11/04/2021. Obs: utilize .loc ou .iloc e justifique a escolha. ''' df_macae = df.loc[(df['city'] == 'Macaé') & (df['state'] == 'RJ')] # cidade de Macaé-RJ df_macae = df_macae.loc[(df_macae['date'] >= '2021-4-4') & (df_macae['date'] <= '2021-4-11')] df_macae.sort_index(inplace=True, ascending=True) print("Número de mortes no período entre dos dias: ", df_macae.iloc[0]['deaths']-df_macae.iloc[-1]['deaths']) # loc utilizado para fitrar os dados do data frame principal baseados no index de city, state e date # iloc utilizado no final para calcular o numero de mortes baseado no indice numero primeiro-ultimo # + id="XseTg8a3ipkp" ''' Exiba em tela o número de mortes por COVID na cidade de Macaé-RJ no último dia disponível na base. Obs: utilize .loc ou .iloc e justifique a escolha. ''' df_macae = df.loc[(df['city'] == 'Macaé') & (df['state'] == 'RJ')] # cidade de Macaé-RJ df_macae.sort_index(inplace=True, ascending=True) print("Número de mortes no último dia disponível na base: ", df_macae.iloc[0]['deaths']-df_macae.iloc[1]['deaths']) # loc utilizado para fitrar os dados do data frame principal baseados no index de city, state e date # iloc utilizado no final para calcular a diferenca no numero de mortes acumulado entre o ultimo e o penultimo disponivel # + [markdown] id="tSi8Xx5R-aKD" # ## 6 - Plotar uma série temporal # # Nestes exercícios usaremos a função plot do Pandas que usa por trás a biblioteca matplotlib. # # Para exibirmos em tela os gráficos devemos usar o comando mágico `%matplotlib inline` em alguma célula do notebook, preferencialmente depois dos imports. # # Mais informações sobre os comandos mágicos no [link](https://ipython.readthedocs.io/en/stable/interactive/magics.html). # + colab={"base_uri": "https://localhost:8080/", "height": 277} id="D12vnvH_CBJ5" outputId="66a7652d-c88b-4b94-feeb-2ede7023ce2a" ''' Plot a série de novos casos por dia na cidade de São Paulo desde o início da pandemia até a data mais recente. Obs: use a série criada no exercício anterior `casos_sp` ''' casos_sp.sort_index(ascending=True, inplace=True) casos_sp.index.name = 'Data' # %matplotlib inline casos_sp.plot() # - # como a coluna de casos confirmados e acumulativa a serie abaixo extrai a diferenca entre o dia atual com o anterior # para verificar a variacao diaria de casos casos_sp_dia = pd.Series(np.ediff1d(casos_sp.sort_index(), to_begin=casos_sp.sort_index()[0]), index=casos_sp.sort_index().index) casos_sp_dia.index.name = 'Data' casos_sp_dia.plot() # + [markdown] id="GRj4ZMiTDARY" # Se o exercício foi executado corretamente um gráfico de novos casos (eixo-y) no tempo (eixo-x) foi plotado. Note que o eixo-y está em notação científica e sem um rótulo, o que dificulta a leitura. # # É possível usar comandos do matplotlib para alterar um gráfico produzido pelo Pandas, como veremos a seguir. # + colab={"base_uri": "https://localhost:8080/", "height": 440} id="_eXmKRTuDnQw" outputId="bec7b47f-90ca-4af2-bb5a-55c727a3b7b6" import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') fig, ax = plt.subplots(figsize=(15,7)) ax.ticklabel_format(useOffset=False, style='plain') ax.set_ylabel('Novos Casos Por Dia') ax.set_xlabel('Data') plt.plot(casos_sp,'b') # - # como a coluna de casos confirmados e acumulativa a serie abaixo extrai a diferenca entre o dia atual com o anterior # para verificar a variacao diaria de casos plt.style.use('fivethirtyeight') fig, ax = plt.subplots(figsize=(15,7)) ax.ticklabel_format(useOffset=False, style='plain') ax.set_ylabel('Novos Casos Por Dia') ax.set_xlabel('Data') plt.plot(casos_sp_dia,'b') plt.show()
aulas/para_alunos_aula_04/exercicios_pandas.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Grover's Algorithm and Amplitude Amplification # # Grover's algorithm is one of the most famous quantum algorithms introduced by Lov Grover in 1996 \[1\]. It has initially been proposed for unstructured search problems, i.e. for finding a marked element in a unstructured database. However, Grover's algorithm is now a subroutine to several other algorithms, such as Grover Adaptive Search \[2\]. For the details of Grover's algorithm, please see [Grover's Algorithm](https://qiskit.org/textbook/ch-algorithms/grover.html) in the Qiskit textbook. # # Qiskit implements Grover's algorithm in the `Grover` class. This class also includes the generalized version, Amplitude Amplification \[3\], and allows setting individual iterations and other meta-settings to Grover's algorithm. # # **References:** # # \[1\]: <NAME>, A fast quantum mechanical algorithm for database search. Proceedings 28th Annual Symposium on # the Theory of Computing (STOC) 1996, pp. 212-219. # # \[2\]: <NAME>, <NAME>, <NAME>, Grover Adaptive Search for Constrained Polynomial Binary Optimization. # https://arxiv.org/abs/1912.04088 # # # \[3\]: <NAME>., <NAME>., <NAME>., & <NAME>. (2000). Quantum Amplitude Amplification and Estimation. http://arxiv.org/abs/quant-ph/0005055 # ## Grover's algorithm # # Grover's algorithm uses the Grover operator $\mathcal{Q}$ to amplify the amplitudes of the good states: # # $$ # \mathcal{Q} = \mathcal{A}\mathcal{S_0}\mathcal{A}^\dagger \mathcal{S_f} # $$ # # Here, # * $\mathcal{A}$ is the initial search state for the algorithm, which is just Hadamards, $H^{\otimes n}$ for the textbook Grover search, but can be more elaborate for Amplitude Amplification # * $\mathcal{S_0}$ is the reflection about the all 0 state # $$ # |x\rangle \mapsto \begin{cases} -|x\rangle, &x \neq 0 \\ |x\rangle, &x = 0\end{cases} # $$ # * $\mathcal{S_f}$ is the oracle that applies # $$ # |x\rangle \mapsto (-1)^{f(x)}|x\rangle # $$ # &nbsp;&nbsp;&nbsp;&nbsp; where $f(x)$ is 1 if $x$ is a good state and otherwise 0. # # In a nutshell, Grover's algorithm applies different powers of $\mathcal{Q}$ and after each execution checks whether a good solution has been found. # # # ### Running Grover's algorithm # # To run Grover's algorithm with the `Grover` class, firstly, we need to specify an oracle for the circuit of Grover's algorithm. In the following example, we use `QuantumCircuit` as the oracle of Grover's algorithm. However, there are several other class that we can use as the oracle of Grover's algorithm. We talk about them later in this tutorial. # # Note that the oracle for `Grover` mush be a _phase-flip_ oracle. That is, it multiplies the amplitudes of the of "good states" by a factor of $-1$. We explain later how to convert a _bit-flip_ oracle to a phase-flip oracle. # + from qiskit import QuantumCircuit from qiskit.aqua.algorithms import Grover # the state we desire to find is '11' good_state = ['11'] # specify the oracle that marks the state '11' as a good solution oracle = QuantumCircuit(2) oracle.cz(0, 1) # define Grover's algorithm grover = Grover(oracle=oracle, good_state=good_state) # now we can have a look at the Grover operator that is used in running the algorithm grover.grover_operator.draw(output='mpl') # - # Then, we specify a backend and call the `run` method of `Grover` with a backend to execute the circuits. The returned result type is a `GroverResult`. # # If the search was successful, the `oracle_evaluation` attribute of the result will be `True`. In this case, the most sampled measurement, `top_measurement`, is one of the "good states". Otherwise, `oracle_evaluation` will be False. # # + from qiskit import Aer from qiskit.aqua import QuantumInstance qasm_simulator = Aer.get_backend('qasm_simulator') result = grover.run(quantum_instance=qasm_simulator) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) # - # In the example, the result of `top_measurement` is `11` which is one of "good state". Thus, we succeeded to find the answer by using `Grover`. # ### Using the different types of classes as the oracle of `Grover` # In the above example, we used `QuantumCircuit` as the oracle of `Grover`. # However, we can also use `qiskit.aqua.components.oracles.Oracle`, and `qiskit.quantum_info.Statevector` as oracles. # All the following examples are when $|11\rangle$ is "good state" # + from qiskit.quantum_info import Statevector oracle = Statevector.from_label('11') grover = Grover(oracle=oracle, good_state=['11']) result = grover.run(quantum_instance=qasm_simulator) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) # - # Internally, the statevector is mapped to a quantum circuit: grover.grover_operator.oracle.draw(output='mpl') # The `Oracle` components in Qiskit Aqua allow for an easy construction of more complex oracles. # The `Oracle` type has the interesting subclasses: # * `LogicalExpressionOracle`: for parsing logical expressions such as `'~a | b'`. This is especially useful for solving 3-SAT problems and is shown in the accompanying [Grover Examples](08_grover_examples.ipynb) tutorial. # * `TrutheTableOracle`: for converting binary truth tables to circuits # # Here we'll use the `LogicalExpressionOracle` for the simple example of finding the state $|11\rangle$, which corresponds to `'a & b'`. # + tags=[] from qiskit.aqua.components.oracles import LogicalExpressionOracle # `Oracle` (`LogicalExpressionOracle`) as the `oracle` argument expression = '(a & b)' oracle = LogicalExpressionOracle(expression) grover = Grover(oracle=oracle) grover.grover_operator.oracle.draw(output='mpl') # + [markdown] tags=[] # You can observe, that this oracle is actually implemented with three qubits instead of two! # # That is because the `LogicalExpressionOracle` is not a phase-flip oracle (which flips the phase of the good state) but a bit-flip oracle. This means it flips the state of an auxiliary qubit if the other qubits satisfy the condition. # For Grover's algorithm, however, we require a phase-flip oracle. To convert the bit-flip oracle to a phase-flip oracle we sandwich the controlled-NOT by $X$ and $H$ gates, as you can see in the circuit above. # # **Note:** This transformation from a bit-flip to a phase-flip oracle holds generally and you can use this to convert your oracle to the right representation. # - # ## Amplitude amplification # Grover's algorithm uses Hadamard gates to create the uniform superposition of all the states at the beginning of the Grover operator $\mathcal{Q}$. If some information on the good states is available, it might be useful to not start in a uniform superposition but only initialize specific states. This, generalized, version of Grover's algorithm is referred to _Amplitude Amplification_. # # In Qiskit, the initial superposition state can easily be adjusted by setting the `state_preparation` argument. # # ### State preparation # # A `state_preparation` argument is used to specify a quantum circuit that prepares a quantum state for the start point of the amplitude amplification. # By default, a circuit with $H^{\otimes n} $ is used to prepare uniform superposition (so it will be Grover's search). The diffusion circuit of the amplitude amplification reflects `state_preparation` automatically. # + tags=[] import numpy as np # Specifying `state_preparation` # to prepare a superposition of |01>, |10>, and |11> oracle = QuantumCircuit(3) oracle.h(2) oracle.ccx(0,1,2) oracle.h(2) theta = 2 * np.arccos(1 / np.sqrt(3)) state_preparation = QuantumCircuit(3) state_preparation.ry(theta, 0) state_preparation.ch(0,1) state_preparation.x(1) state_preparation.h(2) # we only care about the first two bits being in state 1, thus add both possibilities for the last qubit grover = Grover(oracle=oracle, state_preparation=state_preparation, good_state=['110', '111']) # state_preparation print('state preparation circuit:') grover.grover_operator.state_preparation.draw(output='mpl') # - result = grover.run(quantum_instance=qasm_simulator) print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) # ### Full flexibility # # For more advanced use, it is also possible to specify the entire Grover operator by setting the `grover_operator` argument. This might be useful if you know more efficient implementation for $\mathcal{Q}$ than the default construction via zero reflection, oracle and state preparation. # # The `qiskit.circuit.library.GroverOperator` can be a good starting point and offers more options for an automated construction of the Grover operator. You can for instance # * set the `mcx_mode` # * ignore qubits in the zero reflection by setting `reflection_qubits` # * explicitly exchange the $\mathcal{S_f}, \mathcal{S_0}$ and $\mathcal{A}$ operations using the `oracle`, `zero_reflection` and `state_preparation` arguments # For instance, imagine the good state is a three qubit state $|111\rangle$ but we used 2 additional qubits as auxiliary qubits. # + tags=[] from qiskit.circuit.library import GroverOperator, ZGate oracle = QuantumCircuit(5) oracle.append(ZGate().control(2), [0, 1, 2]) oracle.draw(output='mpl') # - # Then, per default, the Grover operator implements the zero reflection on all five qubits. # + tags=["nbsphinx-thumbnail"] grover_op = GroverOperator(oracle, insert_barriers=True) grover_op.draw(output='mpl') # - # But we know that we only need to consider the first three: grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True) grover_op.draw(output='mpl') # ## Dive into other arguments of `Grover` # `Grover` has arguments other than `oracle` and `state_preparation`. We will explain them in this section. # # ### Specifying `good_state` # `good_state` is used to check whether the measurement result is correct or not internally. It can be a list of binary strings, a list of integer, `Statevector`, and Callable. If the input is a list of bitstrings, each bitstrings in the list represents a good state. If the input is a list of integer, each integer represent the index of the good state to be $|1\rangle$. If it is a `Statevector`, it represents a superposition of all good states. # # + tags=[] # a list of binary strings good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = ['11', '00'] grover = Grover(oracle=oracle, good_state=good_state) print(grover.is_good_state('11')) # - # a list of integer good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = [0, 1] grover = Grover(oracle=oracle, good_state=good_state) print(grover.is_good_state('11')) # + tags=[] from qiskit.quantum_info import Statevector # `Statevector` good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = Statevector.from_label('11') grover = Grover(oracle=oracle, good_state=good_state) print(grover.is_good_state('11')) # + tags=[] # Callable good state def callable_good_state(bitstr): if bitstr == "11": return True return False oracle = QuantumCircuit(2) oracle.cz(0, 1) grover = Grover(oracle=oracle, good_state=callable_good_state) print(grover.is_good_state('11')) # - # ### The number of `iterations` # # The number of repetition of applying the Grover operator is important to obtain the correct result with Grover's algorithm. The number of iteration can be set by the `iteration` argument of `Grover`. The following inputs are supported: # * an integer to specify a single power of the Grover operator that's applied # * or a list of integers, in which all these different powers of the Grover operator are run consecutively and after each time we check if a correct solution has been found # # Additionally there is the `sample_from_iterations` argument. When it is `True`, instead of the specific power in `iterations`, a random integer between 0 and the value in `iteration` is used as the power Grover's operator. This approach is useful when we don't even know the number of solution. # # For more details of the algorithm using `sample_from_iterations`, see [4]. # # **References:** # # [4]: Boyer et al., Tight bounds on quantum searching [arxiv:quant-ph/9605034](https://arxiv.org/abs/quant-ph/9605034) # integer iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) grover = Grover(oracle=oracle, good_state=['11'], iterations=1) # list iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) grover = Grover(oracle=oracle, good_state=['11'], iterations=[1, 2, 3]) # using sample_from_iterations oracle = QuantumCircuit(2) oracle.cz(0, 1) grover = Grover(oracle=oracle, good_state=['11'], iterations=[1, 2, 3], sample_from_iterations=True) # When the number of solutions is known, we can also use a static method `optimal_num_iterations` to find the optimal number of iterations. Note that the output iterations is an approximate value. When the number of qubits is small, the output iterations may not be optimal. # iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8) iterations # ### Applying `post_processing` # We can apply an optional post processing to the top measurement for ease of readability. It can be used e.g. to convert from the bit-representation of the measurement `[1, 0, 1]` to a DIMACS CNF format `[1, -2, 3]`. # + def to_DIAMACS_CNF_format(bit_rep): return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)] oracle = QuantumCircuit(2) oracle.cz(0, 1) grover = Grover(oracle=oracle, good_state=['11'],post_processing=to_DIAMACS_CNF_format) grover.post_processing([1, 0, 1]) # - import qiskit.tools.jupyter # %qiskit_version_table # %qiskit_copyright
tutorials/algorithms/07_grover.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # Advanced dynamic seq2seq with TensorFlow # Encoder is bidirectional now. Decoder is implemented using `tf.nn.raw_rnn`. # It feeds previously generated tokens during training as inputs, instead of target sequence. # **UPDATE (16.02.2017)**: I learned some things after I wrote this tutorial. In particular: # - [DONE] Replacing projection (one-hot encoding followed by linear layer) with embedding (indexing weights of linear layer directly) is more efficient. # - When decoding, feeding previously generated tokens as inputs adds robustness to model's errors. However feeding ground truth speeds up training. Apperantly best practice is to mix both randomly when training. # # I will update tutorial to reflect this at some point. # + import numpy as np import tensorflow as tf import helpers tf.reset_default_graph() sess = tf.InteractiveSession() # - tf.__version__ # + PAD = 0 EOS = 1 vocab_size = 259 input_embedding_size = 100 encoder_hidden_units = 100 decoder_hidden_units = encoder_hidden_units * 2 # + encoder_inputs = tf.placeholder(shape=(None, None), dtype=tf.int32, name='encoder_inputs') encoder_inputs_length = tf.placeholder(shape=(None,), dtype=tf.int32, name='encoder_inputs_length') decoder_targets = tf.placeholder(shape=(None, None), dtype=tf.int32, name='decoder_targets') # - # Previously we elected to manually feed `decoder_inputs` to better understand what is going on. Here we implement decoder with `tf.nn.raw_rnn` and will construct `decoder_inputs` step by step in the loop. # ## Embeddings # Setup embeddings (see tutorial 1) # + embeddings = tf.Variable(tf.random_uniform([vocab_size, input_embedding_size], -1.0, 1.0), dtype=tf.float32) encoder_inputs_embedded = tf.nn.embedding_lookup(embeddings, encoder_inputs) # - # ## Encoder # # We are replacing unidirectional `tf.nn.dynamic_rnn` with `tf.nn.bidirectional_dynamic_rnn` as the encoder. # from tensorflow.contrib.rnn import LSTMCell, LSTMStateTuple encoder_cell = LSTMCell(encoder_hidden_units) ((encoder_fw_outputs, encoder_bw_outputs), (encoder_fw_final_state, encoder_bw_final_state)) = ( tf.nn.bidirectional_dynamic_rnn(cell_fw=encoder_cell, cell_bw=encoder_cell, inputs=encoder_inputs_embedded, sequence_length=encoder_inputs_length, dtype=tf.float32, time_major=True) ) encoder_fw_outputs encoder_bw_outputs encoder_fw_final_state encoder_bw_final_state # Have to concatenate forward and backward outputs and state. In this case we will not discard outputs, they would be used for attention. # + encoder_outputs = tf.concat((encoder_fw_outputs, encoder_bw_outputs), 2) encoder_final_state_c = tf.concat( (encoder_fw_final_state.c, encoder_bw_final_state.c), 1) encoder_final_state_h = tf.concat( (encoder_fw_final_state.h, encoder_bw_final_state.h), 1) encoder_final_state = LSTMStateTuple( c=encoder_final_state_c, h=encoder_final_state_h ) # - # ## Decoder decoder_cell = LSTMCell(decoder_hidden_units) # Time and batch dimensions are dynamic, i.e. they can change in runtime, from batch to batch encoder_max_time, batch_size = tf.unstack(tf.shape(encoder_inputs)) # Next we need to decide how far to run decoder. There are several options for stopping criteria: # - Stop after specified number of unrolling steps # - Stop after model produced <EOS> token # # The choice will likely be time-dependant. In legacy `translate` tutorial we can see that decoder unrolls for `len(encoder_input)+10` to allow for possibly longer translated sequence. Here we are doing a toy copy task, so how about we unroll decoder for `len(encoder_input)+2`, to allow model some room to make mistakes over 2 additional steps: decoder_lengths = encoder_inputs_length # # +2 additional steps, +1 leading <EOS> token for decoder inputs # ## Output projection # # Decoder will contain manually specified by us transition step: # ``` # output(t) -> output projection(t) -> prediction(t) (argmax) -> input embedding(t+1) -> input(t+1) # ``` # # In tutorial 1, we used `tf.contrib.layers.linear` layer to initialize weights and biases and apply operation for us. This is convenient, however now we need to specify parameters `W` and `b` of the output layer in global scope, and apply them at every step of the decoder. W = tf.Variable(tf.random_uniform([decoder_hidden_units, vocab_size], -1, 1), dtype=tf.float32) b = tf.Variable(tf.zeros([vocab_size]), dtype=tf.float32) # ## Decoder via `tf.nn.raw_rnn` # # `tf.nn.dynamic_rnn` allows for easy RNN construction, but is limited. # # For example, a nice way to increase robustness of the model is to feed as decoder inputs tokens that it previously generated, instead of shifted true sequence. # # ![seq2seq-feed-previous](pictures/2-seq2seq-feed-previous.png) # *Image borrowed from http://www.wildml.com/2016/04/deep-learning-for-chatbots-part-1-introduction/* # First prepare tokens. Decoder would operate on column vectors of shape `(batch_size,)` representing single time steps of the batch. # + assert EOS == 1 and PAD == 0 eos_time_slice = tf.ones([batch_size], dtype=tf.int32, name='EOS') pad_time_slice = tf.zeros([batch_size], dtype=tf.int32, name='PAD') eos_step_embedded = tf.nn.embedding_lookup(embeddings, eos_time_slice) pad_step_embedded = tf.nn.embedding_lookup(embeddings, pad_time_slice) # - # Now for the tricky part. # # Remember that standard `tf.nn.dynamic_rnn` requires all inputs `(t, ..., t+n)` be passed in advance as a single tensor. "Dynamic" part of its name refers to the fact that `n` can change from batch to batch. # # Now, what if we want to implement more complex mechanic like when we want decoder to receive previously generated tokens as input at every timestamp (instead of lagged target sequence)? Or when we want to implement soft attention, where at every timestep we add additional fixed-len representation, derived from query produced by previous step's hidden state? `tf.nn.raw_rnn` is a way to solve this problem. # # Main part of specifying RNN with `tf.nn.raw_rnn` is *loop transition function*. It defines inputs of step `t` given outputs and state of step `t-1`. # # Loop transition function is a mapping `(time, previous_cell_output, previous_cell_state, previous_loop_state) -> (elements_finished, input, cell_state, output, loop_state)`. It is called *before* RNNCell to prepare its inputs and state. Everything is a Tensor except for initial call at time=0 when everything is `None` (except `time`). # # Note that decoder inputs are returned from the transition function but passed into it. You are supposed to index inputs manually using `time` Tensor. # Loop transition function is called two times: # 1. Initial call at time=0 to provide initial cell_state and input to RNN. # 2. Transition call for all following timesteps where you define transition between two adjacent steps. # # Lets define both cases separately. # Loop initial state is function of only `encoder_final_state` and embeddings: def loop_fn_initial(): initial_elements_finished = (0 >= decoder_lengths) # all False at the initial step initial_input = eos_step_embedded initial_cell_state = encoder_final_state initial_cell_output = None initial_loop_state = None # we don't need to pass any additional information return (initial_elements_finished, initial_input, initial_cell_state, initial_cell_output, initial_loop_state) # Define transition function such that previously generated token (as judged in greedy manner by `argmax` over output projection) is passed as next input. def loop_fn_transition(time, previous_output, previous_state, previous_loop_state): def get_next_input(): output_logits = tf.add(tf.matmul(previous_output, W), b) prediction = tf.argmax(output_logits, axis=1) next_input = tf.nn.embedding_lookup(embeddings, prediction) return next_input elements_finished = (time >= decoder_lengths) # this operation produces boolean tensor of [batch_size] # defining if corresponding sequence has ended finished = tf.reduce_all(elements_finished) # -> boolean scalar input = tf.cond(finished, lambda: pad_step_embedded, get_next_input) state = previous_state output = previous_output loop_state = None return (elements_finished, input, state, output, loop_state) # Combine initializer and transition functions and create raw_rnn. # # Note that while all operations above are defined with TF's control flow and reduction ops, here we rely on checking if state is `None` to determine if it is an initializer call or transition call. This is not very clean API and might be changed in the future (indeed, `tf.nn.raw_rnn`'s doc contains warning that API is experimental). # + def loop_fn(time, previous_output, previous_state, previous_loop_state): if previous_state is None: # time == 0 assert previous_output is None and previous_state is None return loop_fn_initial() else: return loop_fn_transition(time, previous_output, previous_state, previous_loop_state) decoder_outputs_ta, decoder_final_state, _ = tf.nn.raw_rnn(decoder_cell, loop_fn) decoder_outputs = decoder_outputs_ta.stack() # - decoder_outputs # To do output projection, we have to temporarilly flatten `decoder_outputs` from `[max_steps, batch_size, hidden_dim]` to `[max_steps*batch_size, hidden_dim]`, as `tf.matmul` needs rank-2 tensors at most. decoder_max_steps, decoder_batch_size, decoder_dim = tf.unstack(tf.shape(decoder_outputs)) decoder_outputs_flat = tf.reshape(decoder_outputs, (-1, decoder_dim)) decoder_logits_flat = tf.add(tf.matmul(decoder_outputs_flat, W), b) decoder_logits = tf.reshape(decoder_logits_flat, (decoder_max_steps, decoder_batch_size, vocab_size)) decoder_prediction = tf.argmax(decoder_logits, 2) # ### Optimizer # RNN outputs tensor of shape `[max_time, batch_size, hidden_units]` which projection layer maps onto `[max_time, batch_size, vocab_size]`. `vocab_size` part of the shape is static, while `max_time` and `batch_size` is dynamic. # + stepwise_cross_entropy = tf.nn.softmax_cross_entropy_with_logits( labels=tf.one_hot(decoder_targets, depth=vocab_size, dtype=tf.float32), logits=decoder_logits, ) loss = tf.reduce_mean(stepwise_cross_entropy) train_op = tf.train.AdamOptimizer().minimize(loss) # - saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) # ## Training on the toy task # Consider the copy task — given a random sequence of integers from a `vocabulary`, learn to memorize and reproduce input sequence. Because sequences are random, they do not contain any structure, unlike natural language. # + batch_size = 33 batches = helpers.random_sequences(length_from=10, length_to=10, vocab_lower=2, vocab_upper=10, batch_size=batch_size) # print('head of the batch:') # for seq in next(batches)[:10]: # print(seq) input_data,output_data = helpers.get_data("./training/") print(len(input_data)) print(len(output_data)) #output_data # - def next_feed(input_val, output_val): # batch = next(batches) # encoder_inputs_, encoder_input_lengths_ = helpers.batch(batch,100) # #print(encoder_inputs_) # decoder_targets_, _ = helpers.batch( # [(sequence) + [EOS] + [PAD] * 2 for sequence in batch],100 # ) # print(encoder_input_lengths_) # for sequence in np.asarray(decoder_targets_.T) : # print(sequence.shape) # # print(decoder_targets_) # # print(len(output_val[10])) encoder_inputs_, _ = helpers.batch(input_val,50) #print(encoder_input_lengths_) otp =[] for sequence in output_val : if(len(sequence)>0) : otp.append((sequence)+[EOS]) else : otp.append([0]) decoder_targets_, _ = helpers.batch(otp,50) #print(np.asarray(decoder_targets_).shape) # for data in np.asarray(decoder_targets_.T) : # print(data.shape) return { encoder_inputs: encoder_inputs_, encoder_inputs_length: np.full(len(input_val),50), decoder_targets: decoder_targets_, } loss_track = [] # + max_batches = 124 batches_in_epoch = 4 num_epoch=125 try: for ep in range (num_epoch) : print("epoch :",ep ) i=0 for batch in range(max_batches/batches_in_epoch): fd = next_feed(input_data[i:i+batches_in_epoch], output_data[i:i+batches_in_epoch]) _, l = sess.run([train_op, loss], fd) loss_track.append(l) print('batch {}'.format(batch)) print(' minibatch loss: {}'.format(sess.run(loss, fd))) predict_ = sess.run(decoder_prediction, fd) # if batch == 0 or batch % batches_in_epoch == 0: # for j, (inp, pred,out) in enumerate(zip(fd[encoder_inputs].T, predict_.T,fd[decoder_targets].T)): # print(' sample {}:'.format(j + 1)) # print(' input > {}'.format(inp)) # print(' predicted > {}'.format(pred)) # print(' target > {}'.format(out)) # if j >= 9: # break i+=batches_in_epoch save_path = saver.save(sess, "./model/model.ckpt") except KeyboardInterrupt: print('training interrupted') # - # %matplotlib inline import matplotlib.pyplot as plt plt.plot(loss_track) print('loss {:.4f} after {} examples (batch_size={})'.format(loss_track[-1], len(loss_track)*batch_size, batch_size))
2-seq2seq-advanced.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.11 64-bit (''base'': conda)' # name: python3 # --- # + import torch from torch import nn from torchvision.io import read_image, ImageReadMode import torchvision.transforms as T from random import randint from IPython.display import clear_output import numpy as np import pylab as pl from src import * # + N_CHANNELS = 16 # Number of CA state channels TARGET_PADDING = 8 # Number of pixels used to pad the target image border TARGET_SIZE = 40 # Size of the target emoji IMAGE_SIZE = TARGET_PADDING+TARGET_SIZE BATCH_SIZE = 4 POOL_SIZE = 512 CELL_FIRE_RATE = 0.5 torch.backends.cudnn.benchmark = True # Speeds up things # + # Starting state def generator(n, device): return make_seed(n, N_CHANNELS-1, IMAGE_SIZE, alpha_channel=3, device=device) pool = SamplePool(POOL_SIZE, generator) imshow(pool[0]) # + tags=[] # Imports the target emoji target = read_image("images/firework.png", ImageReadMode.RGB_ALPHA).float() target = T.Resize((TARGET_SIZE, TARGET_SIZE))(target) target = RGBAtoFloat(target) imshow(target) # - # Define the model device = torch.device("cuda" if torch.cuda.is_available() else "cpu") target = target.to(device) growing = NeuralCA().to(device) folder = "Pretrained_models/firework/Classical_NCAs/" growing.load(folder + "firework_growing.pt") # + new_CA = NeuralCA(device=device) new_CA.load(folder + "firework_growing.pt") L_perturbation = NCADistance(growing, new_CA) L_target = NCALoss(pad(target, TARGET_PADDING), alpha_channels=[3]) criterion = CombinedLoss([L_perturbation, L_target], [ConstantWeight(0, constant=0.01), ConstantWeight(64)]) # + # Train the model for param in growing.parameters(): param.requires_grad = False wandb.init(mode="disabled") optimizer = torch.optim.Adam(new_CA.parameters(), lr=2e-3) scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[40,80], gamma=0.3) new_CA.train_CA(optimizer, criterion, pool, n_epochs=120, skip_update=4, scheduler=scheduler, kind="persist", skip_damage=2, batch_size=10) # - new_CA.plot_losses() ruler.cosine_similarity(growing, new_CA) # + x = make_seed(1, 15, 48, 1, 3) x = growing.evolve(x.cuda(), 1) imshow(x[0]) imshow(new_CA.evolve(x.cuda(), 300)[0].cpu())
pytorch_ca/perturbation_CA.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.9.6 64-bit # name: python3 # --- # # Chapter 2 # # # # Python Data Structures and Control Flow # # # # ## List, Tuples, Set, Dictionary, Sequence # # # + [markdown] slideshow={"slide_type": "subslide"} # ## List # + [markdown] slideshow={"slide_type": "fragment"} # Most of the time you will need to store a list of data and/or values # + slideshow={"slide_type": "fragment"} cubes = [1, 9, 27, 64, 125] cubes # + [markdown] slideshow={"slide_type": "subslide"} # Length or size of the list is determined by function *len* # + slideshow={"slide_type": "fragment"} len(cubes) # + [markdown] slideshow={"slide_type": "subslide"} # Both ***Indexing*** and ***Slicing*** also works for list. # + slideshow={"slide_type": "fragment"} cubes[0] # + slideshow={"slide_type": "fragment"} cubes[1:3] # + slideshow={"slide_type": "subslide"} cubes = [1, 9, 27, 64, 125] cubes[-1] # + slideshow={"slide_type": "fragment"} cubes[2:] # + slideshow={"slide_type": "fragment"} cubes[:2] # + [markdown] slideshow={"slide_type": "subslide"} # Changing the value of a list. # + slideshow={"slide_type": "fragment"} print(cubes[1]) cubes[1] = 2**3 cubes[1] # + [markdown] slideshow={"slide_type": "subslide"} # Lists are mutable type, i.e when a new value is assigned to their contented they are permanently changed. Unlist String type that are immutable. Notice that the cube of 2 was changes from 9 to 8 the correct value.. # + slideshow={"slide_type": "fragment"} cubes[:] # + [markdown] slideshow={"slide_type": "subslide"} # Lists can be added (concatenate) and its slice can be assign. Both operation can increase the size of the list. # + slideshow={"slide_type": "fragment"} title = ['C','H','e','E'] code = [3,0,6] title + code # + slideshow={"slide_type": "fragment"} title[1:3]=['F','K','K'] title # + [markdown] slideshow={"slide_type": "subslide"} # Clear the list by assigning all elements with an empty list. # + slideshow={"slide_type": "fragment"} title[:]=[] title # + [markdown] slideshow={"slide_type": "subslide"} # ### Multidimensional Lists can be created from nested lists. # + slideshow={"slide_type": "fragment"} title = ['C','H','e','E'] code = [3,0,6] mult_list = [title,code] mult_list # + slideshow={"slide_type": "subslide"} mult_list = [title,code] print(mult_list) mult_list[0] # + slideshow={"slide_type": "fragment"} mult_list[1] # + slideshow={"slide_type": "fragment"} mult_list[0][1] # + [markdown] slideshow={"slide_type": "subslide"} # Lets create list of squared numbers from 0-10. # + slideshow={"slide_type": "subslide"} num_list = [1,2,3,4,5,6,7,8,9] squares = [] for n in num_list: print(n) squares.append(n**2) squares # + [markdown] slideshow={"slide_type": "subslide"} # The above is a small program on getting the list of squares. More explanation as we proceed in the book. # > 1. *num_list = [1,2,3,4,5,6,7,8,9]* : creates a list of numbers from 1 - 9 # > 1. *squares = []* : creates an empty list # > 2. *for n in num_list:* : for iterate over the values in num_list and put them in n. # > 3. *print(n)* : print n to screen. # > 4. *squares.append(n\*\*2)* : compute the square of n and append to the end of the squares list. # # # + [markdown] slideshow={"slide_type": "subslide"} # There are other functions for List such as extend, insert, pop, reverse, remove etc. Please check them out. # + slideshow={"slide_type": "fragment"} squares.pop() print(squares) # + slideshow={"slide_type": "fragment"} squares.insert(0,81) squares # + slideshow={"slide_type": "fragment"} squares.reverse() squares # + [markdown] slideshow={"slide_type": "subslide"} # ## Tuples and Sequences # + [markdown] slideshow={"slide_type": "fragment"} # ***string***, ***list*** allow indexing and slicing, they are Sequence data types and so is ***tuple and range*** # + [markdown] slideshow={"slide_type": "subslide"} # A tuple consists of values separated by commas: # + slideshow={"slide_type": "fragment"} t = 1357, 2468, 'python!' t # + slideshow={"slide_type": "fragment"} t[1] # + [markdown] slideshow={"slide_type": "subslide"} # Nested tuple can be created. However tuples are immutable like string. # + slideshow={"slide_type": "fragment"} tt = t,(1,2,3,4) tt # + slideshow={"slide_type": "fragment"} tt[0] # + slideshow={"slide_type": "fragment"} tt[0]=28,'kate' # + [markdown] slideshow={"slide_type": "subslide"} # ### Packing and Unpacking # + slideshow={"slide_type": "fragment"} # packing t = 1357, 2468, 'python!' t # + slideshow={"slide_type": "subslide"} # unpacking x,y,z = t print('x: ', x) print('y: ', y) print('z: ', z) # + [markdown] slideshow={"slide_type": "subslide"} # ## range() Function # + [markdown] slideshow={"slide_type": "fragment"} # The *range()* function returns a sequence of integer. It takes one to three (1-3) arguments. *range(start, end, step)* all are optional except end. # + slideshow={"slide_type": "fragment"} range(10) # + [markdown] slideshow={"slide_type": "subslide"} # The best way is to iterate over the sequence or convert to a list. # + slideshow={"slide_type": "fragment"} # get value from 0 to 5 for i in range(5): print(i) # + slideshow={"slide_type": "subslide"} # get value from 3 to 8 list(range(3,9)) # + slideshow={"slide_type": "fragment"} # get value from 0 to 9 at step of 3 list(range(0,10,3)) # + [markdown] slideshow={"slide_type": "subslide"} # ## Dictionaries # + [markdown] slideshow={"slide_type": "fragment"} # Dictionary (Dict) are key-value type. The indexing is the key and not number. # + slideshow={"slide_type": "fragment"} my_dict = {'a': 65, 'b': 66, 'c': 67, 'd':68} my_dict # + slideshow={"slide_type": "fragment"} my_dict['b'] # + slideshow={"slide_type": "subslide"} for (k,v) in my_dict.items(): print(k,v) # + [markdown] slideshow={"slide_type": "subslide"} # ## Sets # + [markdown] slideshow={"slide_type": "fragment"} # Set is an unoredered collection and does not allow duplicate value. # + slideshow={"slide_type": "subslide"} my_set = {'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun', 'mon'} my_set # + slideshow={"slide_type": "fragment"} 'wed' in my_set # + [markdown] slideshow={"slide_type": "subslide"} # ## Boolean # + [markdown] slideshow={"slide_type": "fragment"} # Boolean data type contains two values *True* or *False*. # + slideshow={"slide_type": "subslide"} 2 < 0 # + slideshow={"slide_type": "fragment"} 2 > 0 # + slideshow={"slide_type": "subslide"} b_cond = 5 > 10 b_cond # + slideshow={"slide_type": "subslide"} is_done = True is_done # + slideshow={"slide_type": "fragment"} is_not_done = False is_not_done # + [markdown] slideshow={"slide_type": "slide"} # ## Decision making and conditional statements # + [markdown] slideshow={"slide_type": "subslide"} # ## *if* Statements # + [markdown] slideshow={"slide_type": "fragment"} # The if statement type is a conditional or decision statement. It operates on the principle that a thing is done base on the truthee state of a question. # + slideshow={"slide_type": "subslide"} yob = int(input("Please enter your year of birth: ")) current_year = 2020 if yob < 0: print('Your year of birth is negative ???') elif yob == 0: print('Your year of birth is zero ??') elif yob < 1900: print('Your year of birth is less than 1900 ?') elif yob > current_year: print('Your year of birth greater than 2020 ?') else: age = current_year - yob msg1 = 'You are {age} years old in {cy}'.format(age=age, cy=current_year) msg2 = 'You are {0} years old in {1}'.format(age, current_year) msg3 = 'You are {} years old in {}'.format(age, current_year) print(msg1) print(msg2) print(msg3) # + [markdown] slideshow={"slide_type": "subslide"} # The code above receive input from keyboard using : # > *input("Please enter your year of birth: ")* # # and convert or cast the value to integer using the expression. # > *int( )* # + [markdown] slideshow={"slide_type": "subslide"} # ## *for* Statements # + [markdown] slideshow={"slide_type": "fragment"} # We have used the ***for** statement in earlier sections. The ***for*** statement iterate over a *list* items. # + slideshow={"slide_type": "subslide"} props = ['name','formulae','molar mass'] for p in props: print(p, len(p)) # + [markdown] slideshow={"slide_type": "subslide"} # To get the sum of odd numbers from 1-10. # + slideshow={"slide_type": "fragment"} start = 1 step = 2 N = 10 sum = 0 for n in range(start,N,step): sum = sum + n print('odd={0}: sum = {1}'.format(n,sum)) # + [markdown] slideshow={"slide_type": "subslide"} # **Quiz** # Try the sum of even numbers. # + [markdown] slideshow={"slide_type": "subslide"} # ## *while* Statements # + [markdown] slideshow={"slide_type": "fragment"} # **while** statements also iterates over a list. However, it only checks if a condition is *True* or *False* to continue to iterate. # + slideshow={"slide_type": "subslide"} n = 0 step = 1 end = 5 while n < end: print(n) n += step # + slideshow={"slide_type": "subslide"} n = 0 step = 2 end = 10 sum = 0 while n < end: sum += n print('even: {n} -> sum: {sum}'.format(n=n,sum=sum)) n += step # + [markdown] slideshow={"slide_type": "subslide"} # ## *break and continue Statements, and else Clauses* on Loops # + [markdown] slideshow={"slide_type": "fragment"} # The ***break*** statement breaks out of a loop, the innermost enclosing loop in a ***for*** or ***while***. # # Unlike any main programming language the ***Python*** has a cool feature in loop statements having an ***else*** clause. It is executed after ***for*** loop termination and ***while*** loop condition is false. # + [markdown] slideshow={"slide_type": "subslide"} # Example: Find the prime numbers from zero to a number. # + slideshow={"slide_type": "subslide"} start = 2 end = 10 primes = [] for n in range(start, end): for x in primes: if n % x == 0: print(n, 'is a multiple of', x) break else: # loop fell through without finding a factor print(n, 'is a prime number') primes.append(n) primes # + [markdown] slideshow={"slide_type": "subslide"} # ## *pass* Statements # + [markdown] slideshow={"slide_type": "fragment"} # The ***pass*** statement is a placeholder and does nothing. It is commonly used for creating minimal ***functions*** and ***classes***. # + slideshow={"slide_type": "subslide"} class MyEmptyClass: pass # + slideshow={"slide_type": "fragment"} def my_empty_func(*args): pass
essential/02.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # HyperTS has built-in rich modeling algorithms for different modes, such as: # # - StatsForecastSearchSpace: Prophet、ARIMA、VAR; # - StatsClassificationSearchSpace: TSForest, k-NNs; # - DLForecastSearchSpace: DeepAR、RNN、GPU、LSTM、LSTNet; # - DLClassificationSearchSpace: RNN、GPU、LSTM、LSTNet. # # The above algorithms are designed with their own default hyperparameter search spaces. If you want to customize your own search space on this basis, you can specify the customized search space through the parameter ```search_space``` when calling ```make_experiment```. # Suppose now we want to modify the search space of the statistical mode under the forecasting task, namely ```StatsForecastSearchSpace```, you can do the following: # # - ~Specify the ```task``` in detail, otherwise it is impossible to judge whether it is a univariate or a multivariate forecast task;~ # - ~Specify the ```timestamp``` column;~ # - ~If there are covariates, set the parameter ```covariables```;~ # - ~**Please strictly abide by the above three steps, otherwise the customization will fail!!!**~ # - If you wish to disable an algorithm and do not search, you can set the parameter to ```False```. For example, ```enable_arima=False```; # - If you wish to change the initialization of the search space parameters of an algorithm, you can pass the parameter ```xxx_init_kwargs={xxx:xxx, ...}```; # - If you wish your custom parameters to be searchable, you can use ```Choice```, ```Int``` and ```Real``` in ```hypernets.core.search_space```. Where, ```Choice``` supports discrete values, ```Int``` supports integer continuous values, and ```Real``` supports float continuous values. For details, please refer to [Search Space](https://github.com/DataCanvasIO/Hypernets/blob/master/hypernets/core/search_space.py). # **Note** # # - We have updated the custom search space and simplified the parameters. # - See **Simplify**. # + from hypernets.core.search_space import Choice, Int, Real from hyperts.framework.search_space.macro_search_space import StatsForecastSearchSpace custom_search_space = StatsForecastSearchSpace(task='univariate-forecast', timestamp='TimeStamp', covariables=['HourSin', 'WeekCos', 'CBWD'], enable_arima=False, prophet_init_kwargs={ 'seasonality_mode': 'multiplicative', 'daily_seasonality': Choice([True, False]), 'n_changepoints': Int(10, 50, step=10), 'interval_width': Real(0.1, 0.5, step=0.1)} ) # + from hyperts.datasets import load_network_traffic from sklearn.model_selection import train_test_split df = load_network_traffic(univariate=True) train_data, test_data = train_test_split(df, test_size=168, shuffle=False) # + from hyperts import make_experiment experiment = make_experiment(train_data.copy(), task='univariate-forecast', timestamp='TimeStamp', covariables=['HourSin', 'WeekCos', 'CBWD'], search_space=custom_search_space) # - # ### Simplify # + from hypernets.core.search_space import Choice, Int, Real from hyperts.framework.search_space.macro_search_space import StatsForecastSearchSpace custom_search_space = StatsForecastSearchSpace(enable_arima=False, prophet_init_kwargs={ 'seasonality_mode': 'multiplicative', 'daily_seasonality': Choice([True, False]), 'n_changepoints': Int(10, 50, step=10), 'interval_width': Real(0.1, 0.5, step=0.1)} ) # + from hyperts.datasets import load_network_traffic from sklearn.model_selection import train_test_split df = load_network_traffic(univariate=True) train_data, test_data = train_test_split(df, test_size=168, shuffle=False) # + from hyperts import make_experiment experiment = make_experiment(train_data.copy(), task='univariate-forecast', timestamp='TimeStamp', covariables=['HourSin', 'WeekCos', 'CBWD'], search_space=custom_search_space)
examples/07_custom_search_space_01.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### 兩種Reverse的解法 # 下面為使用python兩種reverse的解法,其中一種使用工具reverse,後者以數學方法為主,透過2^31作為(32 bit的整數計算) def reverse(x): y = list(str(x)) y.reverse() return int("".join(y)) class Solution: def reverse(self, x: int) -> int: # Turn the attribute to the positive sign_multiplier = 1 if x < 0: sign_multiplier = -1 x = x * sign_multiplier # assign the result parameter result = 0 # signed 32-bit integer min_int_32 = 2 ** 31 while x > 0: # Add the current digit into result # x % 10 is equal to the last digit result = result * 10 + x % 10 # Check if the result is within MaxInt32 and MinInt32 bounds if result * sign_multiplier <= -min_int_32 or result * sign_multiplier >= min_int_32-1: return 0 x = x // 10 # Restore to original sign of number (+ or -) return sign_multiplier * result
Reverse Solutions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # # Read in catalog information from a text file and plot some parameters # # ## Authors # <NAME>, <NAME>, <NAME> # # ## Learning Goals # * Read an ASCII file using `astropy.io` # * Convert between representations of coordinate components using `astropy.coordinates` (hours to degrees) # * Make a spherical projection sky plot using `matplotlib` # # ## Keywords # file input/output, coordinates, tables, units, scatter plots, matplotlib # # ## Summary # # This tutorial demonstrates the use of `astropy.io.ascii` for reading ASCII data, `astropy.coordinates` and `astropy.units` for converting RA (as a sexagesimal angle) to decimal degrees, and `matplotlib` for making a color-magnitude diagram and on-sky locations in a Mollweide projection. # + import numpy as np # Set up matplotlib import matplotlib.pyplot as plt # %matplotlib inline # - # Astropy provides functionality for reading in and manipulating tabular # data through the `astropy.table` subpackage. An additional set of # tools for reading and writing ASCII data are provided with the # `astropy.io.ascii` subpackage, but fundamentally use the classes and # methods implemented in `astropy.table`. # # We'll start by importing the `ascii` subpackage: from astropy.io import ascii # For many cases, it is sufficient to use the `ascii.read('filename')` # function as a black box for reading data from table-formatted text # files. By default, this function will try to figure out how your # data is formatted/delimited (by default, `guess=True`). For example, # if your data are: # # # name,ra,dec # BLG100,17:51:00.0,-29:59:48 # BLG101,17:53:40.2,-29:49:52 # BLG102,17:56:20.2,-29:30:51 # BLG103,17:56:20.2,-30:06:22 # ... # # (see _simple_table.csv_) # # `ascii.read()` will return a `Table` object: tbl = ascii.read("simple_table.csv") tbl # The header names are automatically parsed from the top of the file, # and the delimiter is inferred from the rest of the file -- awesome! # We can access the columns directly from their names as 'keys' of the # table object: tbl["ra"] # If we want to then convert the first RA (as a sexagesimal angle) to # decimal degrees, for example, we can pluck out the first (0th) item in # the column and use the `coordinates` subpackage to parse the string: # + import astropy.coordinates as coord import astropy.units as u first_row = tbl[0] # get the first (0th) row ra = coord.Angle(first_row["ra"], unit=u.hour) # create an Angle object ra.degree # convert to degrees # - # Now let's look at a case where this breaks, and we have to specify some # more options to the `read()` function. Our data may look a bit messier:: # # ,,,,2MASS Photometry,,,,,,WISE Photometry,,,,,,,,Spectra,,,,Astrometry,,,,,,,,,,, # Name,Designation,RA,Dec,Jmag,J_unc,Hmag,H_unc,Kmag,K_unc,W1,W1_unc,W2,W2_unc,W3,W3_unc,W4,W4_unc,Spectral Type,Spectra (FITS),Opt Spec Refs,NIR Spec Refs,pm_ra (mas),pm_ra_unc,pm_dec (mas),pm_dec_unc,pi (mas),pi_unc,radial velocity (km/s),rv_unc,Astrometry Refs,Discovery Refs,Group/Age,Note # ,00 04 02.84 -64 10 35.6,1.01201,-64.18,15.79,0.07,14.83,0.07,14.01,0.05,13.37,0.03,12.94,0.03,12.18,0.24,9.16,null,L1γ,,Kirkpatrick et al. 2010,,,,,,,,,,,Kirkpatrick et al. 2010,, # PC 0025+04,00 27 41.97 +05 03 41.7,6.92489,5.06,16.19,0.09,15.29,0.10,14.96,0.12,14.62,0.04,14.14,0.05,12.24,null,8.89,null,M9.5β,,Mould et al. 1994,,0.0105,0.0004,-0.0008,0.0003,,,,,Faherty et al. 2009,Schneider et al. 1991,,,00 32 55.84 -44 05 05.8,8.23267,-44.08,14.78,0.04,13.86,0.03,13.27,0.04,12.82,0.03,12.49,0.03,11.73,0.19,9.29,null,L0γ,,Cruz et al. 2009,,0.1178,0.0043,-0.0916,0.0043,38.4,4.8,,,Faherty et al. 2012,Reid et al. 2008,, # ... # # (see _Young-Objects-Compilation.csv_) # If we try to just use `ascii.read()` on this data, it fails to parse the names out and the column names become `col` followed by the number of the column: tbl = ascii.read("Young-Objects-Compilation.csv") tbl.colnames # What happened? The column names are just `col1`, `col2`, etc., the # default names if `ascii.read()` is unable to parse out column # names. We know it failed to read the column names, but also notice # that the first row of data are strings -- something else went wrong! tbl[0] # A few things are causing problems here. First, there are two header # lines in the file and the header lines are not denoted by comment # characters. The first line is actually some meta data that we don't # care about, so we want to skip it. We can get around this problem by # specifying the `header_start` keyword to the `ascii.read()` function. # This keyword argument specifies the index of the row in the text file # to read the column names from: tbl = ascii.read("Young-Objects-Compilation.csv", header_start=1) tbl.colnames # Great! Now the columns have the correct names, but there is still a # problem: all of the columns have string data types, and the column # names are still included as a row in the table. This is because by # default the data are assumed to start on the second row (index=1). # We can specify `data_start=2` to tell the reader that the data in # this file actually start on the 3rd (index=2) row: tbl = ascii.read("Young-Objects-Compilation.csv", header_start=1, data_start=2) # Some of the columns have missing data, for example, some of the `RA` values are missing (denoted by -- when printed): print(tbl['RA']) # This is called a __Masked column__ because some missing values are # masked out upon display. If we want to use this numeric data, we have # to tell `astropy` what to fill the missing values with. We can do this # with the `.filled()` method. For example, to fill all of the missing # values with `NaN`'s: tbl['RA'].filled(np.nan) # Let's recap what we've done so far, then make some plots with the # data. Our data file has an extra line above the column names, so we # use the `header_start` keyword to tell it to start from line 1 instead # of line 0 (remember Python is 0-indexed!). We then used had to specify # that the data starts on line 2 using the `data_start` # keyword. Finally, we note some columns have missing values. data = ascii.read("Young-Objects-Compilation.csv", header_start=1, data_start=2) # Now that we have our data loaded, let's plot a color-magnitude diagram. # Here we simply make a scatter plot of the J-K color on the x-axis # against the J magnitude on the y-axis. We use a trick to flip the # y-axis `plt.ylim(reversed(plt.ylim()))`. Called with no arguments, # `plt.ylim()` will return a tuple with the axis bounds, # e.g. (0,10). Calling the function _with_ arguments will set the limits # of the axis, so we simply set the limits to be the reverse of whatever they # were before. Using this `pylab`-style plotting is convenient for # making quick plots and interactive use, but is not great if you need # more control over your figures. plt.scatter(data["Jmag"] - data["Kmag"], data["Jmag"]) # plot J-K vs. J plt.ylim(reversed(plt.ylim())) # flip the y-axis plt.xlabel("$J-K_s$", fontsize=20) plt.ylabel("$J$", fontsize=20) # As a final example, we will plot the angular positions from the # catalog on a 2D projection of the sky. Instead of using `pylab`-style # plotting, we'll take a more object-oriented approach. We'll start by # creating a `Figure` object and adding a single subplot to the # figure. We can specify a projection with the `projection` keyword; in # this example we will use a Mollweide projection. Unfortunately, it is # highly non-trivial to make the matplotlib projection defined this way # follow the celestial convention of longitude/RA increasing to the left. # # The axis object, `ax`, knows to expect angular coordinate # values. An important fact is that it expects the values to be in # _radians_, and it expects the azimuthal angle values to be between # (-180º,180º). This is (currently) not customizable, so we have to # coerce our RA data to conform to these rules! `astropy` provides a # coordinate class for handling angular values, `astropy.coordinates.Angle`. # We can convert our column of RA values to radians, and wrap the # angle bounds using this class. ra = coord.Angle(data['RA'].filled(np.nan)*u.degree) ra = ra.wrap_at(180*u.degree) dec = coord.Angle(data['Dec'].filled(np.nan)*u.degree) fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111, projection="mollweide") ax.scatter(ra.radian, dec.radian) # By default, matplotlib will add degree tick labels, so let's change the # horizontal (x) tick labels to be in units of hours, and display a grid: fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111, projection="mollweide") ax.scatter(ra.radian, dec.radian) ax.set_xticklabels(['14h','16h','18h','20h','22h','0h','2h','4h','6h','8h','10h']) ax.grid(True) # We can save this figure as a PDF using the `savefig` function: fig.savefig("map.pdf") # ## Exercises # Make the map figures as just above, but color the points by the `'Kmag'` column of the table. # Try making the maps again, but with each of the following projections: `aitoff`, `hammer`, `lambert`, and `None` (which is the same as not giving any projection). Do any of them make the data seem easier to understand?
tutorials/plot-catalog/plot-catalog.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %load_ext autoreload # %autoreload 2 # + import os import sys sys.path.append('/Users/ns5kn/Documents/insight/projects/factCC/models') import baseline from transformers import BertForSequenceClassification, BertTokenizer # + tokenizer_mode = 'bert-base-cased' tokenizer = BertTokenizer.from_pretrained(tokenizer_mode) sentence_0 = "This research was consistent with his findings." sentence_1 = "His findings were compatible with this research." inputs_1 = tokenizer.encode_plus(sentence_0, sentence_1, add_special_tokens=True, return_tensors='pt') # - print(inputs_1) classification_mode = 'bert-base-cased' model = BertForSequenceClassification.from_pretrained(classification_mode, force_download=True) pred_1 = model(inputs_1['input_ids'], token_type_ids=inputs_1['token_type_ids'])[0] # [0].argmax().item() print(pred_1)
notebooks/Debugging.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import ee import geemap.foliumap as geemap Map = geemap.Map() Map.add_basemap("HYBRID") dataset = ee.ImageCollection("CIESIN/GPWv411/GPW_Population_Density").first() raster = dataset.select('population_density') raster_vis = { "max": 1000.0, "palette": ["ffffe7", "FFc869", "ffac1d", "e17735", "f2552c", "9f0c21"], "min": 200.0, } Map.setCenter(79.1, 19.81, 3) Map.addLayer(raster, raster_vis, 'population_density') Map.add_colorbar( colors=raster_vis["palette"], vmin=raster_vis["min"], vmax=raster_vis["max"] ) Map Map.publish(name="World Population Density")
examples/notebooks/world_pop_density.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="jYysdyb-CaWM" # # Fully-Connected Layers Tutorial on Fashion MNIST Data Set # - # This is a naive tutorial on how to use `Dense` (Fully-connected Layer) to train and predict the Fashion MNIST data set # + colab={} colab_type="code" id="dzLKpmZICaWN" # TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # Helper libraries import numpy as np import matplotlib.pyplot as plt print(tf.__version__) # + [markdown] colab_type="text" id="yR0EdgrLCaWR" # ## Import the Fashion MNIST dataset # + [markdown] colab_type="text" id="DLdCchMdCaWQ" # This guide uses the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset which contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 by 28 pixels), as seen here: # # <table> # <tr><td> # <img src="https://tensorflow.org/images/fashion-mnist-sprite.png" # alt="Fashion MNIST sprite" width="600"> # </td></tr> # <tr><td align="center"> # <b>Figure 1.</b> <a href="https://github.com/zalandoresearch/fashion-mnist">Fashion-MNIST samples</a> (by Zalando, MIT License).<br/>&nbsp; # </td></tr> # </table> # # Fashion MNIST is intended as a drop-in replacement for the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset—often used as the "Hello, World" of machine learning programs for computer vision. The MNIST dataset contains images of handwritten digits (0, 1, 2, etc.) in a format identical to that of the articles of clothing you'll use here. # # This guide uses Fashion MNIST for variety, and because it's a slightly more challenging problem than regular MNIST. Both datasets are relatively small and are used to verify that an algorithm works as expected. They're good starting points to test and debug code. # # Here, 60,000 images are used to train the network and 10,000 images to evaluate how accurately the network learned to classify images. You can access the Fashion MNIST directly from TensorFlow. Import and load the Fashion MNIST data directly from TensorFlow: # + colab={} colab_type="code" id="7MqDQO0KCaWS" fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() # + [markdown] colab_type="text" id="t9FDsUlxCaWW" # Loading the dataset returns four NumPy arrays: # # * The `train_images` and `train_labels` arrays are the *training set*—the data the model uses to learn. # * The model is tested against the *test set*, the `test_images`, and `test_labels` arrays. # # The images are 28x28 NumPy arrays, with pixel values ranging from 0 to 255. The *labels* are an array of integers, ranging from 0 to 9. These correspond to the *class* of clothing the image represents: # # <table> # <tr> # <th>Label</th> # <th>Class</th> # </tr> # <tr> # <td>0</td> # <td>T-shirt/top</td> # </tr> # <tr> # <td>1</td> # <td>Trouser</td> # </tr> # <tr> # <td>2</td> # <td>Pullover</td> # </tr> # <tr> # <td>3</td> # <td>Dress</td> # </tr> # <tr> # <td>4</td> # <td>Coat</td> # </tr> # <tr> # <td>5</td> # <td>Sandal</td> # </tr> # <tr> # <td>6</td> # <td>Shirt</td> # </tr> # <tr> # <td>7</td> # <td>Sneaker</td> # </tr> # <tr> # <td>8</td> # <td>Bag</td> # </tr> # <tr> # <td>9</td> # <td>Ankle boot</td> # </tr> # </table> # # Each image is mapped to a single label. Since the *class names* are not included with the dataset, store them here to use later when plotting the images: # + colab={} colab_type="code" id="IjnLH5S2CaWx" class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # + colab={} colab_type="code" id="bW5WzIPlCaWv" train_images = train_images / 255.0 test_images = test_images / 255.0 # - tf.keras.backend.set_floatx('float64') # + [markdown] colab_type="text" id="Ee638AlnCaWz" # To verify that the data is in the correct format and that you're ready to build and train the network, let's display the first 25 images from the *training set* and display the class name below each image. # + [markdown] colab_type="text" id="59veuiEZCaW4" # ## Build the model # # Building the neural network requires configuring the layers of the model, then compiling the model. # + [markdown] colab_type="text" id="Gxg1XGm0eOBy" # ### Set up the layers # # The basic building block of a neural network is the *layer*. Layers extract representations from the data fed into them. Hopefully, these representations are meaningful for the problem at hand. # # Most of deep learning consists of chaining together simple layers. Most layers, such as `tf.keras.layers.Dense`, have parameters that are learned during training. # + colab={} colab_type="code" id="9ODch-OFCaW4" model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10) ]) # + colab={} colab_type="code" id="Lhan11blCaW7" model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # + [markdown] colab_type="text" id="Z4P4zIV7E28Z" # ### Feed the model # # To start training, call the `model.fit` method—so called because it "fits" the model to the training data: # + colab={} colab_type="code" id="xvwvpA64CaW_" model.fit(train_images, train_labels, epochs=10) # + [markdown] colab_type="text" id="W3ZVOhugCaXA" # As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.91 (or 91%) on the training data. # + [markdown] colab_type="text" id="wCpr6DGyE28h" # ### Evaluate accuracy # # Next, compare how the model performs on the test dataset: # + train_loss, train_acc = model.evaluate(train_images, train_labels, verbose=2) print('\nTrain accuracy:', train_acc) # + colab={} colab_type="code" id="VflXLEeECaXC" test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\nTest accuracy:', test_acc) # + [markdown] colab_type="text" id="v-PyD1SYE28q" # ### Make predictions # # With the model trained, you can use it to make predictions about some images. # The model's linear outputs, [logits](https://developers.google.com/machine-learning/glossary#logits). Attach a softmax layer to convert the logits to probabilities, which are easier to interpret. # + colab={} colab_type="code" id="DnfNA0CrQLSD" probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()]) # + colab={} colab_type="code" id="Gl91RPhdCaXI" predictions = probability_model.predict(test_images) # + [markdown] colab_type="text" id="x9Kk1voUCaXJ" # Here, the model has predicted the label for each image in the testing set. Let's take a look at the first prediction:
examples/tfExamples/00_FCLayer_Fashon_MNIST_F64.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="Iwn4nmRpHrcy" colab_type="text" # # Easy Stock and Flow modelling on cadCAD # # This colab notebook shows an quick try on creating an encapsulated manner for generating stock and flow simulations on cadCAD # # Authors: # * <NAME> (<EMAIL>) # * <NAME> (put here) # * Add your name here # # + id="4o4sGIX58Xdh" colab_type="code" colab={} ## Dependences ## # %%capture # !pip install cadcad from collections import namedtuple from types import SimpleNamespace import pandas as pd import numpy as np import matplotlib.pyplot as plt from cadCAD.configuration import Configuration from cadCAD.engine import ExecutionMode, ExecutionContext, Executor # + id="LEuisJV78X5u" colab_type="code" colab={} ## Stock / Flow classes ## ## Ignore this code block if you just want to do things Relation = namedtuple('relation', ['src', 'dst']) Flow = namedtuple('flow', ['name', 'src', 'dst', 'function', 'policy']) class Stock(): """ Stock representing an cadCAD variable / state update function """ count = 0 def __init__(self, name: str, n: float): self.name = name self.count = n def __lshift__(self, other: object): return Relation(other, self) def __rshift__(self, other: object): return Relation(self, other) def __repr__(self): return "Stock(name={}, count={})".format(self.name, self.count) class Nowhere(Stock): """ Stock for allowing flows from nowhere. """ count = None name = "nowhere" def __init__(self): pass class System: """ Container for the stocks and flows. Represents an cadCAD configuration. """ nowhere = None stocks = [] flows = [] def __init__(self): self.nowhere = Nowhere() def add_stock(self, name: str, n: float): """ Add a stock on the system instance. """ stock = Stock(name, n) self.stocks.append(stock) return stock def gen_flow_policy(self, relation: Relation, function: callable): """ Generates an cadCAD policy based on the flow and associated stocks. """ def new_function(params, step, sL, s): y = function(s[relation.src.name], s[relation.dst.name], params[0], s) return {relation.dst.name: y, relation.src.name: -y} return new_function def add_flow(self, name: str, relation: Relation, function: callable=None): """ Creates an flow in the system. Uses an sum relation by default. """ if function is None: function = lambda src, dst: src + dst policy = self.gen_flow_policy(relation, function) flow = Flow(name, *relation, function, policy) self.flows.append(flow) def gen_state_update(self, variable_name: str): """ Creates an generic cadCAD state update function. """ def new_function(params, step, sL, s, _input): y = variable_name x = s[y] x += _input.get(y, 0) return (y, x) return new_function def generate_config(self, initial_state: dict={}, sim_config: dict={}, **kwargs): """ Generates an cadCAD configuration dictionary based on the system instance. """ variables = {} state_update = {} variables['nowhere'] = np.inf # Create variables and partial state update blocks for stock in self.stocks: variables[stock.name] = stock.count state_update[stock.name] = self.gen_state_update(stock.name) state_update['nowhere'] = lambda params, step, sL, s, _input: ('nowhere', np.inf) # Create policy update blocks policies = {} for flow in self.flows: policies[flow.name] = flow.policy partial_state_update_blocks = [{"policies": policies, "variables": state_update }] # The configuration dict config = Configuration(initial_state=variables, partial_state_update_blocks=partial_state_update_blocks, sim_config=sim_config) return config def run(self, T: int=100, N: int=1, params: dict={}): """ Simulate the system instance on cadCAD on single proc mode. """ sim_config = {'T': range(T), 'N': N, 'M': params} config = self.generate_config(sim_config=sim_config) exec_mode = ExecutionMode() exec_context = ExecutionContext(exec_mode.single_proc) executor = Executor(exec_context, [config]) raw_result, tensor = executor.execute() return raw_result # + id="HW7LvYft8Z_V" colab_type="code" outputId="589dd484-7dc2-42d3-ac9d-30967d5bc14c" colab={"base_uri": "https://localhost:8080/", "height": 451} ## The actual stock and flow modelling code block ## # System s = System() nowhere = s.nowhere # Stocks prey = s.add_stock('prey', 100) predator = s.add_stock('predator', 10) # Parameters dt = 0.01 params = {'prey_birth_rate': 1.0 * dt, 'predator_birth_rate': 0.0 * dt, 'prey_death_rate': 0.03 * dt, 'predator_death_rate': 1.0 * dt, 'prey_predator_interaction': 0.05 * dt} # Flows s.add_flow('1', nowhere >> prey, lambda src, dst, params, s: dst * params['prey_birth_rate']) s.add_flow('2', nowhere >> predator, lambda src, dst, params, s: dst * params['predator_birth_rate']) s.add_flow('3', predator >> nowhere, lambda src, dst, params, s: src * params['predator_death_rate']) s.add_flow('4', prey >> nowhere, lambda src, dst, params, s: src * params['prey_death_rate']) s.add_flow('5', prey >> predator, lambda src, dst, params, s: src * dst * params['prey_predator_interaction']) # Simulation raw_results = pd.DataFrame(s.run(T=3000, params=params)) results = raw_results plt.xlabel("prey") plt.ylabel("predator") plt.plot(results.prey, results.predator, '.-') plt.show() # + id="OMY7JnbQXBUP" colab_type="code" outputId="351fb690-df4d-44fe-9668-8ff3a2622260" colab={"base_uri": "https://localhost:8080/", "height": 279} results = raw_results[-100:] plt.xlabel("prey") plt.ylabel("predator") plt.plot(results.prey, results.predator, '.-') plt.show() # + id="LnkkOlzWvwHV" colab_type="code" colab={} # + id="H6NlpEEzvwKE" colab_type="code" outputId="6c7e8f39-f584-48e9-d678-ae20f09debea" colab={"base_uri": "https://localhost:8080/", "height": 51} lista = [1, 2, 5, -1] dicionario = {"a": 5, "b": 9} for nome, valor in dicionario.items(): print("{}\t{:.5f}".format(nome, valor)) # + id="96J4jEr7vwPk" colab_type="code" outputId="acb6db0a-8817-492a-e62d-732c637efaec" colab={"base_uri": "https://localhost:8080/", "height": 34} parametros = {"valor_1": 10, "valor_2": 15} print("{valor_1}: {valor_2}".format(**parametros)) # + id="HMUjJLOdvwU1" colab_type="code" outputId="ff17b179-55b2-452f-adf4-ff67592ef55a" colab={"base_uri": "https://localhost:8080/", "height": 34} "".join([t.replace("q", " -") for t in "qwert yuiop".split(" ")]) # + id="B4mpWc8XvwXh" colab_type="code" outputId="fc1c786b-e110-4284-97fa-aec34be2e3c6" colab={"base_uri": "https://localhost:8080/", "height": 34} sujo = " asdasdqwdqwcwq q d wq qw q " limpo = (sujo.replace("a", "") .replace("q", "-") # .replace("b", "c") .strip()[::2]) print(limpo) # + id="3guZnTXavwSt" colab_type="code" outputId="bf1c5c77-407f-4638-8600-9d729e733d1d" colab={"base_uri": "https://localhost:8080/", "height": 34} limpo # + id="dmBvb-devwNv" colab_type="code" colab={} # + id="W85RA2eKXhM9" colab_type="code" outputId="80cff31b-520f-4077-9608-532bb6c9f0ea" colab={"base_uri": "https://localhost:8080/", "height": 419} raw_results # + id="7qn7-QsBaose" colab_type="code" outputId="73425149-b358-4598-a34a-e198b6f4a7f6" colab={"base_uri": "https://localhost:8080/", "height": 34} nowhere >> predator # + id="PROFtb9poyoK" colab_type="code" colab={}
notebooks/Danlessa_istock_and_flow.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import os #numbers of files to load nFiles = 4 # + #concat all pcaTrainFiles fname = os.path.abspath("Train/pcaTrainAggregate.txt") F = open(fname,'w') text = "" fnammee = 'Train/pcaTrain' for n in range(1,nFiles+1): lines = open(fnammee+str(n)+".txt").readlines() lines = lines[1:] for line in lines: F.write(line) F.close() # + #concat all pcaTrainFiles fname = os.path.abspath("Train/mouthTrainAggregate.txt") F1 = open(fname,'w') text = "" fnammee = 'Train/mouthTrain' for n in range(1,nFiles+1): lines = open(fnammee+str(n)+".txt").readlines() for line in lines: F1.write(line) F1.close() # -
AggregateTrainingData.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python (bot) # language: python # name: bot # --- from IPython.core.display import display, HTML display(HTML("<style>.container { width:90% !important; }</style>")) # + code_folding=[84, 94, 102, 113, 125, 133, 147, 170, 187, 201, 226, 255] import telebot #Biblioteca de criação do Bot Telegram from re import sub from time import sleep from os import walk, path from datetime import date from string import punctuation from ipynb.fs.full.chamar import init from ipynb.fs.full.pegaof import pega_ofertas from dateutil.relativedelta import relativedelta from ipynb.fs.full.xml2pdf_semforn import iniciapdf from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton #Biblioteca dos botões e markup meses = [] nome_meses = ['JANEIRO', 'FEVEREIRO', 'MARÇO', 'ABRIL', 'MAIO', 'JUNHO', 'JULHO', 'AGOSTO', 'SETEMBRO', 'OUTUBRO', 'NOVEMBRO', 'DEZEMBRO'] now = date.today() for i in range(3,-1,-1): #Calcula os 3 meses anteriores x = relativedelta(months=i) meses.append({nome_meses[((now - x).month)-1]:(now - x).month}) def junta_dici(ld): '''Função pra juntar uma lista de dicionários em um único''' resultado = {} for dici in ld: resultado.update(dici) return resultado def junta_loja(pessoa): '''Função pra juntar as lojas contidas em um dicionário em uma única lista''' ljs = [] if pessoa['lj1']: ljs.append('0') if pessoa['lj2']: ljs.append('1') if pessoa['lj3']: ljs.append('2') if pessoa['lj4']: ljs.append('3') if pessoa['lj5']: ljs.append('4') if pessoa['lj6']: ljs.append('5') if pessoa['lj7']: ljs.append('6') return ljs meses_junto = junta_dici(meses) lis_dici = [{'ID':'0','FORN':'','NUMERO':0,'lj1':False,'lj2':False,'lj3':False,'lj4':False,'lj5':False,'lj6':False,'lj7':False,'pdf':False, 'mes':now.month}] def insere_ld(id_,item, mes=0, forn=0, numero=0): '''Função pra inserir algo nas escolhas do usuário''' global lis_dici #Pega o dict de escolhas pelo global for i in lis_dici: if i['ID'] == id_: if numero == 1: i['NUMERO'] = item i['FORN'] = 0 print(i) return True if numero and forn: raise ValueError if item == 'pdf': i['pdf'] = True return True if item == 'preconf': i['pdf'] = False return True if not mes and not forn: #Se não mes e forn, o item mandado vira True i[item] = True return True elif mes: #Se mes, declara o mes de preferencia dentro do dict de escolhas i['mes'] = item return True elif forn: #Se forn, declara o forn de preferencia dentro do dict de escolhas i['FORN'] = sub('[^0-9]', '', item) #Deixa apenas os digitos i['NUMERO'] = 0 return True lis_dici.append({'ID':id_,'lj1':False,'lj2':False,'lj3':False,'lj4':False,'lj5':False,'lj6':False,'lj7':False,'pdf':False, 'mes':now.month}) #Se não achar o ID ele cria um insere_ld(id_, item, mes, forn, numero) #E manda inserir oq foi pedido dentro do id criado def limpa_ld(id_): '''zera as escolhas que não forem ID, MES ou FORN''' global lis_dici for i in lis_dici: if i['ID'] == id_: for k,v in i.items(): if k != 'ID' and k != 'mes' and k != 'FORN': i[k] = False def pega_escolhas(id_): '''Função pra retornar o dict de escolhas a partir de um ID''' global lis_dici for i in lis_dici: if i['ID'] == id_: return i def uma_linha(nome_arquivo): '''Função pra abrir arquivos de texto e retornar a primeira linha''' with open (f'C:/Users/pdv/Desktop/gabriel/{nome_arquivo}', 'r') as arquivo: for linha in arquivo: return linha chaveapi = uma_linha('chaveapitelebot.txt') #Pega a chave API do bot de um arquivo local bot = telebot.TeleBot(chaveapi) #Cria uma instância do bot def checkforn(forn): '''Função que devolve uma lista de fornecedores (e cnpjs) a partir de uma string''' cnpjs, nomes, cnpj = [], [], '' with open("cnpjs.txt", 'r') as cads: for linha in cads: if forn.lower() in linha.lower(): cnpj = ''.join([i for i in linha[-19:-9] if i not in punctuation]) cnpjs.append(cnpj) nomes.append(linha[0:-19]) return (cnpjs, nomes) def faz_botao(dicionario): '''Função pra criar os botões de resposta''' markup = InlineKeyboardMarkup() #inicia o markup (marcação) for botao, retorno in dicionario.items(): #Desempacota os botões e seus retornos do dicionário markup.add(InlineKeyboardButton(str(botao), callback_data=str(retorno))) #cria o botão dentro do markup return markup #retorna o markup def poezero(num): '''Função pra pegar um mes e se for menor que 10 coloca o zero''' try: num = int(num) except: print('erro no poezero') mes = '' if num <= 9: mes = f'0{str(num)}' else: mes = str(num) return mes def envia(mensagemID, pdf = 0): '''Função para enviar documentos ou fotos pro usuário''' pasta = fr'C:\Users\pdv\projetos_jupyter\retorno\\{mensagemID}' if pdf: pasta = fr'C:\Users\pdv\Desktop\selenium-imgs\pdfs\\{mensagemID}' for diretorio, subpastas, arquivos in walk(pasta): if not arquivos: text = 'Desculpe, não achei notas desse fornecedor nessa loja' bot.send_message(mensagemID,text) return 0 for arquivo in arquivos: x = path.join(pasta, arquivo) if pdf: file = open(x, 'rb') bot.send_document(mensagemID, file) file.close() else: photo = open(x,'rb') bot.send_photo(mensagemID, photo=photo) photo.close() bot.reply_to(mensagem, 'pronto ;)') #Mensagem pra mostrar que deu certo def pega_ofertas(): pastas = { 'Dalbem': r'C:\Users\pdv\Desktop\selenium-imgs\Dalbem\feito', 'Fartura': r'C:\Users\pdv\Desktop\selenium-imgs\Fartura', 'Goodbom': r'C:\Users\pdv\Desktop\selenium-imgs\goodbom', 'Oba': r'C:\Users\pdv\Desktop\selenium-imgs\oba', 'Pague Menos': r'C:\Users\pdv\Desktop\selenium-imgs\PagueMenos', } dict_ofertas = {} for merc,pasta in pastas.items(): for diretorio, subpastas, arquivos in walk(pasta): for arquivo in arquivos: dict_ofertas[merc] = f'ofertas: {pasta}' break return dict_ofertas def envia_ofertas(mensagemID, pasta): '''Função para enviar ofertas pro usuário''' for diretorio, subpastas, arquivos in walk(pasta): for arquivo in arquivos: x = path.join(pasta, arquivo) file = open(x, 'rb') if 'pdf' in arquivo: bot.send_document(mensagemID, file) else: bot.send_photo(mensagemID, file) file.close() @bot.message_handler(commands=["ofertas"]) def ofertas(mensagem): mensagemID = mensagem.chat.id bot.send_message(mensagemID,'Qual mercado?' , reply_markup = faz_botao(pega_ofertas())) @bot.message_handler(commands=["numero"]) def numero(mensagem): '''Função que gerencia o /numero''' id_ = mensagem.chat.id #O id é uma parte da estrutura aninhada da mensagem ({'content_type': 'text', 'id': 9, 'message_id': 9,'from_user': {'id': 945441763, 'is_bot': False, 'first_name': 'Gbr', 'username': 'Gbrdoidao', 'last_name': 'Doidao', 'language_code': 'pt-br', 'can_join_groups': None, 'can_read_all_group_messages': None, 'supports_inline_queries': None}, 'date': 1649940793,'chat': {'id': 945441763, 'type': 'private', 'title': None, 'username': 'Gbrdoidao', 'first_name': 'Gbr', 'last_name': 'Doidao', 'photo': None, 'bio': None, 'description': None, 'invite_link': None, 'pinned_message': None, 'permissions': None, 'slow_mode_delay': None, 'message_auto_delete_time': None, 'sticker_set_name': None, 'can_set_sticker_set': None, 'linked_chat_id': None, 'location': None},'sender_chat': None, 'forward_from': None, 'forward_from_chat': None, 'forward_from_message_id': None, 'forward_signature': None, 'forward_sender_name': None, 'forward_date': None, 'reply_to_message': None, 'via_bot': None, 'edit_date': None, 'media_group_id': None, 'author_signature': None, 'text': 'ao', 'entities': None, 'caption_entities': None, 'audio': None, 'document': None, 'photo': None, 'sticker': None, 'video': None, 'video_note': None, 'voice': None, 'caption': None, 'contact': None, 'location': None, 'venue': None, 'animation': None, 'dice': None, 'new_chat_member': None, 'new_chat_members': None, 'left_chat_member': None, 'new_chat_title': None, 'new_chat_photo': None, 'delete_chat_photo': None, 'group_chat_created': None, 'supergroup_chat_created': None, 'channel_chat_created': None, 'migrate_to_chat_id': None, 'migrate_from_chat_id': None, 'pinned_message': None, 'invoice': None, 'successful_payment': None, 'connected_website': None, 'reply_markup': None, 'json': {'message_id': 9, 'from': {'id': 945441763, 'is_bot': False, 'first_name': 'Gbr', 'last_name': 'Doidao', 'username': 'Gbrdoidao', 'language_code': 'pt-br'}, 'chat': {'id': 945441763, 'first_name': 'Gbr', 'last_name': 'Doidao', 'username': 'Gbrdoidao', 'type': 'private'}, 'date': 1649940793, 'text': 'ao'}}) if len(mensagem.text) < 11: bot.send_message(id_, 'preciso de mais números') return global meses_junto numero = mensagem.text[8:] #Pega a parte importante da mensagem (sem o /numero ) insere_ld(id_, item=numero, numero=1) print(mensagem.from_user.username, mensagem.from_user.first_name, ' pesquisou notas n° ', numero) dicio_pdf = {'Preço Notas':'numero preconf','Nota em PDF':'numero pdf'} #Botão pdf / preço {'nome_botão':'retorno do botão'} # dicio_lojas = {'LJ1 - Guanabara':'lj1' ,'LJ2 - Primavera':'lj2','LJ3 - Iguatemi':'lj3','LJ4 - Flamboyant':'lj4', 'LJ5 - São Paulo':'lj5', # 'LJ6 - Valinhos':'lj6', 'LJ7 - Ouro Verde':'lj7', 'ESCOLHIDO':'escolheu'} #Botões das lojas e seus retornos bot.send_message(id_, ' Qual Mes? ', reply_markup=faz_botao(meses_junto)) #Botao pro user escolher o mes da nota bot.send_message(id_, ' Qual vc prefere? ' ,reply_markup=faz_botao(dicio_pdf)) #Cria o botão pro escolher entre PDF e meu preço # bot.send_message(id_, ' LOJAS: ' ,reply_markup=faz_botao(dicio_lojas)) #Cria o botão pro escolher entre PDF e meu preço @bot.message_handler(commands=["notas"]) def notas(mensagem): '''Função que gerencia o /notas''' global meses_junto id_ = mensagem.chat.id #O id é uma parte da estrutura aninhada da mensagem ({'content_type': 'text', 'id': 9, 'message_id': 9,'from_user': {'id': 945441763, 'is_bot': False, 'first_name': 'Gbr', 'username': 'Gbrdoidao', 'last_name': 'Doidao', 'language_code': 'pt-br', 'can_join_groups': None, 'can_read_all_group_messages': None, 'supports_inline_queries': None}, 'date': 1649940793,'chat': {'id': 945441763, 'type': 'private', 'title': None, 'username': 'Gbrdoidao', 'first_name': 'Gbr', 'last_name': 'Doidao', 'photo': None, 'bio': None, 'description': None, 'invite_link': None, 'pinned_message': None, 'permissions': None, 'slow_mode_delay': None, 'message_auto_delete_time': None, 'sticker_set_name': None, 'can_set_sticker_set': None, 'linked_chat_id': None, 'location': None},'sender_chat': None, 'forward_from': None, 'forward_from_chat': None, 'forward_from_message_id': None, 'forward_signature': None, 'forward_sender_name': None, 'forward_date': None, 'reply_to_message': None, 'via_bot': None, 'edit_date': None, 'media_group_id': None, 'author_signature': None, 'text': 'ao', 'entities': None, 'caption_entities': None, 'audio': None, 'document': None, 'photo': None, 'sticker': None, 'video': None, 'video_note': None, 'voice': None, 'caption': None, 'contact': None, 'location': None, 'venue': None, 'animation': None, 'dice': None, 'new_chat_member': None, 'new_chat_members': None, 'left_chat_member': None, 'new_chat_title': None, 'new_chat_photo': None, 'delete_chat_photo': None, 'group_chat_created': None, 'supergroup_chat_created': None, 'channel_chat_created': None, 'migrate_to_chat_id': None, 'migrate_from_chat_id': None, 'pinned_message': None, 'invoice': None, 'successful_payment': None, 'connected_website': None, 'reply_markup': None, 'json': {'message_id': 9, 'from': {'id': 945441763, 'is_bot': False, 'first_name': 'Gbr', 'last_name': 'Doidao', 'username': 'Gbrdoidao', 'language_code': 'pt-br'}, 'chat': {'id': 945441763, 'first_name': 'Gbr', 'last_name': 'Doidao', 'username': 'Gbrdoidao', 'type': 'private'}, 'date': 1649940793, 'text': 'ao'}}) enviado = mensagem.text[7:] #Pega a parte importante da mensagem (sem o /notas ) fornecedor = checkforn(enviado) print('resultado checkforn: ', fornecedor) if not fornecedor[0]: bot.reply_to(mensagem, 'Fornecedor nâo encontrado') #Mensagem pra mostrar que deu errado a busca de forn return 0 if len(fornecedor[0]) > 1: dicio_forn = {} for cnpj in fornecedor[0]: for empresa in fornecedor[1]: dicio_forn[empresa] = f'forn: {cnpj}' bot.send_message(id_, 'Qual Fornecedor?', reply_markup=faz_botao(dicio_forn)) else: insere_ld(id_, fornecedor[0][0], forn=1) #Coloca o fornecedor em escolhas (dicionario do user) print(mensagem.from_user.username, mensagem.from_user.first_name, ' pesquisou notas do ', fornecedor) dicio_pdf = {'Preço Notas':'preconf','Nota em PDF':'pdf'} #Botão pdf / preço {'nome_botão':'retorno do botão'} dicio_lojas = {'LJ1 - Guanabara':'lj1' ,'LJ2 - Primavera':'lj2','LJ3 - Iguatemi':'lj3','LJ4 - Flamboyant':'lj4', 'LJ5 - São Paulo':'lj5', 'LJ6 - Valinhos':'lj6', 'LJ7 - Ouro Verde':'lj7', 'ESCOLHIDO':'escolheu'} #Botões das lojas e seus retornos bot.send_message(id_, ' Qual Mes? ', reply_markup=faz_botao(meses_junto)) #Botao pro user escolher o mes da nota bot.send_message(id_, ' Qual vc prefere? ' ,reply_markup=faz_botao(dicio_pdf)) #Cria o botão pro escolher entre PDF e meu preço bot.send_message(id_, ' LOJAS: ' ,reply_markup=faz_botao(dicio_lojas)) #Cria o botão pro escolher entre PDF e meu preço @bot.message_handler(func=lambda message: True) #Decorador que cuida de mensagens (não comandos) def resposta(mensagem): '''Função que cuida de mensagens sem comandos (/) ''' texto = '''Olá! Seja bem vindo ao Fartura Bot Estes são os meus Comandos: /notas <Nome Fornecedor> /ofertas =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=''' #Mensagem padrão de resposta bot.reply_to(mensagem, texto) #Responde a mensagem dele com o texto padrão @bot.callback_query_handler(func=lambda call: True) def handle_query(chamado): '''Função pra cuidar dos retornos (callbacks) do KeyboardButtons''' id_ = chamado.message.chat.id retorno = chamado.data inteiro = False num = 0 try: inteiro = int(retorno) except: pass if retorno.startswith('lj') or retorno == 'pdf' or retorno == 'preconf': insere_ld(id_,retorno) elif retorno.startswith('numero'): insere_ld(id_,item=retorno[7:]) num = 1 print('escolhido foi') elif retorno.startswith('ofertas: '): envia_ofertas(id_, retorno[9:]) elif inteiro and inteiro in range(13): #Pega o retorno dos botões de meses insere_ld(id_, retorno, mes=1) elif retorno.startswith('forn:'): insere_ld(id_, retorno, forn=1) if retorno == 'escolheu' or num == 1: print('to no escolhido') escolhas = pega_escolhas(id_) lojas = junta_loja(escolhas) mes = poezero(escolhas['mes']) pdf = escolhas['pdf'] forn = escolhas['FORN'] numero = escolhas['NUMERO'] if pdf: if num == 0: r = iniciapdf(id1 = str(id_), fornecedor=forn, numero=numero, lojas=lojas, mes=mes) #Chama a função de criar pdf if num == 1: r = iniciapdf(id1 = str(id_),numero=numero, mes=mes) #Chama a função de criar pdf envia(id_, pdf=1) else: if num == 0: r = init(ean = forn, mes = mes, loja = lojas, idz = str(id_), numero=numero) #Chama a função de criar dataframes dos preços if num == 1: r = init(idz = str(id_), numero=numero, mes = mes) #Chama a função de criar dataframes dos preços envia(id_, pdf=0) limpa_ld(id_) while True: #Esse while é o que mantém o código sempre rodando try: bot.polling(none_stop=True, interval=0, timeout=0) #Mantém o bot rodando infinitamente except: sleep(10) #se der erro ele espera 10 segundos # - '''import time def calcula_tempo(funcao): def wrapper(*args, **kwargs): tempo_comeco = time.time() x = funcao(*args, **kwargs) tempo_final = time.time() print(f'sua função demorou {tempo_final - tempo_comeco}') return x return wrapper l1 = list(range(-200,4000)) l2 = list(range(3000)) l3 = [] @calcula_tempo def checa_lista(l1,l2,l3): for i in l1: if i not in l2: l3.append(i) return l3 print(checa_lista(l1,l2,l3)) @calcula_tempo def Diff(l1, l2): return list(set(l1) - set(l2)) + list(set(l2) - set(l1)) print(Diff(l1,l2))''' pip install schedule
BOT_FARTURA-NUMERO.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.6.2 # language: julia # name: julia-1.6 # --- push!(LOAD_PATH, "/home/zhenan/Github/AtomicOpt.jl") using AtomicOpt using Plots using Images using LinearAlgebra using SparseArrays using FFTW using LinearMaps # ## Load data xs = Vector{Float64}() xd = Vector{Float64}() b = Vector{Float64}() m = 0 n = 0 ks = 0 kd = 0 lines = readlines("./StarGalaxyData.txt", keep=true) for line in lines info = split(line) if length(info) ≥ 1 if info[1] == "xs" for s in info[3:end] push!(xs, parse(Float64, s)) end elseif info[1] == "xd" for s in info[3:end] push!(xd, parse(Float64, s)) end elseif info[1] == "b" for s in info[3:end] push!(b, parse(Float64, s)) end elseif info[1] == "ks" ks = parse(Int64, info[3]) elseif info[1] == "kd" kd = parse(Int64, info[3]) elseif info[1] == "m" m = parse(Int64, info[3]) elseif info[1] == "n" n = parse(Int64, info[3]) end end end # ## Construct atomic sets τs = gauge(OneBall(n*m), xs) As = τs*OneBall(n*m; maxrank = ks) τd = gauge(OneBall(n*m), dct(xd)) Q = LinearMap(p->idct(p), q->dct(q), n*m, n*m) Ad = τd*Q*OneBall(n*m; maxrank = kd) A = As + Ad # ## Solve demixing problem sol = level_set(I(m*n), b, A, tol = 1e-1, maxIts=5000) # ## Plot x = constructPrimal(sol) colorview(Gray, reshape(x[1], m, n)) colorview(Gray, reshape(x[2], m, n)) x2 = sol.F.faces[2] * sol.c[ks+1:end] colorview(Gray, reshape(x2, m, n))
examples/StarGalaxy/StarGalaxyDemixing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Load data import numpy as np import sklearn import scipy.misc # + # loading data x_train = np.loadtxt("data/train_x.csv", delimiter=",") y_train = np.loadtxt("data/train_y.csv", delimiter=",") x_test = np.loadtxt("data/test_x.csv", delimiter=",") # x_train = x.reshape(-1, 64, 64) # y_train = y.reshape(-1, 1) # x_test = x.reshape(-1, 64, 64) # - # ## Split training data into train / valid sets from sklearn.model_selection import train_test_split x_train, x_valid, y_train, y_valid = train_test_split(x_train, y_train, train_size=0.8, test_size=0.2) data = { "x_train": x_train, "x_valid": x_valid, "y_train": y_train, "y_valid": y_valid } # # Baseline Linear Classifier: Linear SVM from sklearn import metrics from sklearn.svm import LinearSVC # + def baseline_linear_svm(data): """ Using out-of-the-box linear SVM to classify data """ clf = LinearSVC() y_pred = clf.fit(data["x_train"], data["y_train"]).predict(data["x_valid"]) print(y_pred) return metrics.accuracy_score(data["y_valid"], y_pred, average="macro"), y_pred # score, y_pred = baseline_linear_svm(data) # print(score) # -
KaggleComp.ipynb