scieee AI-readable full text Open interactive document viewer

Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta

Barroso i Domínguez, Eduard,Rivas Vallès, Sergi

Abstract

The motivation of the project is to model and predict the volume of arrivals at the emergency department (ED) of a general hospital. The process consists of complex linear and nonlinear patterns together. Those types of temporal series are tough to solve efficiently using Box-Jenkins methods (ARIMA models) due its high stochastic behaviour and nonlinearity. Once the time series analysis is discarded owing the bad results obtained, and in order to change the approach of the task, artificial neural networks (ANN) are chosen to solve the problem. This methodology offers a whole new perspective of study, enabling the use of algorithms in a high tight time constraint in order to predict intraday information such as the arrivals expected to occur in the afternoon using morning information. The objective is to program a plain applicative, able to extract the data needed (endogenous and exogenous variables), compute the ANN algorithm and finally show the relevant results in order to help improving the human and material resources management in the area of emergencies. As a fundamental part of the project, the best methodology to work with ANN algorithms is seek in order to settle an accurate approach for future studies.

Full text

DEGREE’S FINAL PROJECT Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Eduard Barroso & Sergi Rivas [email protected]; sergirivas.92, @gmail.com Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 1 Page 2 Degree’s Final Project 1. Abstract The motivation of the project is to model and predict the volume of arrivals at the emergency department (ED) of a general hospital. The process consists of complex linear and nonlinear patterns together. Those types of temporal series are tough to solve efficiently using Box- Jenkins methods (ARIMA models) due its high stochastic behaviour and nonlinearity. Once the time series analysis is discarded owing the bad results obtained, and in order to change the approach of the task, artificial neural networks (ANN) are chosen to solve the problem. This methodology offers a whole new perspective of study, enabling the use of algorithms in a high tight time constraint in order to predict intraday information such as the arrivals expected to occur in the afternoon using morning information. The objective is to program a plain applicative, able to extract the data needed (endogenous and exogenous variables), compute the ANN algorithm and finally show the relevant results in order to help improving the human and material resources management in the area of emergencies. As a fundamental part of the project, the best methodology to work with ANN algorithms is seek in order to settle an accurate approach for future studies. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 3 2. Summary 1. Abstract .............................................................................................................................................. 2 2. Summary ........................................................................................................................................... 3 3. Introduction ..................................................................................................................................... 6 3.1. Purpose of the project .......................................................................................................... 6 3.2. Scope of the project ............................................................................................................... 6 4. Body of the report .......................................................................................................................... 7 4.1. Planning .................................................................................................................................... 7 4.2. Processing the data ............................................................................................................... 8 Code structure .............................................................................................................................. 8 Functions ........................................................................................................................................ 8 Database creation ..................................................................................................................... 13 4.3. Descriptive analysis ........................................................................................................... 15 Preview of the system ............................................................................................................ 15 Characterization of the system ........................................................................................... 15 4.4. Time series analysis .......................................................................................................... 19 Conclusions for the Time Series analysis ....................................................................... 24 4.5. Artificial Neural Networks .............................................................................................. 25 Neural Net package.................................................................................................................. 25 4.5.1.1. ANN first font code ................................................................................................................................................... 25 4.5.1.2. ANN first predictions .............................................................................................................................................. 27 4.5.1.3. Nnet package ............................................................................................................................................................... 30 Nnet package .............................................................................................................................. 30 4.5.2.1. Disaggregate the information ............................................................................................................................. 32 4.5.2.2. Data Sets ........................................................................................................................................................................ 32 4.5.2.3. Respiratory type ........................................................................................................................................................ 33 4.5.2.4. Organic type................................................................................................................................................................. 35 4.5.2.5. Cardiovascular type ................................................................................................................................................. 36 4.5.2.6. Features for each data set ..................................................................................................................................... 36 4.5.2.7. Features in detail ....................................................................................................................................................... 38 4.5.2.7.1 Respiratory type ................................................................................................................................................. 38 4.5.2.7.2 Organic type .......................................................................................................................................................... 39 R Stuttgart Neural Network Simulator library ............................................................ 40 4.5.3.1. Learning in RSNNS ................................................................................................................................................... 40 4.5.3.1.1 General learning procedure .......................................................................................................................... 40 4.5.3.1.2 Backpropagation learning functions......................................................................................................... 41 4.5.3.1.3 Quickpropagation learning function ......................................................................................................... 42 Page 4 Degree’s Final Project 4.5.3.1.4 Resilient propagation learning function ................................................................................................. 42 4.5.3.2. Update Functions in RSNNS ................................................................................................................................. 43 4.5.3.3. Initialization Functions in RSNNS ..................................................................................................................... 44 4.5.3.4. Algorithm development ......................................................................................................................................... 44 4.5.3.4.1.1 Variable introduction .............................................................................................................................. 44 4.5.3.4.1.2 Error analysis .............................................................................................................................................. 45 4.5.3.4.1.3 Cross Validation ......................................................................................................................................... 51 4.5.3.4.2 Consistency analysis ......................................................................................................................................... 51 4.5.3.4.2.1 Variable normalization .......................................................................................................................... 53 4.5.3.5. Topology selection ................................................................................................................................................... 54 4.5.3.5.1.1 Factorial experiment ............................................................................................................................... 54 4.6. Artificial Neural Networks: python implementation ............................................ 64 Why Python? .............................................................................................................................. 64 Steps before training ............................................................................................................... 65 PyBrain ......................................................................................................................................... 66 4.6.3.1. PyBrain code ............................................................................................................................................................... 66 Class implementation ............................................................................................................. 71 4.6.4.1. ANN code....................................................................................................................................................................... 71 4.6.4.2. Python conclusions .................................................................................................................................................. 78 5. Conclusions ................................................................................................................................... 79 6. Economic study ............................................................................................................................ 81 7. Environmental study ................................................................................................................. 84 8. Bibliography ................................................................................................................................. 85 9. ANNEX 1 .......................................................................................................................................... 87 9.1. Core of the algorithm ........................................................................................................ 87 9.2. Factorial experiment code .............................................................................................. 92 9.3. .................................................................................................................................................... 94 9.4. PyBrain documentation ................................................................................................... 95 Create and process the data sets........................................................................................ 95 Define the layers structure and oolean ........................................................................... 96 Build a standard multilayer perceptron ......................................................................... 96 Define the training algorithm .............................................................................................. 96 9.5. Auxiliary python libraries ............................................................................................... 98 Math ............................................................................................................................................... 98 Random ........................................................................................................................................ 98 Numpy ........................................................................................................................................... 98 Datetime .................................................................................................................................... 100 Matplotlib ................................................................................................................................. 100 Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 5 9.6. R documentation ............................................................................................................... 103 Nnet ............................................................................................................................................. 103 RSNNS ........................................................................................................................................ 104 9.6.2.1. mlp ................................................................................................................................................................................ 104 9.7. Futures paths to follow ................................................................................................... 105 Support vector regression ................................................................................................. 105 How it Works? ........................................................................................................................ 105 SVR over sklearn .................................................................................................................... 106 Page 6 Final degree project 3. Introduction 3.1. Purpose of the project The goal of the project is to create a useful application for the Hospital Universitari de Girona Dr. Josep Trueta in order to control and predict the volume of arrivals at the emergency department (ED). The whole day (24 hours) has been divided in two particular strips: from 07:00 to 13:00 corresponding to the first strip, and the rest of the day as the second strip. The executable, using the appropriate covariates (extracted from the first strip) and algorithms programmed (ANN), should be able to predict the amount of patients left to come in the same day for the last strip. By estimating the parameters with good accuracy, the applicative might be useful for the institution in order to improve the resource management and logistics of this particular area as they program the second part of the day after midday. 3.2. Scope of the project In order to ensure the functionality of the executable, there are two important topics that must be accurately solved. First of all, from a full analysis and thanks to a deep understanding of the general flow of the process, select the right and more explicative covariates. And second, choose and develop the proper algorithm to fit the real model in the best possible way. The first point has been solved by a large and deep descriptive analysis using all the data available in order to understand the process and their explicative variables. The second has been approached using the time series Box-Jenkins methodology (ARIMA). Despite this is a quite powerful tool for time series analysis, in these particular cases, where the data has a predominant random behaviour, the methodology does not offer the accuracy required. After comparing and studying different options, the knowledge and experience leads to use soft computing tools such as artificial neural networks (ANN) or support vector machine (SVM) algorithms. ANN’s offer universal function approximation capability on the data itself, i.e. they are purely empirical models that can theoretically mimic any relation to any nine-degree of precision. In practicality they have limitations in their approximation capability by finite and noisy data sets, and stochastic relationships that can mask the final results. So, once the main characteristics are analysed this methodology seems enough powerful and appropriate to face the posed problem. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 7 4. Body of the report 4.1. Planning January Redact December Program the executable Product design November Improve the ANN code Introduce new covariates Code tests Transcript code from R to python October Python font code Choose optimum model First functional code for ANN Pre-project Understand the process Temporal series analysis Study of the best approaches Learn statistical software (RStudio) Page 8 Final degree project 4.2. Processing the data To deal with the huge amount of data generated each year by the hospital, some tools like spreadsheets or statistical software are not flexible enough to manipulate the volume of data. For this reason a python plug-in is required to process the data and create a compatible format for the R scripts. Code structure The data brought by the hospital is divided in two files that have to be merged in a single database. To do so, a python code has to parse both files, drop all the information into a python compatible structure and proceed to join the data. Those steps are implemented in separated functions and can be easily adapted to bring different data sets. The main difficulty of this problem is the time structure. All the data in the files is referenced by a typical date, thus it is necessary to translate it to a single magnitude such as hours. All those calculations are performed with the python library datetime taking 01/01/2010 as time reference. Functions Given two dates returns the difference between both in years. This function is a key element to reduce the time schema into a single magnitude. from datetime import datetime, date def time_to_years(reference_date, current_date): FMT = '%d/%m/%Y' t1 = datetime.strptime(reference_date, FMT) t2 = datetime.strptime(current_date, FMT) t_difference = t2 - t1 time = int(t_difference.days/365) return time Parses each attribute from a given icodi line according to their type (either integer or string). Return the processed line in a list. This function is part of the process of reading the file and is not intended to work by itself. def processIcodiRow(icodiLine): icodi = int(icodiLine[0]) diagnosticCode = icodiLine[1] ps = icodiLine[2] return [icodi, diagnosticCode, ps] Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 15 4.3. Descriptive analysis Preview of the system The Hospital Universitari de Girona Dr. Josep Trueta is a health public centre managed by the Institut Català de la Salut (ICS). The centre offers assistance to the most of people from Girona. It covers all the basic medical and chirurgical specialties, characteristic of any tertiary hospital. The emergency department receives more than 70000 admissions each year and 190 in average per day. There are five basic types of typologies the patients can present when they arrive to the emergency department:  Type 1: triage I. Resuscitation. Situations where resuscitation is required. Vital risk.  Type 2: triage II. Emergency. High urgent situations. Predictable vital risk.  Type 3: triage III. Urgent. Situations of potential risk.  Type 4: triage IV: Less urgent. Potentially complex situations without vital risk.  Type 5: triage V: Not urgent. Situations that allows delay of attention. No risk detected. Despite the organization by types, it’s interesting to keep in mind that each category seen above can be part of another medical classification:  Trauma: study of the injuries or alterations of the locomotor system.  Pediatrics: study and treatment of infant injuries and diseases.  Gynecology and obstetrics: study of the female reproductive system and the pregnancy, birth and puerperium.  Medical surgical: all the rest of the medical cases. As a more general classification:  Respiratory: presenting injuries or alterations of the respiratory system.  Cardiovascular: presenting injuries or alterations of the cardiovascular system.  Organic: general injuries, everyone that does not fit neither of the groups shown above. Characterization of the system As a first approach it’s interesting to visualize the flow in the emergency department along a week (from Monday to Sunday). Plot 1. Number of emergencies per day of the week Page 16 Final degree project Mondays are the most crowded days as some people wait for recover during the weekend but if they could not make it, they have to go to the hospital the first day of the week. Also along the weekend most of the primary attention centres are closed. The second pic of demand, it is placed on Fridays (specially the last years 2012, 2013, as people do not want to lose labour days in the emergency department because of the crisis). It is also interesting to appreciate the general distribution of the different typologies and its comparison. Plot 2. Number of emergencies according its typology per day of the week The plot shows the data for the year 2013 and it has approximately the same behaviour for the rest of the years:  Typologies III (Urgent) and IV (Less urgent) are the most representative ones. Having this amount of typology III shows the hospital behaves correctly (there are hospitals with high demand from IV and V).  The amount of cases I (Resuscitation) and II (Emergency) have the lower rate and as will be seen, its distribution it’s completely random. As there are four complete years of data, could be useful to observe each typology distribution for each year studied. Plot 3. Number of emergencies (Resuscitation) per day of the week Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 17 Plot 4. Number of emergencies (Emergency) per day of the week Plot 5. Number of emergencies (Urgent) per day of the week Plot 6. Number of emergencies (Less urgent) per day of the week . Page 18 Final degree project Plot 7. Number of emergencies (Not urgent) per day of the week The most interesting conclusion, observing the plots above, it’s how the less random typologies (especially III and IV) follow carefully the average week distribution, as the other ones, with a higher random component, seems to behave quite chaotically. This is a really important observation when it comes to build a model that suits the real data, as if only the less random typologies are taken the algorithm should get better results. Another interesting study consists in determining how the arrivals are distributed along the day. In order to visualize this information the data is organized in time periods of one hour. Plot 8. Number of emergencies per time slot From the plot above is clear that despite the year studied, the general flow of arrivals, follows quite similar patterns. Is interesting to highlight how the flat curve in the early morning hours, is followed by a pronounced rise among the morning and midday and after reaching the morning peak, a slight fall followed by a quite chaotic afternoon oscillating between the same values, and finally another decrease to get to the night hours. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 19 4.4. Time series analysis Once the descriptive analysis was completed, as a first approach to solve the problem, a time series model was set. Even though it is not going to be used for getting suitable solutions for the current project, seems a good idea to summarize the steps that have been followed using the ARIMA methodology as well as a brief resume of the results achieved. The student Eduard Barroso has been engaged with the Hospital Universitari de Girona Dr. Josep Trueta due being working as an intern during the summer of 2014. All along this period, despite analysing in detail the volume and occupation in the emergency department, a times series analysis has been performed in order to be able to forecast the volume of emergencies. In the current chapter (2.4), only the most useful conclusions are explained. Time series analysis embraces methods for analysing time series in order to extract meaningful statistics and other characteristics from the data. Time series forecasting is the use of a model to predict future values based on previously observed values. The studied data, which clearly follows a stochastic pattern, it’s build up by a sequence of random variables evolving through time. It must be said that the methodology used for work with time series does not require a huge amount of computations but does need repeated calculations involving a great number of variables. Because of the reasons presented, the analysis it’s made using free statistical software called RStudio. Methodology used: - Model identification: study of the main time series components (trend, seasonality, cycles and random). Trend: there is a long-term increase or decrease in the data. Seasonal: series influenced by seasonal factors. Seasonality is always of a fixed and known period. Cyclic: when the time series exhibits rises and falls that are not of fixed period. The duration of this fluctuations is usually, at least, of two years. - Model fitting: using R functions and corroborating the results with the correlograms. - Model tuning and prediction. - Error testing. Page 20 Final degree project In the first section, Data Reading, the data for each year can be loaded and set as a temporal series for further analysis. Then, with the help of several plots, like monthplot or decompose the features (trend, seasonality, randomness) of the series can be analysed. In case it presents a clear trend, it can be erased from the model by applying the differentiation (second section). As this whole sections represents a sneak peak of the time series analysis, the ARIMA model, has been fitted using the FORECAST R package. In the nineteenth line of the last section, the first ARIMA model fitted, has been chosen according to the results of eighteenth line (auto.arima) and its correlograms. Another interesting function it is the one that decomposes the time series in the different intrinsic components (decompose). Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 21 Plot 9. Time series components for the year 2012 (Decompose function applied) - Parameters estimation: fitting the data with the best ARIMA model according to AIC (Akaike information criterion) as the parameter to be optimized. Combining the variables in different ARIMA models allows us to decide which the better ones are in order to fit the model. Page 22 Final degree project After analyse all the ARIMA models according to the AIC criterion, the best one is chosen to fit the real data. Next step consists in make the predictions with the selected model. Also it is interesting to plot the results of the prediction together with the real data. Plot 10. Predictions (blue line) and real values (red line) The prediction of the first week of 2013, as observed, it is quite disappointing as it has most of the values outside the 85% interval confidence, and even some of them outside the 95%. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 23 - Hypothesis validation (Ljung-Box methodology): study of the residuals. Plot 11. Residuals of the time series analysis Plot 12. Density of the residuals Page 24 Final degree project Observing the Box test and the residuals distribution seems that the model is correctly adjusted. However, the predictions obtained are not good for a forecast exercise. Conclusions for the Time Series analysis After several tests using ARIMA models, seems that the data studied it is not susceptible to be modelled by this method. Its erratic component does not let the forecast perform close to the reality. In order to try to lower the random phenomenon in the process, different assumptions are taken: - Model only the typology of patients that do not follow a random distribution (like types I, II and V), such as types III, IV. - Predict spots amongst the year, and not use the whole year in order to forecast the first week of the next year as this is located in a critic dates. With the dictated assumptions, new results are found. The best one is the follow one: Plot 13. Predictions (blue line) and real values (red line) In this case, using only the less random types of medical typologies (III and IV), and forecasting between the year (in this case a week among October), the results are notably better. Anyway, this is the best case-scenario found among many tests and models used. Also with the assumptions taken, especially the one to take a noncritical week doesn’t offer a good performance of the generalized model. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 31  linout: switch for linear output units. Default logistic output units. The predictions are not meant to pursue a classification, so there is the need of using a linear output.  maxit: maximum number of iterations. Default 100. When processing the algorithm, if there is no convergence, the analysis stops when reaching the 1000 iterations in the current algorithm.  decay: parameter for weight decay. Default 0. Over-fitting is a recurrent problem when using neural networks, it is useful to set the decay different to 0, as it penalizes large weights, so partially preventing from over-fitting. In our case is set to 1e-4.  formula: a formula of the form class ~ x1 + x2 + ... Another important change that has been made consists in standardized all the variables before they are being applied into the artificial neural network algorithm. The standardization can be calculated with the following code: Once the basic structure of the neural network is set, is time to test it by using different input variables. Pursuing the goal of work with the best possible input variables, several references (books, papers, etc.) had been kept in mind. A remarkable fact, is to be able to use all the knowledge and expertise from people having high ranks inside this concrete field. According both sources, the most used variables for modelling the volume of arrivals at the emergency department, are the following ones: Temperature, Humidity, Vacations/Holidays and if there are some kind of big social event like an important football match for example. After obtaining all the variables required and applying them, the artificial neural network results are notably improved as it allows to predict with less than 14% of RMSE (relative mean square error). Therefore, there is still a problem as it is not possible to predict with less than 9.5% error in any case. This is the main reason to try to solve the problem applying a concrete methodology from scratch. train<-matrix() first = 1 for(q in (1:ncol(train_old))){ m<-mean(as.matrix(train_old[q])) s<-sd(as.matrix(train_old[q])) norm<-(train_old[q]-m)/s norm if (first == 1){ train<-norm first = 0 } else{ train<-cbind(train,norm) } } Page 32 Final degree project 4.5.2.1. Disaggregate the information When it comes to deal with a process that is the result of the aggregation of different non-linear features and its interactions, it may be useful to break up those inputs or parts of the process in order to try to lower its complexity. During this project the following assumptions have been made for, by understanding the subprocesses, improve the accuracy of the predictions: - Instead of using the n past days to forecast the following day, the information of the current day is used. By partitioning the day in two different strips, information of the first strip of the day, can be used to forecast the last strip of the same day. And also allows, like the previous case, the use of delayed information. - Once it is verified that using the total number of arrivals at the emergency department to make the predictions does not offer the desired results, the new approach consists in disaggregate the total amount of patients in three basic typologies: respiratory, circulatory and organics. By analysing each of the three groups, the forecasts are notably better as the algorithm can be particularly modified and adjusted to each different situation. - Another interesting break up could be the one consisting in disaggregate each one of the above three cases by age. Other three categories including the patients aged between 0-16 years, 16-65 years and more than 65 years. As there is not a big volume of arrivals for each type and age combination this option has been discarded in the scope of the present project. - There is another option to disaggregate the data in a functional way. It consists in having in mind the fact that for each of the three categories shown above (respiratory, organics and cardiovascular) they can have 5 different types of patients according to its triage (emergency indicator). It has already been used for the temporal series analysis with quite good results. Even so, in this project this option has not been taken for the same reason explained above: low amount of data for each disaggregated case. Anyway it is a demonstrable fact that selecting the less random types (excluding the most urgent, and less probable type) in order to lower the randomness of the time series. 4.5.2.2. Data Sets The data set used to carry out all the analysis done in the project is based in the data recorded in the emergency department of the hospital during the years 2010, 2011, 2012 and 2013. Knowing that 2012 was a leap year, we have 1461 days to analyse. Actually the study has been done with a few less days since using delayed variables, a week has been lost following that purpose (there is no possibility to have data from 2009). Focusing on the artificial neural network training, the last 180 days of 2013 have been removed and keep as a validation set. The rest of data have been used for the cross validation algorithm (k=9) in order to have different sets: data train and data test. Once the best neural network Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 33 weights have been chosen, they are applied to the validation set data in order to get the predictions in a real trial. Afterwards it is possible to analyse the fitting power and performance of the current algorithm. 4.5.2.3. Respiratory type As a first approach to model the process, a plot of the total arrivals for this medical speciality vs period studied is done. Plot 21. Respiratory emergencies per day (2010-2013) According to the graph above, this type of patients follows a strong seasonality all along the four studied years. It helps us to notice two different phases in each year: two periods of time where the volume of arrivals notability increase (corresponding to the months of winter and autumn) and the other two corresponding to the spring and summer. It is also interesting to plot the arrivals corresponding to the first strip during the whole studied period in order to verify if, for this particular case, it follows the same pattern (the arrivals at the first strip are coloured in red, and the ones at the second one, in black). Page 34 Final degree project Plot 22. Respiratory emergencies per day (2010-2013) It seems that both time series follow a similar pattern. To remark this fact is useful to apply the correlation function to see if there is a real relation. cor(data$A_1,data$Total-data$A_1) [1] 0.5269408 This is an interesting result because due to the partition done, there are two important time series that are quite correlated, and will be an angular point to develop the algorithm towards good fitting. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 35 4.5.2.4. Organic type As a first approach to model the process, a plot of the total arrivals for this medical speciality vs period studied is done. Plot 23. Organic emergencies per day (2010-2013) In this particular case there is no seasonal or even a pattern been followed by the data. Even thought this fact looks worst in therms of the prediction performance, for this type there is a significant larger amount of events which is a good in terms of training the algorithm. It is interesting to check the same steps as in the first case in order to make up and identify differencies between both processes. Plot 24. Organic emergencies per day (2010-2013) Page 36 Final degree project In this case there is no interesting relations between both features. This conclusion is logic as long as we understand that this is the biggest group and it includes all the unclassified cases. Also for this case the correlation is much below than 0.5 (0.23). Even though it does not show any clear relation unlike the case analysed above, it is interesting to try to model this process as it represents a complete different problem, and there is enough amount of data to try to do it. 4.5.2.5. Cardiovascular type This last case of study shows a similar behaviour as the one seen above. The problem, in this case, is that there are not enough amount of data to try to model a good artificial neural network. It is quite disappointing as normally, for this type of patients, there is a clear seasonality as the respiratory ones. Plot 25. Cardiovascular emergencies per day (2010-2013) Clearly, there is not enough registers to work with, and not being able to spot any clear relation, as the respiratory process, it is decided not to analyse this kind of medic speciality. Since they represent, in general, less than a 10% of the total arrivals at the emergency department it does not really altered the goal of try to help with the saturation problem. 4.5.2.6. Features for each data set In order to know which features are better for modelling the respiratory cases (presenting strong seasonality) or for the organic ones, the same kind of features are going to be used for both processes as an initial approximation. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 37 In order to perform this analysis, the already applied Box-Jenkins methodology is used for discover if there exists an autocorrelation or partial autocorrelation within the variables. Plot 26. Auto covariance or autocorrelation function for the three typologies By comparing the three plots, the relation between the seasonality of the respiratory type and the high autocorrelation presented in the ACF plot, is highlighted. In order to notice the effect of the recent conclusions in a real artificial neural network performance, three similar data sets are set up. Each one has as input, the following covariates: A_1 A_1 (lag 1) A_1 (lag 2) A_1 (lag 3) A_1 (lag 7) T1 (lag 1) T2 (lag 2) T3 (lag 3) T7 (lag 7) Holiday (3 days) Table 1. Explicative variables used in the model Where A_1 stands for the arrivals at the first strip of the day (from 07:00 to 13:00) and T for the total volume of arrivals (A_1+A_2). According to papers with similar goals as the ones pursued in the present one, it is always useful to set the vacation days. In this case when there is an official vacation, it is highlighted with a one (otherwise, zero) the previous, the current, and the following day. Using the same algorithm and parameters for the neural network, it is computed 100 times obtaining one hundred different RMSE values and applying the mean to this vector, there is the chance to notice significant differences for each of the three types (respiratory, organics and cardiovascular). Page 38 Final degree project From a 100 samples for each measure, the following means are obtained: Respiratory 2.802%, 2.810%, 2.805% Organic 10.437% 10.246% 10.335% Cardiovascular 25.455% 25.455% 25.565% Table 2. Relative error for each typology It is clear that for the type with more seasonality (respiratory category), the dynamics of the process can be highly adjusted by using the correct number of lags. The other types are performing much worst, especially in the cardiovascular case that really shows a bad RMSE mean due there are just a few cases during each weak. To conclude, it seems reasonable to keep using the defined inputs (always standardized) for the respiratory type, the same for the organics, knowing that in order to reduce the RMSE some other variables should be introduced, and finally for the cardiovascular type it really does not look like it can be modelled by using this methodology and covariates. 4.5.2.7. Features in detail 4.5.2.7.1 Respiratory type In this case, only using the temporal series, seems to offer quite good adjusted results for the RMSE. It is interesting to observe the plot below where the points are the predicted values for the last half of the year, and the lines in red, the real values for those days. Plot 27. Predicted values in red and real observation in black The RMSE value is really low, it fluctuates between 2.8% and 5%. It could be a good final result/conclusion but since there are several papers proving the existing relations between the Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 39 volume of arrivals for the respiratory type with an approximately ten-fourteen delayed days descend of the temperature, it is interesting to add this feature in order to try to improve the results. The cold temperature index has been obtained using the following formula: After introducing three new features, an index for the measure of the cold temperature and two delays (7 and 10 lags) of this variable, the results after several samples, are not that good as the previous ones and also, analysing the resultant graphs, it seems there is some over-fitting. It is important to notice that since this current temporal series has a seasonal component and is offering good results, it would perform well approximations by using the ARIMA methodology. 4.5.2.7.2 Organic type For this type, using the same kind of covariates as the previous case, the RMSE values oscillates close to the 10.5% of RMSE, so it seems a good data set to try to introduce new explanatory variables in order to reach better results. In this case, it is interesting to try it with the same cold/hot temperature index as the case above. After trying only with the cold temperature index, the results are notability improved (8.8% error) and using the hot temperature index (its used is highly recommended in several papers) it has a better performance (8.4%), even though it is not much different. Plot 28. Predicted values in red and real observation in black It really does not offer such a good perspective as the respiratory type, but even though the process seems to follow a random or chaotic behaviour, a certain kind of pattern can be noticed. There have been more test adding other features like humidity, wind speed, among others but the results have not been improved at all. Page 40 Final degree project Note that all the error percentages presented in references 3.5.2.6 and 3.5.2.7 have not been transformed, again, to the proper scale. R Stuttgart Neural Network Simulator library In order to improve the results, once an exhaustive analysis of the variables has been carried out, a new R package is used for the analysis. The chosen package is the denominated R Stuttgart Network Simulator (RSNNS), which consists in one of the software’s that support the highest number of models (multi-layer perceptrons, recurrent Elman, Jordan networks, radial basis function networks among others). SNNS (Stuttgart Neural Network Simulator) is a simulator for neural networks developed at the Institute for Parallel and Distributed High Performance Systems (Institut für Parallele und Verteilte Höchstleistungsrechner, IPVR) at the University of Stuttgart since 1989. Besides the huge number of models that can be applied, focusing on the multi-layer perceptron (mlp) possibilities, it offers a wide range of learning, update and hidden activation functions. Thanks to this variety, it allows us to seek for better results. As in the other packages, one of the fundamental pieces of the model are the units: input, hidden and output units. The SNNS default activation function is Act_logistic which computes the network input simply by summing over all weighted activations and then squashing the result with the logistic function (𝑓𝑎𝑐𝑡 = 1 (1+𝑒−𝑥)). The output function computes the output of every unit from the current activation of this unit. 4.5.3.1. Learning in RSNNS 4.5.3.1.1 General learning procedure An important spot to focus on with the neural network research, is the question of how to adjust the weights of the links to get the desired system behaviour. This modification is often based on Hebbian rule. It can put in the general form as: ∆𝑤𝑖𝑗=𝑔(𝑎𝑗(𝑡),𝑡𝑗)ℎ(𝑜𝑖(𝑡),𝑤𝑖𝑗) where: 𝑤𝑖𝑗: weight of the link from unit i to unit j. 𝑎𝑗: activation of unit j in step t. 𝑡𝑗: teaching input, desired output of unit j. 𝑜𝑖(𝑡): output of unit i at time t. 𝑔(…): function, depending on the activation of the unit and the teaching input. ℎ(…) : function, depending on the output of the preceding element. In this project the training is carried on using, first, a feed-forward neural network, and then with a Backpropagation model, both, with supervised learning. This techniques consists in the following procedure: Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 47 From down to the top, the random plot presents a random distribution of the error, the seaso nal graph shows a seasonality component that should be investigated. The trend plot strength the argument that there exists an undeniable growth of the error in th e last period of the analysis which also correspond to a highest registers of emergencies. Seasonal component Plot 32. Seasonal plot of the error Monday Tuesday Wednesday Thursday Friday Saturday Sunday 0,09 -1,10 -0,05 -0,5 0,24 0,49 0,63 Table 4. Values of the seasonal component Tuesday has the higher error among the week followed by Saturday and Sunday. From the descriptive analysis, done during the first part of the project, was observed that the higher frequency of emergencies during the week were on the weekend. According to the previous conclusion a new variable, has been introduce in the data set: Day of the week (Dow) indicating with a 1 the days within the weekend and with 0 the others. Monday Tuesday Wednesday Thursday Friday Saturday Sunday 0,27 -0,88 0,14 -0,44 0,38 0,11 0,39 Table 5. Values of the seasonal component Thanks to the new variable the seasonal component has been considerably reduced. Finally, in order to decrease Tuesday’s parameter, this day has been indicated with a -1 obtaining: Monday Tuesday Wednesday Thursday Friday Saturday Sunday 0,17 -0,34 0,09 -0,38 0,50 -0,13 0,10 Table 6. Values of the seasonal component Once the seasonal component of the error time series has been allocated and reduced, and in order to improve the final prediction, the trend component should be also lowered. Page 48 Final degree project Trend component Plot 33. Trend plot of the error As indicated above, the trend clearly increases for the last months, especially on December, of 2013. One interesting thing to notice is that the trend of the error is increasing when the total number of emergencies increases during the year. This can be observed by showing the graph for the total emergencies in 2013. Plot 34. Respiratory emergencies in year 2013 One solution to capture this behaviour would be to add a dummy variable to indicate if the month should be analysed as high frequency period (winter and autumn) indicated with a 1, or low frequency (spring and summer) designated with a 0. Despite the introduction of this new dummy variable to the model, it is still not able to capture this phenomenon and cannot lower the trend for this specific periods. In order to apply a more particular solution, the Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 49 month of December, which is the one where the trend substantially grows, has been designated with a 1 while keeping the other months as 0 and still no differences. In order to lower the trend, several variables have been tested, dummies and others like temperature, or indexes combining temperature and humidity information. Any of them has worked as supposed to. Knowing that, and for improving the model, the neural network parameters and functions should be as tuned as possible. For solving this situation a part of code has been added to the algorithm in order to visualize which the days with the higher errors are during the training and testing. It is also important to know which the biggest errors are done during the training of the neural network. The top 20 errors have been collected thanks to a matrix that is populated during the training period. Tested several times, the values in the top 10 tend to be shown every time. Page 50 Final degree project ID A1.0 T0 Date Weekday Month 1066 7 35 08/12/2012 6 12 698 9 38 06/12/2011 2 12 81 6 31 29/03/2010 1 3 751 6 33 28/01/2012 6 1 723 0 0 31/12/2011 6 12 8 0 18 15/01/2010 5 1 502 3 22 24/05/2011 2 5 688 10 35 26/11/2011 6 11 365 4 31 07/01/2011 5 1 311 5 28 14/11/2010 7 11 1087 0 0 29/12/2012 6 12 654 9 32 23/10/2011 7 10 725 13 38 02/01/2012 1 1 350 4 27 23/12/2010 4 12 1122 9 33 02/02/2013 6 2 442 4 25 25/03/2011 5 3 637 2 21 06/10/2011 4 10 699 8 35 07/12/2011 3 12 737 1 19 14/01/2012 6 1 1133 7 29 13/02/2013 3 2 Table 7. Table of the highest errors obtained in the training From the top error table, seems that the days with high frequency of emergencies (T0) are not well predicted. Also there are two days were the total entries are 0 which probably are real errors in the data set. As observed in the error time series study, the days with the highest number of respiratory emergencies, are the ones within the “cold” months that were indicated, without success, with a 1 (dummy variable). This table gives real valuable information in order to improve the model as confirms the need to introduce a variable capable of capture the dynamics for this particular months. The histogram of the residuals shows that the variance is normally distributed. In the plot above, a bell-shaped histogram which is evenly distributed around zero is shown. Plot 35. Histogram of the error Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 51 4.5.3.4.1.3 Cross Validation Cross Validation is going to be used as a model validation technique for assessing how the results of a statistical analysis will generalize to an independent data set. This also will allow to know how accurately the model is performing in practice. There are several types of cross validation and they can be grouped as exhaustive and non-exhaustive types. Using an exhaustive method, the model will learn and test in all the possible ways to divide the original sample into a training and validation set. On the other hand, the non-exhaustive methods, do not compute all ways of splitting the original sample. For this project is chosen to use the k-fold cross validation, which is one of the nonexhaustive methods. In k-fold, the original sample is randomly partitioned into k equal sized subsamples. Of the k samples, a single subsample is retained as the validation data for testing the model, and the remaining k-1 subsamples are used as training data. This methodology has been chosen according to several good references from similar projects developed by some universities. 4.5.3.4.2 Consistency analysis A key indicator that help to improve the results of the algorithm and that is widely related with some principal neural network parameters such as the learning function or the size, is the error curve generated during the training. This curve, usually has a hyperbolic shape such as the one shown in the plot below. Plot 36. Training error for each iteration. Several conclusions can be obtained from this curve, such as how many iterations took, during the training, to reach a constant error (or a minimum spot) or even can discover if the algorithm is over fitting the weights. Page 52 Final degree project In order to determine the different shapes that this error curve for the data set, several trainings are performed only changing the learning function for each case. All the results are compared in the same plot. Plot 37. Error in the training for each algorithm iteration and learning function This plot is displaying the iterative error for each iteration for the following learning functions (with a size of ten and a logistic output as settings): BackpropWeightDecay (black), Std_Backpropagation (red), Rprop (blue), Quickprop (yellow), BackpropMomentum (green) and BackpropChunk (grey). This plot clearly shows that for this data set, and despite using different parameters to try to tune the algorithm, the Quickprop learning function has an unpredictable error function which is better to avoid while the rest of the models are showing a similar behaviour. Plot 38. Error in the training for each algorithm iteration and learning function Showing the plot for the backpropagation functions (the Rprop has been keep out of the graph) discovers that all of them have a similar shape and they tend to approximately the same value at the same number of iterations. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 53 In the other hand, there is the Rprop learning function which decreases slower than the backpropagation functions, and reaches a lower level of error when the computation has finished. This interpretation could led towards a bad conclusion, as how it is saw in the factorial experiment, the Rprop perform better during the training, but due a possible overfitting, the results in test are worse than using the other learning functions. Plot 39. Error in the training for each algorithm iteration and learning function Another plot with the same error curves obtain from a multi-layer perceptron with a size of 25 instead of 10. In this one, the Quickprop (yellow) learning function still working bad, and Rprop has the same previous behaviour but a little bit more accentuated. Plot 40. Error in the training for each algorithm iteration and learning function 4.5.3.4.2.1 Variable normalization According to multiple tests, the normalization of the variables from the data set is very important to work with the neural networks. The standard procedure consists in transform each variable in order to have it within 0 and 1. This is because when using the logistic Page 54 Final degree project activation function, the values should be set as described. Without applying this normalization the neural network is not working properly. There are different methodologies to transform the data set variables into a range between 0 and 1. The easiest and most used ones, are the standard normalization 𝑥−𝑚𝑒𝑎𝑛(𝑥) 𝑣𝑎𝑟(𝑥) or, even faster, divide the data set by the maximum value. Despite those methods work accurately and allow us to work with the logistic activation function, sometimes, they could be covering up or be distorting some valuable intrinsic information from the variable inner distribution. This is why, as a previous analysis, is worthy to perform an study of which one of the distributions (Normal, Poisson, Exponential, Weibull, etc.) fit better each variable in order to apply the right normalizations respectively. In this case any of the distributions is fitting the variables, hence the standard normalization is choose. 4.5.3.5. Topology selection 4.5.3.5.1.1 Factorial experiment As there are several features that can be used in the RSNNS library, the most important and the ones that have been analysed in the RSNNS section are chosen to be part of a factorial experiment. This factorial experiment is going to have the following independent variables and levels: - Learning function: Std_Backpropagation, BackpropBatch, BackpropChunk, BackpropMomentum, BackpropWeightdecay, Rprop. - Size (number of units in the hidden layer): low (5), moderate (20), high (50) and very high (100). - linOut: sets the activation function of the output units to linear or logistic (Boolean values). The dependent variables are ARV and MSE, but they are calculated two times: one as the result of the training and another for the testing. This is important, as it has been noticed that some good features for training offers worst results in testing than the others. So it is recommendable to perform this kind of analysis when working with neural networks. Another feature that should be monitored is the proportion of the data set that is used for training and testing. All the analysis previously carried out consists in, by using three years and a half, predict the last half of the forth month. Perform the analysis with other proportions (75%-25% or even 50% - 50%) could clarify how the neural network is calculating the results. First Factorial Experiment: using three years and a half for training and half a year for testing. The results are written in a csv file. Thanks to a dynamic table several conclusions can be assumed. The analysis is going to be perform by little by little adding new dimensions (explicative variables). For all the tables displayed in the following analysis the values MSE1 and ARV1 are the results for the training of the neural network (fitting measure) and MSE2 and ARV2 for the test (prediction measure). First, the performance of the different learning functions is tested for both training and testing sets. It is important to remark that each learning function parameters are initialized, in the neural network, with its default values Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 55 MSE1 ARV1 MSE2 ARV2 BackpropBatch 0.1614 1.7139 0.1543 1.6821 BackpropChunk 0.0748 0.2364 0.0631 0.1856 BackpropMomentum 0.0745 0.2345 0.0629 0.1845 BackpropWeightDecay 0.0745 0.2348 0.0626 0.1830 Rprop 0.0696 0.2059 0.0662 0.2059 Std_Backpropagation 0.0745 0.2344 0.0629 0.1850 Table 8. ARV and MSE values for each Learning function The initial results show that all the values get better for test, but this is due there are less values. What is remarkable from the table are the following conclusions: - The BackpropBatch does not work properly for this data set. - The other learning functions based on the backpropagation algorithm are working quite similar. - The Rprop learning function provide the best values in train but the worst in test. This phenomenon happens due to a possible over fitting of the model. Next step, two levels (True or false) of the categorical variable linOut haven been added to the table. It does not bring new important conclusions as the values are similar. MSE1 ARV1 MSE2 ARV2 BackpropBatch FALSE 0.1321 0.7462 0.1302 0.8005 TRUE 0.1908 2.6816 0.1782 2.5638 BackpropChunk FALSE 0.0743 0.2336 0.0623 0.1811 TRUE 0.0751 0.2391 0.0638 0.1901 BackpropMomentum FALSE 0.0747 0.2361 0.0626 0.1829 TRUE 0.0742 0.2330 0.0632 0.1861 BackpropWeightDecay FALSE 0.0744 0.2339 0.0624 0.1815 TRUE 0.0746 0.2353 0.0629 0.1846 Rprop FALSE 0.0691 0.2025 0.0672 0.2121 TRUE 0.0703 0.2093 0.0652 0.1997 Std_Backpropagation FALSE 0.0746 0.2358 0.0628 0.1841 TRUE 0.0742 0.2330 0.0631 0.1858 Table 9. ARV and MSE values for each Learning function and each output function combination As all the explicative variables are set to be within 0 and 1, the linOut parameter is set to false as it implies that the output is not linear but logistic. Page 56 Final degree project Next step consists in analyse the results with different sizes of the hidden layer. This is a tricky decision as there are several external factors implied, when looking for the best number of hidden units. This factors are the following ones according many documentation: Number of input and output units, number of training cases, amount of noise in the targets, the complexity of the function or classification to be learned, the architecture, the type of hidden unit activation function, the training algorithm and regularization. In most situations, there is not a specific methodology to determine the best number of hidden units without training several networks and estimating the generalization error of each. If there are too few hidden units, there will be high training error and high generalization error due to under fitting and high statistical bias. If there are too many hidden units, there will be low training error but still have high generalization error due to over fitting and high variance. There are lots of solutions regarding this problem but most of them only focuses in providing solutions for only some of the factors, but do not offer a good general solution. The best recommendation is to perform a sensitive analysis, similar to the one that is carried out in this project, in order to see for which size of the neural network the generalization error is the lowest one. This generalization error, in machine learning, consists in measure how well a learning machine generalizes to unseen data. It is measured as the distance between the error on the training set and the test set and is averaged over the entire set of possible training data that can be generated after each iteration of the learning process. As this parameter is not easy to obtain, the goodness of each model is related to MSE and ARV values. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 63 learnFRprop:linearTRUE:sizeLay -10.467 learnFStd_Backpropagation:linearTRUE:sizeLay -10.48 Pr(>|t|) (Intercept) 2.00E-16 learnFBackpropChunk 1.40E-09 learnFBackpropMomentum 1.68E-09 learnFBackpropWeightDecay 1.34E-09 learnFRprop 1.53E-09 learnFStd_Backpropagation 1.51E-09 linearTRUE 3.93E-11 sizeLay 0.031 learnFBackpropChunk:linearTRUE 1.00E-06 learnFBackpropMomentum:linearTRUE 1.34E-06 learnFBackpropWeightDecay:linearTRUE 1.22E-06 learnFRprop:linearTRUE 2.33E-06 learnFStd_Backpropagation:linearTRUE 1.26E-06 learnFBackpropChunk:sizeLay 0.1136 learnFBackpropMomentum:sizeLay 0.1167 learnFBackpropWeightDecay:sizeLay 0.1094 learnFRprop:sizeLay 0.0382 learnFStd_Backpropagation:sizeLay 0.1063 linearTRUE:sizeLay <2.00E-16 learnFBackpropChunk:linearTRUE:sizeLay <2.00E-17 learnFBackpropMomentum:linearTRUE:sizeLay <2.00E-18 learnFBackpropWeightDecay:linearTRUE:sizeLay <2.00E-19 learnFRprop:linearTRUE:sizeLay <2.00E-20 learnFStd_Backpropagation:linearTRUE:sizeLay <2.00E-21 Table 14. Summary of the factorial experiment Residual standard error: 0.0287 on 216 degrees of freedom Multiple R-squared: 0.7682, Adjusted R-squared: 0.7435 F-statistic: 31.12 on 23 and 216 DF, p-value: < 2.2e-16 Finally an ANOVA model can be added to test the relation of the different variables with the output (MSE2): Response: TMSE2 Df Sum Sq Mean Sq F value Pr(>F) learnF 5 0.2746 0.0549 66.6878 < 2.2e-16 *** linear 1 0.0039 0.0039 4.8448 0.0288 * sizeLay 1 0.0229 0.0229 27.871 3.15E-07 *** learnF:linear 5 0.0191 0.0038 4.6508 0.000472 *** learnF:sizeLay 5 0.0899 0.0179 21.8401 < 2.2e-16 *** linear:sizeLay 1 0.0284 0.0284 34.5312 1.57E-08 *** learnF:linear:sizeLayer 5 0.1503 0.0301 36.5029 < 2.2e-16 *** Residuals 216 0.1778 0.0008 Table 15. ANOVA of the factorial experiment --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Page 64 Final degree project 4.6. Artificial Neural Networks: python implementation Why Python? Although R is a very powerful tool to train nets and analyse its performance, it doesn’t deliver a user-friendly interface for the end user. Moreover, some of the main neural network packages – such as Theano 1 , Pylearn 2 , Caffe 3 etc. – do not offer support for R. Thus, to get over those problems, the programming language had to be switched into a more versatile option. Two main languages offered a solid alternative to R: C++ and Python. Although C++ is largely used, implementing a neural network proof to be a tough task, whereas in Python codes are simpler and clearer. Moreover, Python also allows writing simple user interfaces and the pipeline defined could be easily redirected if needed. When coming to data, Python also have a clear advantage over R as it allows parsing a file within a few lines. In addition, all the pre-process of the data has been done in Python, so it was the natural evolution of the workflow. In addition to the language, the SDK to develop the application is a key element. In this case, all the Python codes and graphics have been run under the iPython Notebook 4 . This tool has the ability to run the code in independent blocks, always maintaining the value of the variables in a debug mode. 1 http://deeplearning.net/software/theano/ 2 https://github.com/lisa-lab/pylearn2/ 3 http://caffe.berkeleyvision.org/ 4 http://ipython.org/notebook.html Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 65 Steps before training To train the neural network, in any of the studied cases, it is necessary to load all the data into a python format. To do so, two functions have been implemented to parse the data from a csv format into a two-dimensional NumPy 5 array and normalize the data. The first one, reads a given file, and returns a NumPy array with all the information. By means of the normalization flag, the user can specify if the data should be normalized. By default this option is set as True and is computed in an independent function. The separator to parse the data can also be set, although the default character is “;”. def readFile(fileIn, isHeader = True, normalization = True, separator = ";"): count = 0 dataLog = [] for line in fileIn: if isHeader: isHeader = False else: try: line = line.split("\r\n")[0] line = line.split(separator) row = [] for num in line: row.append(float(num)) dataLog.append(np.array(row)) except: print "Error parsing line [%d]: %s" % (count, line) count += 1 npDataLog = np.array(dataLog) if normalization: npDataLog = normData(npDataLog) return npDataLog 5 http://www.numpy.org/ Page 66 Final degree project Scales the data by columns into a range between 0 and 1. To normalize the data the minimum is subtracted and all the values are divided by the maximum. The values used to implement this normalization are stored in a file (by default normVal.csv), in order to undo the normalization once the prediction is done. def normData(argray, normPath = "normVal.csv"): vNorm = [] size = array.shape normFile = open(normPath, 'w') for idx in range(size[-1]): normFile.write(str(array[:,idx].min()) + " " + str(array[:,idx].max() + "\n") array[:,idx] -= array[:,idx].min() array[:,idx] /= array[:,idx].max() normFile.close() return array PyBrain In a first approach, the neural network training has been implemented using a well-know library: PyBrain 6 . Although there are alternative libraries in Python for this purpose, PyBrain is one of the most complete and has a complete documentation with many examples. Moreover, it is easy to create a multilayer perceptron with very few lines and many of its training parameters can be set. The only inconvenience of PyBrain is that it requires a specific type of data structure and so, a function to switch from the raw information to the specific format. This class is called SupervisedDataSet and requires two parameters to be initialized: the number of the inputs and outputs. def createDataSet(array): ds = SupervisedDataSet( lenInput, lenOutput ) for row in array: ds.appendLinked(row[:-1], row[-1]) return ds 4.6.3.1. PyBrain code When working with PyBrain, it necessary to define three key elements:  The layers (morphology of the different layers)  The structure of the net (number of neurons and their connections)  The trainer (algorithm to minimize the weights) 6 http://pybrain.org/ Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 67 In the code below, those three elements are imported from the PyBrain package, the data is loaded from a csv file, the sizes of the different layers of the net are specified and the sets are created in a certain proportion. from pybrain.structure import SigmoidLayer, LinearLayer from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer dataFile = open('/Users/sergi/Desktop/data_resp.csv', 'r') data = readFile(dataFile, separator = ";") lenInput = len(data[0]) - 1 hiddenUnits = 25 lenOutput = 1 ds = createDataSet(data) te, tr = ds.splitWithProportion( 0.15 ) The net is defined, with 25 hidden units and a sigmoid function as activation. The back propagation trainer is initialized, with the flag verbose to evaluate the intermediate states of the training. net = buildNetwork(lenInput, hiddenUnits, lenOutput, bias = True, hiddenclass = SigmoidLayer, outclass = LinearLayer) trainer = BackpropTrainer(net, tr, verbose = True) To train the net, a fixed number of epochs is fixed. To track the training, the function prompts the error of the train and the test, for each epoch. trainError = [] testError = [] for iteration in range(200): error = trainer.train() trainError.append(error) listError = [] predictions = [] for value in te['input']: predictions.append(net.activate(value)) for j in range(len(predictions)): listError.append((predictions[j] - te['target'][j])) listError = np.array(listError) rmse = float(np.sqrt(np.sum(listError**2)/len(listError))) testError.append(rmse) Page 68 Final degree project To understand completely the quality of the training, two graphics are plotted. The first one shows the predictions versus the real values. The second one shows the error of the prediction against the real value. In addition to the graphics, the RMSE and ARV are calculated. import pylab import numpy as np predictions = [] for value in te['input']: predictions.append(net.activate(value)) # Plot the prediction against the real value axisMin = 0.0 axisMax = 1.0 pylab.rcParams['figure.figsize'] = (15, 10) pylab.subplot(2,2,1) pylab.scatter(te['target'], predictions, s=10, color = 'blue', label = 'NN output') pylab.xticks(pylab.linspace(axisMin, axisMax, 11, endpoint=True)) pylab.yticks(pylab.linspace(axisMin, axisMax, 11, endpoint=True)) pylab.xlabel("Real values") pylab.ylabel("Predictions") pylab.grid() # Plot the error against the real value pylab.subplot(2,2,2) pylab.scatter(te['target'], te['target'] - predictions, s=10, color = 'red', label = 'NN output') pylab.xticks(pylab.linspace(axisMin, axisMax, 11, endpoint=True)) pylab.yticks(pylab.linspace(-axisMax/2, axisMax/2, 11, endpoint=True)) pylab.xlabel("Real values") pylab.ylabel("Error") pylab.grid() # Plot an histogram of the error. pylab.subplot(2,2,3) pylab.hist(te['target'] - predictions) pylab.xlabel("Error") pylab.grid() pylab.show() # Compute the RMSE listError = [] for j in range(len(predictions)): listError.append((predictions[j] - te['target'][j])) error = np.array(listError) rmse = float(np.sqrt(np.sum(error**2)/len(error))) print "RMSE:", rmse Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 69 # Compute the ARV teMean = 0 for i in range(len(te)): teMean += te['target'][i][0] teMean /= len(te) arv = np.sum(error**2)/np.sum((te['target'] - teMean)**2) print "ARV: %.3f" % arv Output. RMSE: 0.0703180750483 ARV: 0.214 Plot 40. Training error with the PyBrain package. As evaluated before those values are typical results for this configuration. The errors also confirm the assumption that huge values are more unlikely to be predicted. Page 70 Final degree project Finally, the errors obtained during the training are plotted. It is clear from the graphic that the training has achieved a local (either minimum or absolute) and the accuracy doesn’t improve with the number of epochs. pyplot.rcParams['figure.figsize'] = (15, 10) pyplot.plot(trainError, 'b-') pyplot.plot(testError, 'r-') pyplot.ylim((0, 0.3)) pyplot.grid() Plot 44. Train and test error with the PyBrain package. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 71 Class implementation Although the PyBrain library is a powerful tool to work with, some elements of the network structure and its behaviour remain uncontrolled by the user. Thus, writing a Python class over NumPy, to define and train the network, is the best option to understand the whole process and control all the variables. 4.6.4.1. ANN code Import libraries to process the data and draw the graphics. Nearly all the computational calculus have to be done by means of the NumPy package, however some functions such as the hyperbolic tangent or randomizing the data are implemented in other Python packages. import math import pylab import random import numpy as np Functions to define the activation functions (sigmoid and hyperbolic tangent) and their derivatives. Those functions are required to process the entire algorithm when predicting and computing the back propagation. def sigmoid(x): return 1 / (1 + np.exp(-x)) def dsigmoid(y): return y * (1.0 - y) def tanh(x): return math.tanh(x) def dtanh(y): return 1 - y*y Page 72 Final degree project Once the librairies are imported and the activation functions are defined, the Multilayer Perceptron Class can be defined with its attributes and methods. The basic structure of the this class is defined below: Attributes to define the network:  Solver parameters (iterations, learning rate, momentum and rate decay)  Size of the layers  Weight values  Temporal variables to compute the back propagation. Methods to use the network:  Feed forward computation  Back propagation  Test  Train  Predict class MLP_NeuralNetwork(object): # initialize parameters self.iterations = iterations self.learning_rate = learning_rate self.momentum = momentum self.rate_decay = rate_decay # initialize arrays self.input = input + 1 # add 1 for bias node self.hidden = hidden self.output = output # set up array of 1s for activations self.ai = [1.0] * self.input self.ah = [1.0] * self.hidden self.ao = [1.0] * self.output # create randomized weights # use scheme from 'efficient backprop to initialize weights input_range = 1.0 / self.input ** (1/2) output_range = 1.0 / self.hidden ** (1/2) self.wi = np.random.normal(loc = 0, scale = input_range, size = (self.input, self.hidden)) self.wo = np.random.normal(loc = 0, scale = output_range, size = (self.hidden, self.output)) # create arrays of 0 for changes # this is essentially an array of temporary values that gets updated at # each iteration # based on how much the weights need to change in the following iteration self.ci = np.zeros((self.input, self.hidden)) Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 79 5. Conclusions Pursuing the best model to predict the emergencies, occurring during the year, in the Hospital Universitari Dr. Josep Trueta de Girona, several methodologies and algorithms have been applied: Starting with a temporal series analysis which was not able to accurately capture the flow of the process; followed with a deep study of the artificial neural networks applied to a regression problem. Using this algorithm, contained in the machine learning analysis, has bring two important work paths: develop a based and reproducible methodology and adapt it to solve the presented problem. There are several papers using artificial neural networks for classification purposes and even for linear regressions, but there are just a few regarding nonlinear predictions for temporal series like the one presented in this project. The lack of a well-defined methodology to face this kind of process has lead us to try to define, as detailed as possible, a consistent work frame for future projects pursuing similar objectives. Therefore, and according to the discussion described in the core of the project, the following steps have been defined: Descriptive analysis of the data set (2.3) Analysis of the explicative variables (2.5.2.2) Package discussion (R, Python) Sensitivity analysis (2.5.3.4.1) Relation between input and output variables (2.5.3.4.1.1) Analysis of the erorr (2.5.3.4.1.2) Cross validation (2.5.3.4.1.3) Consistency analysis (2.5.3.4.2) Variable normalization Topology selected (2.5.3.5) Factorial experiment Page 80 Final degree project Despite the model is capable of capture the main flow of the process, it is failing in the forecast of the outliers which would have represent an important improvement compared with a regression method. Even though different methodologies and explicative variables have been applied to correct this issue, they have not offered good solutions. The algorithms that presented a lower error levels due the capture of some of this outliers (as using the Rprop learning function) in the training, have failed in the test due to the over fitting made. As a last possible solution, knowing the seasonality of the process, two neural networks have been built (each one according to the frequency of emergencies: low for spring and summer or high for autumn and winter) and trained according this definition. The results are not shown as they are worse than the ones using the previous methodology due to by partitioning the problem, there are too few registers to train the algorithm. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 81 6. Economic study In this section, the costs and profits of the project are discussed. First, a brief impact analysis regarding the implementation of the project into the Hospital Universitari de Girona Dr. Josep Trueta is performed. Secondly all the associated costs of the development of the project are accurate listed. Assuming that the algorithm offers good forecasts, the hospital management could you use it in order to schedule and scale both resource and personnel actives of the hospital. The application provided to the management team would help them know a good approximation of the emergencies left to come at the emergency department once the information from the morning (first strip) has been introduced to the algorithm via the plain application. It is rough to calculate the exact benefits (in cash) for the hospital even though it is easy to identify it would suppose a great help for the emergency department logistics once a good estimation of the volume of emergencies has been predicted. The project’s costs can be disaggregated due several concepts: - Human resources - Consulting hours to analyse, onside, the problem to solve and to investigate its related covariates. - Salary associated to the development of the algorithm according an engineering salary. - Insurances. - Energy consumption: electricity (charge the laptop and light for the office). - Infrastructure - Hardware: laptop, screen, mouse and keyboard. - Software: licenses for using the programs. - Location. There are several costs than can be discounted as they have a low impact in the total budget of the project. In this expenses category the following concepts are included: - Infrastructure – location: due all the project has been developed in the engineer’s own place, and occasionally in public areas (such as public libraries or the university), the costs associated with the location and with the energy consumption have not been taken in account for the total cost calculation. The hardware costs are also not used for the costs calculations as the development Page 82 Final degree project of the project does not imply a depreciation of this hardware, which is used for private reasons as well. - All the insurance costs have been neglected as well. Knowing that there already is a student insurances paid. The costs of all other concepts have been taken into account. The most representative ones are the ones related to engineering hours. This concept has been partitioned in two different types of costs. From one side, the consulting spent hours spent on side, in the hospital, in order to inquire and gather as much information as possible about the future modeled process. Once this hours satisfies the requirements gathering, the development hours associated to engineering costs have to be counted. The total amount of hours dedicated to develop this project are the ones corresponding to the hours scheduled to achieve the equivalence with 12 ECTS’s credits. In this case it implies among 360 hours which mean, approximately, nine weeks working eight hours per day. Another cornerstone to calculate the costs in the project is the price of the licenses for the software used during the development. In this case R and its framework extension, Rstudio, have been used for the analysis and the development of the algorithm. Then, in order to be able to tune as much as possible the algorithm and also to get it ready for the applicative, Python has been used. The cost of this software is null as all of them belongs to free software which has not to be paid for the development of the project. Another licenses used have been the ones corresponding to Windows and Microsoft Office which are included in the price of buying the laptop. Salary concepts Cost / hour (€/h) Total time (h) Total cost (€) Consulting 25 40 1000 Development 20 320 6400 Total - - 9600 Table16. Salary costs Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 83 Hardware Total cost (€) Amortization time (months) Duration of use (months) Cost associated (€) Laptop 2200 84 2 50 Others (mouse, keyboard…) 150 42 2 8 Total - - - 58 Table 17. Infrastructure costs Project total cost is equal to 9600 + 58 = 9658 €. Page 84 Final degree project 7. Environmental study The environmental impact of the system developed by the current project is not significant. It is a fact that, by taking into account the decrease of the hospital resources spend due a better prediction of the volume of emergencies, would bring a less negative environmental effect. The real values of the reductions in environmental costs that this system could mean cannot be accurately estimated in the scope of this project. Another keystone that has to be analysed is the environmental cost of the project itself. Even though there is an undoubtedly energetic cost due the utilization of electronic equipment (in this case a laptop), it can be neglected, as the cost of the energy consumption of the laptop was not taken into account in the economic study. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 85 8. Bibliography Montserrat Pepió. Seres temporales. 2ª ed. Barcelona: Edicions UPC, 2002. Mª Luisa Pérez, Quintín Martín. Aplicaciones de las redes neuronales artificiales a la estadística. Madrid: Hespérides, S.L, 2003. Mª Pilar González. Análisi de series temporales: Modelos ARIMA. País Vasco: Facultad de Ciencias Económicas y Empresariales, 2009. J.P. Marques de Sá. Pattern Recognition. Oporto:Springer, 2001. Department of Computer Science Mangalore University. “PERFORMANCE ANALYSIS OF NEURAL NETWORK MODELS FOR OXAZOLINES AND OXAZOLES DERIVATIVES DESCRIPTOR DATASET”. Vol.3 No.6, November 2013. Christoph Bergmeir, José M. Benítez. “Neural Networks in R Using the Stuttgart Neural Network Simulator: RSNNS”. Vol. 46, Issue 7, January 2012. Jonathan D.Cryer, Kung-Sik Chan. Time Series Analysis, 2nd ed. USA: Springer, 2008. Sarah Thompson. R is my friend. [Checked: July 2014]. http://beckmw.wordpress.com/2013/08/12/variable-importance-in-neural-networks/ Quick-R (accessing the power of R). [Checked: July 2014, August 2014]. http://www.statmethods.net/advstats/timeseries.html Avril Chohlan. Little Book of R for Time Series. Cambridge, U.K. [Checked: May 2014, July 2014]. Disponible a: http://a-little-book-of-r-for-time-series.readthedocs.org/en/latest/ Cross Validated. [Checked: July 2014, August 2014]. http://stats.stackexchange.com/ Andreas Zell, Günter Mamier, Michael Vogt. Stuttgart Neural Network Simulator User Manual, Version 4.1. [Checked: February 2015]. http://www.ra.cs.unituebingen.de/SNNS/UserManual/UserManual.html Wikipedia. [Checked January 2015]. http://en.wikipedia.org/wiki/Cross-validation_(statistics) Robert Griñó Cubero. Neural Networks for water demand time series forecasting. Institut de Cibernètica (CSIC-UPC). Theophano Mitsa. (2010). Temporal Data Mining. USA. Chapman & Hall book. Hecht-Nielsen, R. (June 22, 1989). “Theory of the backpropagation neural network”. 593 – 605 Page 86 Final degree project vol.1. A.T.C. Goh. (1995). “Back-propagation neural networks for modeling complex systems”. Volume 9, Issue 3, 1995, Pages 143–151. Alex J. Smola, Bernhard Schölkopf. (1998). [Checked: January 2015] “A Tutorial on Support Vector Regression”. http://www.svms.org/regression/SmSc98.pdf Scikit-learn. Support Vector Regression. [Checked: February 2015]. http://scikitlearn.org/stable/auto_examples/svm/plot_svm_regression.html iPython. [Checked: October 2014]. “The Ipython Notebook”. http://ipython.org/notebook.html Numpy manual. [Checked: November 2014]. http://docs.scipy.org/doc/numpy/reference/ PyPlot Summary. [Checked: November 2014]. http://matplotlib.org/api/pyplot_summary.html PyBrain docs. [Checked: October 2014]. http://pybrain.org/docs/ Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 87 9. ANNEX 1 9.1. Core of the algorithm Once the different parts of the code that integrates the neural network algorithm have been explained, is time to take a look into the core of this code in order to know how it is internally organized. #Load the data #Normalize the data #Initialization of the library and data set dataTot<-read.csv2(file="respiratory.csv", header=T, sep=";",dec=".") idresp=9 data=dataTot[,1:idresp] library(RSNNS) set.seed(12345678) inputs<-data[,1:(ncol(data)-1)] outputs<-data[,ncol(data)] train_old<-data.frame(cbind(inputs,outputs)) train=train_old data[,1]=data[,1]/max(data[,1]) data[,2:5]=data[,2:5]/max(data[,2:5]) data[,6]=data[,6]/max(data[,6]) data[,idresp]=data[,idresp]/max(data[,idresp]) Page 88 Final degree project #Definitions (train and validation sets, training blocks, ARV, MSE and error) # Loop 1: setting the parameter nveg, the number of times that the multi-layer perceptron (mlp) is going to compute the training (with different initialization parameters) is fixed. Inside this first loop there is the sample function which randomly organizes the data from the training set (keeping out the one for the validation) into the defined number of blocks, block, that are going to be used in the Loop 2. The parameter block, indicates in how many blocks should the training set be partitioned for performing the cross validation using the k-folders non exhaustive technique. The calculations for each block are done in the second loop, # Loop 2, where the values for ARV and MSE are registered in the predefined matrices for each iteration. For each one of the nveg (five in this example) iterations, the neural network trains block times with different data (according to the k-fold technique) the algorithm (in this case, seven). In the example below, there are the seven different results of the training for the nveg equals to two. This methodology is applied in order to prove the consistency of the algorithm which, according to numerous tests, it is consistent with the data that is being used. train_set<-train[1:1273,] validation_set<-train[1274:1454,] block<-7 fac=1 nveg=5 TARV=matrix(0,ncol=nveg,nrow=block) TMSE=matrix(0,ncol=nveg,nrow=block) error=matrix(0,ncol=nveg,nrow=nrow(train_set)) ARV=function(a,p) sum((a-p)^2)/sum((a-mean(a))^2) MSE=function(a,p) sqrt(mean((a-p)^2)) Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 95 9.4. PyBrain documentation Functions implemented in PyBrain used to develop the software for this project. Create and process the data sets class pybrain.datasets.supervised.SupervisedDataSet(inp, target) SupervisedDataSets have two fields, one for input and one for the target. __init__(inp, target)¶ Initialize an empty supervised dataset. Pass inp and target to specify the dimensions of the input and target vectors. __len__()¶ Return the length of the linked data fields. If no linked fields exist, return the length of the longest field. addSample(inp, target)¶ Add a new sample consisting of input and target. Batches(label, n, permutation=None)¶ Yield batches of the size of n from the dataset. A single batch is an array of with dim columns and n rows. The last batch is possibly smaller. If permutation is given, batches are yielded in the corresponding order. Clear(unlinked=False)¶ Clear the dataset. If linked fields exist, only the linked fields will be deleted unless unlinked is set to True. If no fields are linked, all data will be deleted. Copy()¶ Return a deep copy. Classmethod loadFromFile(filename, format=None)¶ Return an instance of the class that is saved in the file with the given filename in the specified format. randomBatches(label, n)¶ Like .batches(), but the order is random. Classmethod reconstruct(filename)¶ Read an incomplete data set (option arraysonly) into the given one. saveToFile(filename, format=None, **kwargs)¶ Save the object to file given by filename. splitWithProportion(proportion=0.5)¶ Produce two new datasets, the first one containing the fraction given by proportion of the samples. Page 96 Final degree project Define the layers structure and 96 oolean 96 class pybrain.structure.modules.LinearLayer(dim, name=None)¶ Bases: pybrain.structure.modules.neuronlayer.NeuronLayer The simplest kind of module, not doing any transformation. __init__(dim, name=None)¶ Create a layer with dim number of units. Class pybrain.structure.modules.SigmoidLayer(dim, name=None)¶ Bases: pybrain.structure.modules.neuronlayer.NeuronLayer Layer implementing the sigmoid squashing function. __init__(dim, name=None)¶ Create a layer with dim number of units. Build a standard multilayer perceptron pybrain.tools.shortcuts.buildNetwork(*layers, **options)¶ Build arbitrarily deep networks. Layers should be a list or tuple of integers, that indicate how many neurons the layers should have. Bias and outputbias are flags to indicate whether the network should have the corresponding biases; both default to True. To adjust the classes for the layers use the hiddenclass and outclass parameters, which expect a subclass of NeuronLayer. If the recurrent flag is set, a RecurrentNetwork will be created, otherwise a FeedForwardNetwork. If the fast flag is set, faster arac networks will be used instead of the pybrain implementations. Define the training algorithm class pybrain.supervised.trainers.BackpropTrainer(module, dataset=None, learningrate=0.01, lrdecay=1.0, momentum=0.0, verbose=False, batchlearning=False, weightdecay=0.0)¶ Trainer that trains the parameters of a module according to a supervised dataset (potentially sequential) by backpropagating the errors (through time). __init__(module, dataset=None, learningrate=0.01, lrdecay=1.0, momentum=0.0, verbose=False, batchlearning=False, weightdecay=0.0)¶ Create a BackpropTrainer to train the specified module on the specified dataset. The learning rate gives the ratio of which parameters are changed into the direction of the gradient. The learning rate decreases by lrdecay, which is used to to multiply the learning rate after each training step. The parameters are also adjusted with respect to momentum, which is the ratio by which the gradient of the last timestep is used. If batchlearning is set, the parameters are updated only at the end of each epoch. Default is False. Weightdecay corresponds to the weightdecay rate, where 0 is no weight decay at all. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 97 setData(dataset)¶ Associate the given dataset with the trainer. testOnClassData(dataset=None, verbose=False, return_targets=False)¶ Return winner-takes-all classification output on a given dataset. If no dataset is given, the dataset passed during Trainer initialization is used. If return_targets is set, also return corresponding target classes. Train()¶ Train the associated module for one epoch. trainEpochs(epochs=1, *args, **kwargs)¶ Train on the current dataset for the given number of epochs. Additional arguments are passed on to the train method. trainOnDataset(dataset, *args, **kwargs)¶ Set the dataset and train. Additional arguments are passed on to the train method. trainUntilConvergence(dataset=None, maxEpochs=None, verbose=None, continueEpochs=10, validationProportion=0.25)¶ Train the module on the dataset until it converges. Return the module with the parameters that gave the minimal validation error. If no dataset is given, the dataset passed during Trainer initialization is used. validationProportion is the ratio of the dataset that is used for the validation dataset. If maxEpochs is given, at most that many epochs are trained. Each time validation error hits a minimum, try for continueEpochs epochs to find a better one. Page 98 Final degree project 9.5. Auxiliary python libraries Math Math Provides access to the mathematical functions defined by the C standard. Math.tanh(x) Return the hyperbolic tangent of x. Random Random implements pseudo-random number generators for various distributions. Random.shuffle(x[, random]) Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated. Numpy NumPy is the fundamental package for scientific computing with Python. Numpy.exp(x[, out]) = <ufunc ‘exp’> Calculate the exponential of all elements in the input array. Parameters: x : array_like Input values. Returns: out : ndarray Output array, element-wise exponential of x. numpy.zeros(shape, dtype=float, order=’C’) Return a new array of given shape and type, filled with zeros. Parameters: shape : int or sequence of ints Shape of the new array, e.g., (2, 3) or 2. Dtype : data-type, optional The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64. order : {‘C’, ‘F’}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Returns: out : ndarray Array of zeros with the given shape, dtype, and order. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 99 Numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False) Sum of array elements over a given axis. Parameters: a : array_like Elements to sum. Axis : None or int or tuple of ints, optional Axis or axes along which a sum is performed. The default (axis = None) is perform a sum over all the dimensions of the input array. Axis may be negative, in which case it counts from the last to the first axis. New in version 1.7.0. If this is a tuple of ints, a sum is performed on multiple axes, instead of a single axis or all the axes as before. Dtype : dtype, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of a is used. An exception is when a has an integer type with less precision than the default platform integer. In that case, the default platform integer is used instead. Out : ndarray, optional Array into which the output is placed. By default, a new array is created. If out is given, it must be of the appropriate shape (the shape of a with axis removed, i.e., numpy.delete(a.shape, axis)). Its type is preserved. See doc.ufuncs (Section “Output arguments”) for more details. Keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr. Returns: sum_along_axis : ndarray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. Page 100 Final degree project numpy.random.normal(loc=0.0, scale=1.0, size=None) Draw random samples from a normal (Gaussian) distribution. The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently, is often called the bell curve because of its characteristic shape (see the example below). The normal distribution occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution. Parameters: loc : float Mean (“centre”) of the distribution. Scale : float Standard deviation (spread or “width”) of the distribution. Size : int or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned. Datetime The datetime module supplies classes for manipulating dates and times in both simple and complex ways. Class datetime.date An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year, month, and day. Matplotlib matplotlib.rcParams An instance of RcParams for handling default matplotlib values. Matplotlib.pyplot.subplot(*args, **kwargs) Return a subplot axes positioned by the given grid definition. Keyword arguments: axisbg: The background color of the subplot, which can be any valid color specifier. See matplotlib.colors for more information. Polar: A 100 oolean flag indicating whether the subplot plot should be a polar projection. Defaults to False. Projection: A string giving the name of a custom projection to be used for the subplot. This projection must have been previously registered. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 101 matplotlib.pyplot.scatter(x, y, s=20, c=u’b’, marker=u’o’, cmap=None, norm=None, vmin=Non e, vmax=None, alpha=None,linewidths=None, verts=None, hold=None, **kwargs) Make a scatter plot of x vs y, where x and y are sequence like objects of the same lengths. Parameters: x, y : array_like, shape (n, ) Input data s : scalar or array_like, shape (n, ), optional, default: 20 size in points^2. C : color or sequence of color, optional, default c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. C can be a 2-D array in which the rows are RGB or RGBA, however. Marker : MarkerStyle, optional, default: ‘o’ See markers for more information on the different styles of markers scatter supports. Cmap : Colormap, optional, default: None A Colormap instance or registered name. cmap is only used if c is an array of floats. If None, defaults to rc image.cmap. norm : Normalize, optional, default: None A Normalize instance is used to scale luminance data to 0, 1. Norm is only used if c is an array of floats. If None, use the default normalize(). Vmin, vmax : scalar, optional, default: None vmin and vmax are used in conjunction with norm to normalize luminance data. If either are None, the min and max of the color array is used. Note if you pass a norm instance, your settings for vmin and vmax will be ignored. Alpha : scalar, optional, default: None The alpha blending value, between 0 (transparent) and 1 (opaque) linewidths : scalar or array_like, optional, default: None If None, defaults to (lines.linewidth,). Note that this is a tuple, and if you set the linewidths argument you must set it as a sequence of floats, as required by RegularPolyCollection. Returns: paths : PathCollection matplotlib.pyplot.xticks(*args, **kwargs) Get or set the x-limits of the current tick locations and labels. Matplotlib.pyplot.yticks(*args, **kwargs) Get or set the y-limits of the current tick locations and labels. Matplotlib.pyplot.grid(b=None, which=u’major’, axis=u’both’, **kwargs) Turn the axes grids on or off. Page 102 Final degree project Matplotlib.pyplot.show(*args, **kw) Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt. In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block. A single experimental keyword argument, block, may be set to True or False to override the blocking 102 oolean 102 r described above. Use of artificial neural networks for emergencies prediction at Hospital Universitari de Girona Dr. Josep Trueta Page 103 9.6. R documentation Nnet Fit single-hidden-layer neural network, possibly with skip-layer connections. Usage nnet(x, …) Arguments formula A formula of the form class ~ x1 + x2 + … x matrix or data frame of x values for examples. Y matrix or data frame of target values for examples. Weights (case) weights for each example – if missing defaults to 1. Size number of units in the hidden layer. Can be zero if there are skip-layer units. Data Data frame from which variables specified in formula are preferentially to be taken. Subset An index vector specifying the cases to be used in the training sample. (NOTE: If given, this argument must be named.) na.action A function to specify the action to be taken if Nas are found. The default action is for the procedure to fail. An alternative is na.omit, which leads to rejection of cases with missing values on any required variable. (NOTE: If given, this argument must be named.) contrasts a list of contrasts to be used for some or all of the factors appearing as variables in the model formula. Wts initial parameter vector. If missing chosen at random. Mask logical vector indicating which parameters should be optimized (default all). Linout switch for linear output units. Default logistic output units. Entropy switch for entropy (= maximum conditional likelihood) fitting. Default by leastsquares. Softmax switch for softmax (log-linear model) and maximum conditional likelihood fitting. Linout, entropy, softmax and censoredare mutually exclusive. Censored A variant on softmax, in which non-zero targets mean possible classes. Thus for softmax a row of (0, 1, 1) means one example each of classes 2 and 3, but for censored it means one example whose class is only known to be 2 or 3. Skip switch to add skip-layer connections from input to output. Rang Initial random weights on [-rang, rang]. Value about 0.5 unless the inputs are large, in which case it should be chosen so thatrang * max(|x|) is about 1. Decay parameter for weight decay. Default 0. Maxit maximum number of iterations. Default 100. Hess If true, the Hessian of the measure of fit at the best set of weights found is returned as component Hessian. Trace switch for tracing optimization. Default TRUE. MaxNWts The maximum allowable number of weights. There is no intrinsic limit in the code, but increasing MaxNWts will probably allow fits that are very slow and time-consuming. Abstol Stop if the fit criterion falls below abstol, indicating an essentially perfect fit. Reltol Stop if the optimizer is unable to reduce the fit criterion by a factor of at least 1 – reltol. Page 104 Final degree project … arguments passed to or from other methods. RSNNS The Stuttgart Neural Network Simulator (SNNS) is a library containing many standard implementations of neural networks. This package wraps the SNNS functionality to make it available from within R. As the high-level api is already quite powerful and flexible, you’ll most probably normally end up using one of the functions: mlp, dlvq, rbf,rbfDDA, elman, jordan, som, art1, art2, artmap, or assoz, with some pre- and postprocessing. These S3 classes are all subclasses ofrsnns. For this project the mlp function has been used. 9.6.2.1. mlp This function creates a multilayer perceptron (MLP) and trains it. MLPs are fully connected feedforward networks, and probably the most common network architecture in use. Training is usually performed by error backpropagation or a related procedure. Usage mlp(x, …) Arguments x a matrix with training inputs for the network … additional function parameters (currently not used) y the corresponding targets values size number of units in the hidden layer(s) maxit maximum of iterations to learn initFunc the initialization function to use initFuncParams the parameters for the initialization function learnFunc the learning function to use learnFuncParams the parameters for the learning function updateFunc the update function to use updateFuncParams the parameters for the update function hiddenActFunc the activation function of all hidden units shufflePatterns should the patterns be shuffled? linOut sets the activation function of the output units to linear or logistic inputsTest a matrix with inputs to test the network targetsTest the corresponding targets for the test input pruneFunc the pruning function to use pruneFuncParams the parameters for the pruning function. Unlike the other functions, these have to be given in a named list.