Full text
Universidade do Minho Escola de Engenharia Bruno Filipe Martins Fernandes The Internet of People approach to Road Safety and Vulnerable Road Users in Smart Cities January, 2021 UMinho | 2021Bruno Filipe Martins Fernandes The Internet of People approach to Road Safety and Vulnerable Road Users in Smart Cities
Universidade do Minho Escola de Engenharia Bruno Filipe Martins Fernandes The Internet of People approach to Road Safety and Vulnerable Road Users in Smart Cities Doctoral Thesis Doctoral Program in Informatics Work supervised by Cesar Analide de Freitas e Silva da Costa Rodrigues José Carlos Ferreira Maia Neves January, 2021
ii COPYRIGHT AND TERMS OF USE OF THIS WORK BY A THIRD PARTY This is an academic work that can be used by third parties as long as internationally accepted rules and good practices regarding copyright and related rights are respected. Accordingly, this work may be used under the license provided below. If the user needs permission to make use of the work under conditions not provided for in the indicated licensing, they should contact the author through the RepositoriUM of University of Minho. License granted to the users of this work Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en
Acknowledgements Por ti e para ti, Tia. Por ti e para ti, Avó. In the 17th Chapter of St Luke it is written: ”the Kingdom of God is within man”. Not one man nor a group of men, but in all men! In you! You, the people have the power - the power to create machines. The power to create happiness! You, the people, have the power to make this life free and beautiful, to make this life a wonderful adventure. — Sir Charles Spencer Chaplin Now that the time has come for me to acknowledge all those that, somehow, supported me during this journey, I hope not to get short on words. I must start by expressing my gratitude to Professor Cesar Analide and Professor José Maia Neves, who, more than supervisors, are extraordinary friends. I will not forget Professor Paulo Novais. Thank you all for your guidance, comments, and challenges. I am also deeply grateful to all my friends at ISLab. Thank you Ana, António, Dalila, Fábio, Filipe, Francisco, Leandro, Leonardo, Luís, Marco, Pedro, and Ricardo. Thank you all for your support and friendship. I must also thank Hector for his friendship and for helping me keep this work on the right path. My gratitude is also expressed to the ALGORITMI Centre and FCT for providing me all the means to complete this journey, including a national PhD scholarship (with reference SFRH/BD/130125/2017). On a personal level, I must express my uttermost gratitude to my friends and all my family. To my grandparents, my aunts, my uncles, and my cousins, thank you for always being there for me, especially after this difficult phase we all went through. I am deeply grateful to my parents, Sérgio and Lúcia. To my brother and sister, Paulo and Mariana, you know you are the source of my strength. Finally, to the one that has been with me for many years now, Ana Bela, thank you for cherishing me, for your support and comprehension. I know that without you I would not be here. We have both made it! Since high school kids to this day - what an amazing journey. I could not fail to thank the One who has been guiding me throughout my all life. I know that lately I have been further away but I promise I will meet You again. Thank You for making this journey with me. Thank you all. iii
iv STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of University of Minho. Braga, (Bruno Filipe Martins Fernandes) Assinado por : BRUNO FILIPE MARTINS FERNANDES Num. de Identificação Civil: BI13945086 Data: 2021.03.05 13:42:25 Hora padrão de GMT
Resumo A Internet das Pessoas para benefício da Segurança Rodoviária e dos Utilizadores Vulneráveis da Estrada em Cidades Inteligentes Desde o início dos tempos, tudo temos feito para melhorar a nossa qualidade de vida. A nossa caminhada tem sido incrível, mas está longe de ter terminado. Infelizmente, um problema em destaque na nossa sociedade prende-se com os acidentes rodoviários, a principal causa de morte de crianças e jovens adultos. Na estrada existem grupos de pessoas mais vulneráveis que outros, sendo estes descritos como Utilizadores Vulneráveis da Estrada (UVE). Na sua essência, este grupo caracteriza-se por pedestres, ciclistas e motociclistas. Estima-se que, actualmente, mais de metade dos mortos na estrada sejam UVE. Estes números são consequência de políticas que prioritizam veículos em vez de pessoas. Reduzir acidentes entre UVE permanece um desafio. Nenhuma solução monolítica conseguirá resolver todos os problemas. Pelo contrário, a expectativa é que serão várias pequenas contribuições a fazer a diferença. Desta forma, a nossa contribuição é baseada na percepção de pessoas como actores activos e proactivos de uma cidade inteligente. Desta premissa surge o 3-C, o qual se foca em sensorizar a Cidade, a Comunidade e o Cidadão. O 3-C, que define as directrizes e objectivos deste trabalho, quando complementado com a metodologia de investigação adoptada, permitiu a organização de uma sequência lógica de procedimentos replicáveis, precisos e parcimoniosos para a concepção de conhecimento científico. Esta tese de doutoramento apresenta, entre outros, um arquétipo, SafeCity, que agrega várias soluções que tiveram origem no processo de investigação realizado. Este arquétipo apresenta métodos e modelos disruptivos para inferência de aborrecimento e personalidade, para concepção de mapas de sentimentos e para previsão do fluxo de tráfego rodoviário, entre outros. O objectivo é o de permitir que as pessoas sejam actores participativos e que, assim, tenham acesso a um conjunto de informação sobre o estado actual e futuro do ambiente onde estão inseridas, permitindo que os UVE adaptem o seu comportamento perante cada situação, hora e local de uma cidade. Arquétipos adicionais incluem uma blockchain sobre um sistema multi-agente para gestão de grandes quantidades de dados estruturados. Palavras-chave: Aprendizagem Automática, Cidades Inteligentes, Inteligência Ambiente, Internet das Pessoas, Utilizadores Vulneráveis da Estrada. v
Abstract The Internet of People approach to Road Safety and Vulnerable Road Users in Smart Cities Since the dawn of times, the human being has always endeavored to improve his quality of life. Our journey has been amazing but it has not yet finished. Unfortunately, an issue that has been rising to prominence is related to road traffic accidents, the leading cause of death for children and young adults. On the road, there are groups of people more vulnerable than others to injuries and accidents. Those are known as Vulnerable Road Users (VRUs), being defined as pedestrians, cyclists, and motorcyclists. It is estimated that, currently, more than half of all road traffic deaths are amongst VRUs. These numbers are a consequence of policies that prioritize vehicles instead of people. Reduce injuries among VRUs remains a big challenge. No monolithic solution will, singularly, settle out all problems. Instead, the expectation is that multiple small contributions may help answering important challenges raised by this group of road users. Hence, our contribution is grounded on the perception of people as active, reactive, and proactive actors of a Smart City’s ecosystem. From this premise emerges the 3-C, i.e., City, Crowd, and Citizen sensing. The 3-C, which defines the guidelines and goals of this work, when complemented with the adopted research methodology, allowed the organization of a logical sequence of replicable, precise, and parsimonious procedures to build scientific knowledge. This thesis presents, among others, an archetype platform, SafeCity, which aggregates multiple solution specimens produced as a result of the conducted research. SafeCity makes use of multiple disruptive methods and models for on-device boredom inference, to assess one’s personality, to conceive emotional maps, and to provide accurate multi-step traffic flow forecasts, among many others. The goal is to allow people to be participative actors, thus having access to a set of information about the current and future status of the environment where they stand, allowing VRUs to adapt their behavior upon each situation, hour, and place of a city. Additional archetypes include a multi-agent system blockchain for the management of large amounts of data of different types and sources. Keywords: Ambient Intelligence, Internet of People, Machine Learning, Smart Cities, Vulnerable Road Users. vi
Contents List of Figures xi List of Tables xiv Listings xvi List of Algorithms xvii Acronyms xviii 1 Introduction 1 1.1 Research Domains ................................. 1 1.1.1 Road Safety and Vulnerable Road Users ................... 1 1.1.2 Internet of Things and the Internet of People ................ 4 1.1.3 Smart Cities ................................ 6 1.1.4 Artificial Intelligence ............................ 8 1.2 Related Work and Projects in the VRUs’ domain ................... 12 1.2.1 Academic Literature ............................ 12 1.2.2 Related Projects .............................. 16 1.2.3 Summary ................................. 24 1.3 Conceptualization .................................. 26 1.3.1 The Problem, Motivation, and Goals ..................... 26 1.3.2 Hypothesis and Research Questions .................... 28 1.3.3 Research Methodology and Plan ...................... 29 1.3.4 Research Team and Host Institution ..................... 32 1.3.5 Document Structure ............................ 32 2 City Sensing 34 2.1 Rationale ...................................... 34 2.2 A Conceptual Architecture for the Internet of People ................. 35 2.3 Software Agents for City Sensing .......................... 37 2.3.1 The Collector ................................ 37 vii
CONTENTS 2.3.2 ML Architect ................................ 40 2.4 Traffic Flow Forecasting ............................... 41 2.4.1 State of the Art ............................... 42 2.4.2 Exploring spatial-temporal dependencies in time series ........... 45 2.4.3 Data Preparation and Pre-processing .................... 47 2.4.4 Experiments ................................ 50 2.4.5 Results and Discussion ........................... 53 2.5 UV Index Forecasting ................................ 60 2.5.1 State of the Art ............................... 61 2.5.2 Data Preparation and Pre-processing .................... 62 2.5.3 Experiments ................................ 64 2.5.4 Results and Discussion ........................... 65 2.6 Summary ...................................... 66 3 Crowd Sensing 68 3.1 Rationale ...................................... 68 3.2 Passive Sensing ................................... 69 3.2.1 State of the Art ............................... 69 3.2.2 Materials and Methods ........................... 71 3.2.3 Range Measurement Experiment ...................... 78 3.2.4 Passive Crowd Sensing Experiment ..................... 80 3.2.5 Results and Discussion ........................... 83 3.3 Active Sensing ................................... 87 3.3.1 State of the Art ............................... 88 3.3.2 Materials and Methods ........................... 89 3.3.3 Geofencing ................................. 93 3.3.4 Emotional Map from People’s Feelings ................... 98 3.4 Summary ...................................... 103 4 Citizen Sensing 105 4.1 Rationale ...................................... 105 4.2 An Adjective Selection Personality Assessment Method ................ 106 4.2.1 State of the Art ............................... 108 4.2.2 Data Collection and Exploration ....................... 109 4.2.3 Data Preparation and Pre-processing .................... 115 4.2.4 Experiments ................................ 119 4.2.5 Results and Discussion ........................... 123 4.3 Boredom Detection ................................. 131 viii
LIST OF TABLES 4.7 Architecture II results with and without data augmentation, for each independent trial, with sample accuracy as metric. Hyperparameters described by letters as follows: a. number of estimators, b. eta, c. gamma, d. trees’ max depth, e. minimum child weight, and f. colsample by tree. ................................... 126 4.8 Evaluation results of Architecture II, with and without data augmentation, based on trait’s accuracy obtained from the test folds of the outer-split. .................. 127 4.9 Features available in the boredom dataset. ........................ 138 4.10 Hyperparameter’s search space for each candidate model. ................ 141 4.11 Summary results of the three best candidate models, per algorithm, for boredom detection. 142 4.12 Single pedestrian answers to the TMQ-5, CRQ-4, and SAIQ-3. ............... 149 4.13 Entropic states’ evaluation for the best and worst case’s scenarios for the TMQ-5. . . . . . 151 4.14 Predicate’s extension obtained from the answers of a single pedestrian to the questions of the TMQ-5, CRQ-4, and SAIQ-3. BCS stands for best-case scenario. WCS stands for worst-case scenario. ........................................ 152 6.1 Location, in this thesis, where the elicited tasks, research questions, and goals are addressed. 188 xv
Listings 3.1 Crowd Sensing onProbeRequestCaptureData function. .............. 74 3.2 Crowd Sensing newSighting function. ....................... 75 3.3 Crowd Sensing macToString function. ....................... 75 3.4 Crowd Sensing sketch’s setup function. ....................... 76 3.5 Crowd Sensing sketch’s loop function. ....................... 77 3.6 Creating geofences in Android. ........................... 91 3.7 Monitoring geofences. ................................ 91 3.8 Adding the created geofences. ............................ 91 3.9 Creating the heat-map in Android. .......................... 92 3.10 Changing the dataset of geographically tagged data points that make the heat-map. . . 92 3.11 Removing the heat-map. .............................. 93 3.12 FirebaseGeofence object. ............................. 93 3.13 Access rules to the geofences collection. ...................... 94 3.14 FirebaseFeelings object. ............................. 98 3.15 Access rules to the users_feelings collection. ................... 99 4.1 Routing of the web platform for personality assessment and data collection. . . . . . 111 4.2 The resultsRouter is the one responsible for rendering the subject’s personality traits. 112 4.3 Creation of a BroadcastReceiver to listen for changes on the audio jack. . . . . . . 134 4.4 Creation of a SensorEventListener to register the accelerometer sensor value. . . . 134 4.5 Access rules to the boredom collection. ...................... 137 4.6 Predicates’ extensions. ............................... 145 xvi
List of Algorithms 2.1 Computation of missing timesteps. ........................... 49 2.2 From an unsupervised to a supervised problem. ..................... 49 2.3 LSTM model’s conception and compilation. ....................... 51 4.1 Filling the selected_attr feature. ............................ 117 4.2 Building the Gradient Boosted models. .......................... 122 xvii
Acronyms ADAS Advanced Driver Assistance System AI Artificial Intelligence AmI Ambient Intelligence ANNs Artificial Neural Networks AP Access Point ARIMA AutoRegressive Integrated Moving Average ARIMAX AutoRegressive Integrated Moving Average with Explanatory Variable ARL Association Rules Learning ASAP Adjective Selection to Assess Personality AUC Area Under the Curve BLE Bluetooth Low Energy BPTT Backpropagation Through Time CNNs Convolutional Neural Networks CRISP-DM Cross-Industry Standard Process for Data Mining CRQ-4 Crossing Roads Four-Item-Questionnaire DA Data Augmentation DL Deep Learning EML Extreme Machine Learning GDPR General Data Protection Regulation GRUs Gated Recurrent Units GUI Graphical User Interface xviii
ACRONYMS HTTP Hypertext Transfer Protocol IDE Integrated Development Environment IEEE Institute of Electrical and Electronics Engineers IoP Internet of People IoT Internet of Things ISLab Synthetic Intelligence Laboratory ITS Intelligent Transportation System JSON JavaScript Object Notation KRR Knowledge Representation and Reasoning LSTMs Long Short-Term Memory Networks MAC Media Access Control address MAE Mean Absolute Error MAS Multi-Agent Systems ML Machine Learning MLPs Multilayer Perceptrons MQTT Message Queuing Telemetry Transport MSE Mean Squared Error OUI Organizationally Unique Identifier P2V Pedestrian-to-Vehicle PMML Predictive Model Markup Language PoC Proof-of-Confidence PoW Proof-of-Work ReLU Rectified Linear Unit RMSE Root Mean Squared Error RNNs Recurrent Neural Networks xix
ACRONYMS RRS Road Restraint System RSSI Received Signal Strength Indicator SAIQ-3 Self-Assessment and Identity Three-Item-Questionnaire tanh Hyperbolic Tangent TMQ-5 Travel Motivation Five-Item-Questionnaire URI Uniform Resource Identifier UV Ultraviolet V2I Vehicle-to-Infrastructure V2V Vehicle-to-Vehicle V2X Vehicle-to-X VANETs Vehicular Ad-hoc Networks VRUs Vulnerable Road Users WHO World Health Organization xx
Chapter 1 Introduction We all desire a better life for ourselves, for our community, and for all beings that inhabit our planet. Indeed, since the dawn of times, the human being has always endeavored to improve his quality of life. From the discovery of fire and the invention of the wheel to walking on the moon or the world’s globalization. The journey has been amazing. But it has not yet finished. We must keep striving to improve our world. Our mission is to take advantage of the amazing technological revolution the world is experiencing to improve our quality of life, reduce and eliminate diseases, and ensure a prosperous future for our planet and future generations. The work here addressed aims to contribute, even if on a small scale, to this endeavor. 1.1 Research Domains During these last decades, migration towards urban centers has significantly increased worldwide. It is estimated that in 2018 more than 55% of the world’s population lived in urban settlements, being predicted that one in every three people will live in cities with at least half a million inhabitants by 2030 [1]. In fact, the number of megacities worldwide, i.e., cities with more than 10 million inhabitants, is expected to rise from 33, in 2018, to 43, in 2030 [1]. This evidence, coupled with the fascinating technological evolution we are now experiencing, makes the foundations on where this thesis rests, with the next lines describing and characterizing the main research domains at the basis of this work. 1.1.1 Road Safety and Vulnerable Road Users Road safety has been rising to prominence in today’s society. For instance, according to the World Health Organization (WHO), an agency of the United Nations responsible for global public health, the number of deaths related to road traffic accidents climbs every year, reaching 1.35 million deaths in 2016 [2]. Still according to WHO, road traffic accidents are the eighth leading cause of death for all age groups 1
CHAPTER 1. INTRODUCTION (Figure 1.1), being the number one cause of death for children and young adults aged between 15 and 29 years. In fact, more people die as result of road accidents than from AIDS or tuberculosis [2]. 0 2 4 6 8 10 Ischaemic heart disease Stroke Chronic obstructive pulmonary disease Lower respiratory infections Alzheimer disease and other dementias Trachea, bronchus, lung cancers Diabetes mellitus Road injury Diarrhoeal diseases Tuberculosis Millions of deaths Top 10 causes of death by 2016 Figure 1.1: Top 10 global causes of death in 2016. Data obtained from [3]. Inequalities in the number of road traffic deaths are also visible in different regions of the globe. Figure 1.2 depicts the number of road traffic deaths per 100 000 population in different regions. Africa and South-East Asia are the regions with a higher ratio of traffic deaths. In contrast, Europe and America depict a lower number of deaths per 100 000 inhabitants. Data also show that high-income countries have a significantly lower ratio of deaths when compared to middle and low-income countries [2]. 0 5 10 15 20 25 30 Africa South-East Asia Worldwide Eastern Mediterranean Western Pacific America Europe Road traffic deaths per 100 000 population Figure 1.2: Ratio of road traffic deaths per 100 000 population in WHO regions in 2016. Data obtained from [2]. Road traffic injuries and deaths are a major health problem. In this context, road safety refers to a set of methods and measures adopted to prevent and reduce injuries in road users. Examples may include the dissemination of awareness campaigns, the improvement of physical features of roads such as road pavements [4] and road barriers [5], or the inclusion of sensorization and Artificial Intelligence (AI) to model and improve traffic dynamics [6–8], among many others. 2
CHAPTER 1. INTRODUCTION The group of road users includes multiple distinct actors such as pedestrians, cyclists, passengers, drivers, and even public transport users. However, on the road, there are groups of people more vulnerable than others to injuries and accidents. Those are known as Vulnerable Road Users (VRUs), being defined by the European Parliament as ”non-motorized road users, such as pedestrians and cyclists as well as motorcyclists, and persons with disabilities or reduced mobility and orientation” [9]. Their vulnerability may arise from several directions including the lack of external protection, age, physical and mobility impairments, and visual and/or hearing disabilities. Currently, it is estimated that more than half of all road traffic deaths are amongst pedestrians, cyclists, and motorcyclists [2]. Indeed, VRUs are still often neglected by road traffic agencies of many countries. It is usual for police forces to consider accidents with such users as non-traffic crashes, which negatively influences existing records and estimations [10]. Worldwide, pedestrians and cyclists represent 26% of all road traffic deaths. Motorized two and three-wheelers represent 28% [2]. These numbers are consequence of policies that prioritize vehicles instead of people, that ignore VRUs when planning and designing roads, and that devalues the importance of crossings for pedestrians and separate lanes for cyclists. In the European Union, as depicted in Figure 1.3, in 2017, 21% of all people killed on roads were pedestrians and 26% were 2-wheelers, which includes motorcyclists (15%), cyclists (8%) and moped users (3%) [11]. Car Passengers 46% Pedestrians 21% Other 7% Motorcyclists 15% Cyclists 8% Moped Users 3% 2-Wheelers 26% Figure 1.3: Percentage of road fatalities in the European Union by transport mode in 2017, considering all road types. Data obtained from [11]. In the European Union, most road traffic deaths in 2017 occurred on rural roads (54%), with 38% happening in urban areas and only 8% in motorways. In addition, while in 2010 only 18% of all road fatalities concerned elderly people, that number increased to 28% in 2017. These numbers are a clear indication of the increased vulnerability of those over 65 years old as pedestrians, especially in urban areas [11]. In fact, considering only urban roads, the percentage of pedestrians’ fatalities nearly doubles (from 21% to 40%), with the percentage of cyclists’ deaths increasing by 50%. On the other hand, car passenger fatalities reduce from 46% to 26% (Figure 1.4). A temporal analysis of crash reports showed that pedestrian deaths are more likely to happen on holiday periods and on the last two months of the year, while most cyclists’ fatalities occur during the summer or 3
CHAPTER 1. INTRODUCTION Car Passengers 26% Pedestrians 40% Other 4% Motorcyclists 14% Cyclists 12% Moped users 4% 2-Wheelers 30% Figure 1.4: Percentage of fatalities in urban roads in the European Union by transport mode in 2017. Data obtained from [11]. early fall [12]. For cyclists, the risk of crashes also increases in urban environments [13]. The presence of retail stores, touristic places, and environmental factors, such as the weather, also increase the risk of vehicle and bicycle collisions [14]. Large urban areas, either due to its higher density of vehicles, lower number of sidewalks and pedestrian crossings, inconstant or non-modeled traffic dynamics, or higher values of pollution, pose increased risks to VRUs. In fact, on an urban context, the number of VRUs’ deaths is substantially higher than the number of deaths of vehicle passengers. To reduce this number, one is required to pay attention to the needs of VRUs, who have been neglected by transport and planning policies [2]. In addition, measures that induce walking and cycling also promote physical exercise, the reduction of air pollution and greenhouse gas emissions, and lead to better road traffic dynamics. Reduce VRUs’ injuries remains a big challenge. No singular approach will solve the problem. Instead, the expectation is that multiple small contributions may help answering important challenges raised by this group of road users. Hence, we are required to have safer roads and infrastructures, to advance vehicles, to conceive passive and active devices and models, to have stronger regulations, better awareness campaigns, and we must consider VRUs as active and participative actors of the road ecosystem. 1.1.2 Internet of Things and the Internet of People Internet of Things (IoT) is a paradigm being increasingly supported by different stakeholders. It is considered as the next big step in the evolution of the Internet [15]. The idea is to connect multiple heterogeneous devices, or ”things”, through wireless connections and unique identifiers to create a pervasive environment where a person can interact, at any time, with the digital and the physical world. IoT opens exciting opportunities but also new questions on the interaction between the citizen and the machine. Commonly known objects such as clothes, food packing, shoes, or bicycles, among many others, will be equipped with some level of internet-addressable feature, offering context awareness and communication features [16]. The large-scale implementation of IoT devices promises to transform our lives. For consumers, new products 4
CHAPTER 1. INTRODUCTION Ambient Intelligence Ambient Intelligence (AmI) is a multi-disciplinary domain that deals with the development of intelligent systems, i.e., it consists of sensors and actuators incorporated into an environment, which then becomes sensitive and responsive to the presence and needs of a human being in a non-intrusive way [63]. AmI is built upon the fields of pervasive and ubiquitous computing, context awareness, and human-computer interaction [64]. The evolution of technology was a key factor in the appearance of AmI. In the last years, we have evolved from large hardware devices to smaller, connected, and more integrated processors and devices, which originated the IoT. This allowed the incorporation of computational power in familiar objects such as vehicles, fridges, bus stops, and even windows and lighting systems. In fact, sensorization is a key factor of intelligent systems, together with reasoning and acting [65]. This last factor consists in perform some action in the environment based on the output of reasoning models conceived using ML, Rule-based Systems, or Case-based Reasoning. Sensorization, in turn, is what enables AmI. Since AmI is built for real-world environments, the effective use of sensors is crucial to maximize the number and quality of the data streams that describe the environment. In a Smart City, the goal is to invoke large scale AmI by creating several distinct sensorization levels [66]. As depicted in Figure 1.6, on the first level one can find public APIs that can be used to extract relevant information such as road traffic conditions, the weather, and pollution levels. On a second level, there are the devices that can be used by people in their daily routine, being crucial enablers of the citizen sensor. This level also includes straightforward user data such as gender, age, weight, impairments, blood pressure, consumption habits, personality, and social characteristics. The third level comprises the city in itself and methods for extracting actionable data from the environment. 1. 2. 3. API City Citizen Sensor Ambient Intelligence Scale Levels Age Figure 1.6: Sensorization levels in a Smart City. 11
CHAPTER 1. INTRODUCTION Blockchain The exponential growth of cryptocurrencies, with Bitcoin in the lead, was what put the spotlight on blockchains. Indeed, more than a paradigm, blockchain is a data structure, a technology, and a protocol, all at the same time. It is unclear who first coined the term, although it is likely to have arisen from the paper that originated Bitcoin [67], authored by Satoshi Nakamoto, where terms such as ”block in the chain” or ”chain of blocks” are used. As the name implies, a blockchain is essentially a chain of blocks that contain data, with the first block of the chain being called the genesis block. It is interesting to note that what makes a blockchain trustworthy is the fact that nobody in the network trusts anybody. Thus, the higher the number of nodes in the network the greater the security and the trustworthiness of the blockchain. Empowered by cryptocurrencies, blockchains have been widely used to store transactions of currency, allowing nodes to store, validate, and understand from where and to where each amount of currency is being moved. However, soon researchers understood the applicability of such technology in different domains. One example is the effective development of smart contracts by Ethereum [68]. In fact, new approaches to blockchains have emerged and are, indeed, still emerging. From product traceability [69] to food safety and origin in supply chain problems [70], blockchain and smart contracts provide means to guarantee provenience and compliance rules between all the involved parties. In the field of medicine, blockchain examples can be found, essentially, in secure health records sharing [71–73]. In the field of the IoT, since such networks are data-centric and device-centric by nature, blockchain is particularly suited to deal with data correctness and to handle malicious behaviors of devices [74]. Security in data exchange is also important within IoT networks, with blockchain being used to provide decentralized authentication systems for IoT devices [75]. Indeed, it has been corroborated that blockchains have now moved beyond financial services and smart financial contracts [74,76]. 1.2 Related Work and Projects in the VRUs’ domain Road safety has become a major issue of concern for several stakeholders. The European Union, for example, has adopted the ”Vision Zero and Safe System approach” to eliminate deaths and severe injuries on European roads by 2030. Hence, it is natural to find several distinct studies and projects being developed in the road safety domain. The next lines describe the main academic literature and industrial projects that give special importance to the VRUs’ problem. 1.2.1 Academic Literature Several studies have already engaged in connecting the domains of road safety with the IoT. One example is the one of Mitton and Rivano (2014) who proposed a theoretical model to compute data gathered through mobile sensors in bicycles. The goal was to ”make the bike easier and make people want to ride bicycles more often” (p. 3) [77]. Another work, performed by Miyaji (2015), used data about traffic incidents to clarify which are the major psychosomatic states of drivers who experienced an incident [78]. 12
CHAPTER 1. INTRODUCTION Another example of a study that made use of data gathered by IoT devices is the one performed by Zheng, Rajasegarar, and Leckie (2015), where the authors employed several mechanisms to predict parking occupancy rate, thus allowing the citizen to avoid full parking lots, which may lead to better traffic dynamics and fewer accidents [79]. These examples are useful to demonstrate the importance of data made available by the IoT [16]. In the promising Smart Cities of the near future, communication between vehicles and the city will be constant [80,81]. Hence, studies are taking advantage of Vehicular Ad-hoc Networks (VANETs) to improve not only road safety but also the driver’s quality of life. VANETs are a technology that uses cars as nodes of a network to create a mobile network of vehicles [82]. This allows vehicles to easily communicate among them and with fixed infrastructures. Barba et al. (2012) developed a Smart City framework for VANETs that included intelligent traffic lights set on crossroads of a city that transmit warning messages and traffic statistics to vehicles [80]. However, a set of assumptions were made that are hardly true today. For instance, not all vehicles have global positioning systems and driver wizards with full information about the position of intelligent traffic lights, which was required by the designed framework. Another example may be seen in the work of Bui, Lee, Jung, and Camacho (2016), who, inspired by recent progress in vehicle technologies, propose a new approach to manage, in real-time, the traffic flow at road intersections by controlling the traffic light scheduling. They simulated their approach, being able to reduce the waiting time at intersections [83]. Indeed, the community has been using VANETs and Intelligent Transportation System (ITS) to improve and organize the flow of vehicles on the roads [84] and to provide real-time updated information of roads and traffic status [85]. Privacy and security of VANETs are also a hot-topic. The goal is to guarantee proper behavior of the network and the ability to resist to intrusions [86–88]. Focusing on vehicular communications, several authors have been studying possible forms of communication between vehicles, pedestrians, and infrastructures, also known as Vehicle-to-X (V2X). In this context, Vehicle-to-Vehicle (V2V) is a form of bi-directional communication between vehicles. The exchanged information may be used to calculate traffic conditions, geographical positions, to avoid inter-vehicle collisions, or to propagate rescue messages after an accident [89,90]. Vehicle-to-Infrastructure (V2I) is a form of communication between a vehicle and an infrastructure, usually built on roads or streets. V2I may be used, for example, by a vehicle to identify its position or to obtain information about traffic and road conditions [91,92]. In 2019, Casademont et al. proposed a cooperative-ITS for VRUs in which vehicles alert drivers of potential collisions with cyclists [93]. Even though the authors claim their framework is for VRUs, the fact is that VRUs are passive actors. The focus is only on informing the driver, i.e., the non-vulnerable user, about a possible collision. The developed framework required a large set of sensors and devices, i.e., stations, to be installed in cars and bicycles. For instance, cars required digital cockpits to show warning messages to the driver while bicycles were equipped with high precision location systems based on GPS, inertial sensors, and ultra wide-band ranging. Communication between the installed stations is provided by a network that supports V2X communications [93]. Nonetheless, other forms of vehicular communication are emerging. Forms mainly focused on pedestrians. Such forms may be defined as Pedestrian-to-Vehicle (P2V) and are shifting the focus from vehicles to pedestrians. This form of communication would allow the 13
CHAPTER 1. INTRODUCTION exchange of messages between VRUs and vehicles, in both directions [94–97]. However, P2V is still in its infancy, being, at the moment, more a concept than reality. In 2014, Cho proposed a P2V communication system focusing on conflict zones such as unsigned single roads and intersection areas [96]. It had, as main focus, children and old people. The proposed theoretical system consisted of three parts named as on-board unit, road-side unit, and portable unit. The first one is installed in vehicles, the second one is located on the road, and the last one is used by pedestrians. Although the authors claim to use a type of P2V communication, real communication happens between vehicles and infrastructures, and only then between infrastructures and the pedestrian. There is no direct communication between people and vehicles. More examples of theoretical studies can be found in [98] and [99]. The first one proposes the combination of new wireless technologies with existing collision prevention systems. It also addresses important trade-offs for information exchange between vehicles and VRUs, namely low latency, low energy consumption, high position accuracy, and high warning reliability [98]. Besides these trade-offs, there is one that should not be forgotten, i.e., cost. A hypothetical solution for the VRUs’ problem will only be implemented if it is economically viable. The second study proposes the concept of a hybrid city lighting to provide a more economical, safer, and smarter way to lighten up the way through future cities by projecting games on the pavement. With depth sensors implemented in the city’s infrastructure, the authors claim they would also be able to develop car warning systems and detect clear ice areas on pavements or roads [99]. Another approach focuses on indirect communication between vehicles and VRUs, which can be achieved by means of interfaces installed in vehicles. In [100], the authors propose a set of interface concepts for autonomous vehicles to communicate its intention to VRUs in urban situations. The goal is to have unambiguous communication between road actors. Hence, some constraints must be considered. In particular, it should be avoided the use of language and cultural-specific symbols. In fact, in the designed interfaces, the authors considered three autonomous vehicle states: the vehicle is cruising, yielding, or it is starting to drive. Six interface concepts were proposed. One, for example, consisted of equipping the front bumper of the autonomous vehicle with a light strip that would work as a communication interface. The interface would light up with different patterns based on the car’s intention. Another concept consisted of a band of light that surrounds the entire vehicle. In this concept, in urban scenarios, the band would only light a small segment on the part of the interface that is close to the detected VRUs. This would allow VRUs to acknowledge that they were, or not, detected by the autonomous vehicle and act accordingly. Colors can also be used to inform VRUs about the intention of the vehicle to yield, or not, to them [100]. Interestingly, most of the work done in this domain was performed by automobile manufacturers [101–103]. The fact is that VRUs’ vulnerability may arise from many directions. The most common include the lack of external protection, road user’s age, physical and mobility impairments, and visual or hearing disabilities, among others. Hence, many different methods can be followed when the goal is to increase VRUs’ safety. One that has been receiving attention from the community is related to VRUs’ intent and trajectory prediction. A major challenge of this method is related to the high degree of uncertainty of VRUs’ actions in urban environments. For instance, in 2019, Saleh, Hossny, and Nahavandi proposed a model to predict 14
CHAPTER 1. INTRODUCTION long-term VRUs’ intentions using reinforcement learning and Recurrent Neural Networks (RNNs). The authors defined long-term as 2/3 seconds ahead. Even though the models presented positive results, many decisions were made solely from an empirical point of view, without further experimentation and evaluation. Nonetheless, to train the models the authors used and pre-processed two distinct datasets [104]. One, the Stanford drone dataset [105], is available online and consists of a bird’s eye view camera mounted on a drone hovering the campus of Stanford’s University. This dataset is made of several videos with frame by frame bounding-boxes annotations on moving targets such as pedestrians, bicyclists, skateboarders, cars, buses, and golf carts [104,105]. The second used dataset, which is also available online, was Daimler’s path dataset [106]. This dataset consists of frame sequences recorded with a stereo camera system mounted behind the windshield of a vehicle and contains four pedestrian motion scenarios. Pedestrians are also annotated with bounding boxes. More examples of studies that focused on RNNs to predict VRUs’ intentions are [107], [108], and [109]. In [107], the authors focused on LSTMs to model human interactions in crowded spots. Data were obtained from the perspective of surveillance cameras. In [108], the authors also conceived LSTMs to predict trajectories of pedestrians, using only past positional data to forecast the next trajectory point. Finally, in [109] the authors used LSTMs with attention mechanisms to forecast pedestrians’ intentions, demonstrating that forecast delays of less than 1 second may significantly affect the accuracy of models. In addition, it should be noted that cyclist velocities at intersections are typically higher than those of pedestrians, which prevents models from generalizing to both scenarios without accuracy loss [110]. A different approach focuses on the spatial and temporal analysis of crashes involving vehicles and VRUs. The goal is to identify areas where the vulnerability of such users is specially high, mainly in the framework of Smart Cities [111,112]. In [113], the authors focused on the recognition of hazardous areas, also called blackspots, which can be defined as a particular zone that has a crash frequency significantly higher than other zones. In the performed study, blackspots are built on the density and severity of injuries, i.e., injuries are weighted based on its severity (light injuries, severe injuries, and fatalities). Several features were considered by the authors during their analysis, including VRUs’ age and gender, injury severity, temporal variables, weather conditions, road location, and the surrounding environment. The authors found that September, October, and November were the months with more injuries, corroborating the results of [12], and that January and February seem to be the months with more fatalities. Thursdays and Fridays were the weekdays with more injuries. In addition, the authors found that more than 40% of pedestrianvehicle accidents occur in the presence of crosswalks or traffic lights. No record of severely injured or dead cyclists occurred close to cycle lanes, strengthening the importance of such infrastructures to increase the safety of cyclists in an urban context. As for the used dataset, it contained VRUs crash data from three Portuguese cities between 2012 and 2015. In 2015, Anaya et al. presented a novel Advanced Driver Assistance System (ADAS) to prevent accidents involving motorcyclists and cyclists. The authors developed a VRUs detection system where vehicles and motorcyclists have their own communication unit. On the other hand, cyclists, whose bicycles have reduced 15
CHAPTER 1. INTRODUCTION communication capabilities, are equipped with an on-board sensor known as iBeacon. An iBeacon is a lowpowered bluetooth-based sensor with low-cost transmitters. It notifies bluetooth devices of one’s presence. This study focused on keeping the non-vulnerable driver informed about the presence and location of VRUs by having a unidirectional information flow. In a previous study, the same authors have studied the accuracy and performance of several technologies such as GPS and Wi-Fi. Such studies are important as benchmarks since VRUs and drivers need to be informed of a possible collision as soon as possible, leaving no time for latency or packet losses [91]. Liebner, Klanner, and Stiller (2013) have also focused on the benefits that smartphones could bring to VRUs. The authors evaluated accuracy and transmission latency for smartphone-to-car communications, being able to show that the performance of the smartphone’s GPS is heavily affected if the smartphone is, for example, in the breast pocket of a jacket [114]. Another study, conducted by Pyykonen, Virtanen, and Kyytinen (2015), focused on the problem of collisions between heavy goods vehicles and VRUs, in particular cyclists and motorcyclists. To address this problem the authors conceived an intelligent blind spot detection system to detect objects in blind spots and warn drivers. To achieve their goal, vehicles required new sensors such as stereo cameras, short-range radar sensors, and ultrasonic range finders. These sensors gather data that are presented to the driver through a human-machine interface based on audible and visual warnings, and a bird-eye view of the vehicle [115]. A different approach to this problem may be seen in [116]. The authors’ approach is to make use of sensors to detect users and their movement, and then send alerts to vehicles nearby. The proposed system is composed of several modules, including a VRUs detection module, a road-side unit, which is part of the road’s infrastructure and is responsible to transmit messages to vehicles, and an on-board unit, which is installed in the vehicle, receives messages, and notifies the driver. The model is, in its essence, based on a VANETs’ approach. It is however disregarding VRUs as an active and proactive part of the system. Moreover, it showed important drawbacks such as the inability to detect pedestrians walking at higher speeds [116]. 1.2.2 Related Projects Having the VRUs’ problem a significant societal impact, it is possible to find projects that are being funded and supported by associations, companies, and/or institutes, that aim to promote the evolution of industry while improving people’s quality-of-life. Evidently, the difficulty of reviewing such projects is substantially higher when compared to a traditional literature review. The main documentation produced by these projects consists of gray literature, i.e., materials and research produced by companies outside of the traditional academic publishing channels. Such documentation includes work package reports, white papers, case studies, project’s blog news, and government documents, among others. The lack of guidelines and standards significantly increases the difficulty of finding, analyzing, and evaluating gray literature. The concealment of results and documents is yet another adversity to overcome. 16
CHAPTER 1. INTRODUCTION 1.2.2.1 Projects’ Search Strategy A centralized platform to aggregate all projects is a non-existent situation. Therefore, to conduct the review, an extensive search was performed among different databases. In addition to typical scientific databases, a search was also performed among research and innovation programs, such as European Commission’s CORDIS, The EU Framework Program for Research and Innovation (Horizon 2020), the European Commission’s Seventh Framework Program (FP7-ICT and FP7-SST) and the International Transport Forum. Search engines were also used as well as the ”Related Projects” page of the selected projects, which proved to be important to find projects working in similar themes and domains. The focus went towards projects comprising road safety, VRUs,IoT, and Big Data. The more factors being pursued the best. Search terms and keywords were grouped using boolean operators, with the search being conducted in the first months of 2019. Upon inadequate or non-existent information, the project would be discarded. Figure 1.7 depicts the main steps of the followed strategy to find relevant projects. Objectives Databases Academic Industry IEEE Xplore CORDIS Scopus Horizon 2020 Springer FP7 -ICT and FP7-SST Google Scholar ITF Refinements Selection Criteria • Vulnerable Road Users • Internet of Things • Road Safety • Big Data Refinements Sort Search on project’s title, summary and description By Relevance English language By Date Limit to recent years (≥ 2009) Relaxed look at previous years 1. Relevance of project’s title, summary and description 2. If classified as relevant, read and analyse the project’s roadmap, work packages, publications and grey literature 3. Look for a Related Projects page. If its existence was confirmed, evaluate the referred projects. Figure 1.7: Projects’ search strategy. 17
CHAPTER 1. INTRODUCTION 1.2.2.2 Projects’ Review Fourteen projects were considered relevant in regard to their proposal for safety enhancement and technological evolution. A critical analysis of the selected projects allowed us to summarize the main findings and advances produced by already closed projects and, at the same time, evaluate the novelty of those that are yet ongoing. ARTRAC: Advanced Radar Tracking and Classification for Enhanced Road Safety The ARTRAC project consisted of a consortium of seven partners including universities, automotive manufacturers, and research organizations. It is an already closed project that began on November 1st, 2011 and had a duration of three years. It focused on 24 GHz radar sensors, equipped in cars, to protect VRUs in general. ARTRAC aimed to develop a generic detection system capable of detecting pedestrians and cyclists as well as other vehicles [117,118]. This project focused on vehicles and how to use sensor technology to increase road safety. It soon became clear that vehicles would greatly benefit from the presence of sensors to improve the driving experience and increase the safety of the road actors. This project aimed to equip cars with radar sensors to detect obstacles, such as VRUs, on the road. In fact, nowadays most vehicles use such sensors for parking assistance or distance calculations. The goal of the ARTRAC consortium was to improve vehicles, being partially successful. The non-vulnerable users were just passive elements that were only used to be marked as obstacles. HIGHTS: High precision positioning for cooperative ITS applications HIGHTS is an H2020-funded research project. It started in May 2015 and finished in April 2018. HIGHTS Consortium comprises fourteen partners from five countries. The consortium aimed to combine traditional satellite systems with an innovative use of on-board sensing and infrastructure-based wireless communication technologies to produce highly-accurate positioning technologies (accuracy of 25cm) for Cooperative- ITS, focusing on developing protocols and network support for data exchange between vehicles, infrastructure, and IoT devices [119]. The intention was for the developed platform to be a key enabler of cooperative adaptive cruise control and platooning. The platform intends to increase VRUs safety through bi-directional danger detection and by detecting slight deviations from driving courses [120]. Unfortunately, at the time of writing, and even though the project is now closed for a long time, no information is available regarding the completeness and implementation of the final solution. The greatest innovation this project aimed to bring was the development of a highly accurate positioning technology for vehicles. In fact, the focus of HIGHTS was on enabling cooperative adaptive cruise control and platooning. However, it should be recognized that many applications could benefit from this new technology as it could easily allow one to apprehend the exact presence, direction, and velocity of vehicles and, thus, increase the efficiency of models to predict VRUs’ intentions. 18
CHAPTER 1. INTRODUCTION ICSI: Intelligent Cooperative Sensing for Improved traffic efficiency ICSI was a FP7 project co-funded by the European Commission under the ICT theme, launched in November 2012 with a duration of thirty-six months. The consortium comprises partners such as INTECS and Brisa - Auto-Estradas de Portugal. The project’s goal was to define a new architecture to enable cooperative sensing in ITS. Thus, based on real-time data, ICSI intended to develop a prototype of an European traffic monitoring system, enhancing energy efficiency in transportation systems. The consortium predicted that reductions in carbon dioxide emissions would be its most striking feature. The proposed fully-distributed architecture was able to detect and act over some of its elements, using the available local storage and computational resources. Sensor prototypes, road-side units, and communication units are required to be developed and integrated into the conceived platform [121,122]. In this project, the targets are vehicles and traffic efficiency. ICSI focused on computer vision technologies, consisting of a set of camera-based sensors accompanied by a communication module that provided information on traffic flow and parking areas occupancy. Being difficult to unveil the true practical benefits of this project (and if/how they were achieved), it can be seen as a starting point for future projects, mainly for those aiming to advance traffic strategies based on real-time data. Within ICSI, the user is unconscious of his key role (e.g., occupying/freeing a parking lot, or increment/decrement traffic congestion) but his participation is mandatory. Ko-TAG: Kooperative Sensorik Ko-TAG was a collaborative research project with partners of the automotive industry and sponsored by the German Federal Ministry of Economy and Technology. It was launched in 2009 and lasted four years. The project was focused on cooperative radio-based sensing technology, mainly for V2V communication and VRUs’ security. Vehicles were equipped with tracking units that query transponders carried by road users. Based on the received responses, the tracking unit determines the relative positions of nearby road users, classifies them, and assesses the risk of a collision. If there is such a risk, the system will either warn the driver or act to mitigate it, preparing the vehicle for an emergency stop. To refine the results, the tracking system uses an inertial measurement unit integrated into the transceiver to acquire data on pedestrians’ speed and direction. Pedestrian behavior is predicted with a statistical-based model [123,124]. The lack of available documentation was an adversity when analyzing this project, especially when most of the information was not in the English language. However, it is worth noting that this project aimed to bring benefits to vehicle emergency stops and autonomous emergency braking systems. Enhancing the safety of VRUs was also a priority, being Ko-TAG a project that proposed a novel concept of transponders carried by road users that would be detected by vehicles equipped with a specific antenna system. In recent years, the performance of devices, such as smartphones or sensors, has increased significantly, which reduces the need for proprietary software and hardware. In addition, considering VRUs as simple ”things holders” prevents the use of algorithms for affective computing and behavioral analysis, leaving manual observation and statistics as the only possibilities for behavior modeling. 19
CHAPTER 1. INTRODUCTION MAVEN: Managing Automated Vehicles Enhances Network MAVEN is an H2020-funded project, coordinated by the German Aerospace Centre and Dynniq, with partners such as TomTom and MAPtm. It is a three-year project, having started in September 2016. MAVEN’s main goal is to enhance intelligent urban road transport network and cooperative systems for infrastructureassisted automated vehicles. It aims to develop algorithms to organize the flow of such vehicles and to structure the negotiation processes between vehicles and the infrastructure. The expectation is to increase traffic efficiency, improve infrastructure’s capacity, and reduce emissions. In addition, it pretends to integrate new ADAS techniques to prevent dangerous situations with VRUs and contribute to V2V and V2I interactions through vehicle platooning and scheduling algorithms [125]. It is easily noticeable that most big cities are experiencing traffic problems on their roads. Future autonomous vehicles may help solve this problem and, thus, make traffic flow more homogeneous, improve driver safety and comfort, and reduce fuel consumption. MAVEN intends to study solutions to these issues through the development of new algorithms for platooning and negotiation between automated vehicles [126]. Aware that it can still take some years for fully automated vehicles to drive through our roads, MAVEN also aims to produce a roadmap for the introduction of future traffic management systems [125]. OPTIMUM: Multi-source Big Data Fusion Driven Proactivity for Intelligent Mobility The OPTIMUM project was launched in May 2015 and had a duration of three years. The consortium had INTRASOFT International as coordinator and partners such as the Austrian Institute of Technology and Infraestruturas de Portugal. Due to the increasing saturation of transport networks, new solutions to improve traffic, freight transportation, and connectivity should focus on fuse data collected and processed from several sensors and service providers. Thus, OPTIMUM meant to establish a scalable and distributed architecture for the management and processing of multi-source big data, enabling the continuous monitoring of transportation systems while facilitating proactive actions in a semi-automatic manner. Among others, this project aimed to (1) capitalize on the benefits and potential of big data fusion, (2) design and develop a smart sensing system able to cope with huge amounts of heterogeneous data, and (3) enable semantic understanding of the acquired data to predict the status of transport networks [127,128]. OPTIMUM proved to be a somehow difficult project to evaluate regarding its final result. Several reports are available to the community. However, it becomes impractical to go through several dozens of documents to look for the conceived case studies, the performed tests, and the obtained results. As prototypes, an android app and a web platform were released but it seems both have been discontinued. Nonetheless, it is worth highlighting the use of distinct approaches for data acquisition and fusion. Prospect: PROactive Safety for PEdestrians and CyclisTs The Prospect project was an EU research project funded by the H2020 program. The consortium included Audi, BMW, Volvo, Bosch, and Continental, among others. The project started in May 2015 and had its 20
CHAPTER 1. INTRODUCTION VRUs vulnerability may arise from several directions. In fact, many distinct approaches, with different goals, can be followed and implemented. No solution will settle out all problems nor will it eliminate all fatalities. Instead, the difference will be made through the sum of several small contributions. Hence, the approach followed in this work aims, first and foremost, to recognize VRUs as active, reactive, and participative actors of the city ecosystem, guaranteeing that VRUs are aware of their surroundings. From this premise emerges what we define as the 3-C. The 3-C correspond to City,Crowd, and Citizen sensing, i.e., it consists of three sensorization levels and the corresponding models for knowledge extraction. Based on that, the following goals were defined: • City Sensing - one major goal of this work focuses on sensing the city in itself and on conceiving methods to extract knowledge from the city’s ecosystem. On the one hand, such knowledge can be shared with VRUs with the goal of making such users aware of their surroundings. On the other hand, this goal is directed towards the promotion of smarter cities, i.e., cities able to sense their environment, act on problematic situations, and provide actionable information to their citizens; • Crowd Sensing - also known as mobile crowd sensing, consists in sensing large groups of individuals through means of mobile devices with sensing and computing capabilities. This level lies between sensing the city and the citizen. Two approaches may be followed. A passive approach to crowd sensing allows gathering knowledge about the density of people at certain points of interest for VRUs, such as pedestrian crossings or busier roads. An active approach, on the other hand, incites subjects to participate and opine about their city; • Citizen Sensing - another goal of this work consists of developing means to sense the citizen in order to establish them as more than simple ”things” holders. To achieve such goal, special focus should be given to the use of mobile and wearable devices as well as the design and conception of ML models for affective computing. To strengthen the foundations of this work, two additional goals were elicited: • Smart Cities introduce novel problems related to the management of inordinate amounts of data of different types and sources. Hence, research must be conducted to study new ways to store data in such a context, guaranteeing that data may be committed by any actor, being, at the same time, freely available to anyone that aims to derive knowledge from it; • The development of a collaborative platform that allows VRUs to have access to a set of data and information regarding the environment where he/she stands. The goals here described are the ones to be tackled during this research work. The knowledge and specialization of the research team, as described in a subsequent section, was crucial for the definition of this line of attack. 27
CHAPTER 1. INTRODUCTION 1.3.2 Hypothesis and Research Questions Having settled the problem and goals that underlie this work, it is now time to define the main research hypothesis that will guide the experiments to be carried out: RESEARCH HYPOTHESIS The combination of AmI techniques and Affective Computing with the IoP is an effective approach, in terms of efficiency and efficacy, to enhance VRUs’ safety by making them participative actors of the city’s ecosystem with an increased awareness of their surroundings. The main research hypothesis goes through several fields to achieve the main goal of enhancing VRUs’ safety. In fact, this research work is expected to conduct research in the fields of (1) AmI, to deal with the development of intelligent environments and crowd sensing in Smart Cities; (2) Affective Computing, to give dimension and depth to VRUs; (3) IoP and MAS, to create a collaborative platform to be used by those more vulnerable on the road. The conceived platform is expected to live by itself, using ML models and other techniques to learn and provide actionable information to VRUs. The prediction is that if one uses such techniques and paradigms in the context of a Smart City, it will be easier for VRUs to participate and have access to a set of information about the current and future status of their city, which will make them feel safer and assume better behaviors on the road. Given this array of features, the research hypothesis is broken down into specific solutions’ specimens in the form of exploratory, evaluation, and action research questions: Research Question 1:Is a MAS able to autonomously capture city’s data and produce actionable knowledge from such sources? AMAS is expected to emerge from the conducted research, being comprised of a set of agents that are able to autonomously capture data, pre-processing it, and then make it available for ML models, which are also to be embedded by intelligent agents. The goal is to have a fully-autonomous ML pipeline, going from data collection to model conception. The validity of this research question is to be assessed by means of the produced and deployed prototypes, and their performance. Research Question 2:With the use of Affective Computing techniques and mobile devices, is it possible to accurately measure boredom and the personality of subjects in real-time with a non-invasive, non-intrusive approach? Affective computing is here seen as a way to capture emotions, mood, and personality through computational means. This use case aims to conceive means to measure boredom and personality in real-time, using ML and mobile devices in a non-invasive, non-intrusive manner. This research question is of the utmost importance as it aims to give systems the ability to obtain a deeper understanding of people based on their personal characteristics. This question will be validated through the conception, development, 28
CHAPTER 1. INTRODUCTION and evaluation of models for boredom and personality assessment, being further validated by the scientific community. Research Question 3:Is it possible to implement passive methods for crowd sensing that require no participation from people? This research question focuses on the conception of passive methods for crowd sensing, i.e., methods to sense people without the need to install or carry proprietary software. The goal is to be able to enhance crowd control and people’s safety without requiring citizens to have, in their possession, any mobile application. The validity of this research question is to be assessed through means of prototypes and experimentation as well as by peers in scientific gatherings. Research Question 4:Is blockchain a viable solution (in terms of efficiency and performance) to store structured data? Can intelligent agents work, and maintain, a blockchain? Data collected about a Smart City’s environment should be made available to all. Hence, solutions are required where data may be committed by any actor, being, at the same time, freely available to anyone that aims to derive knowledge from it. Combined with the need for an immutable, distributed, and decentralized approach and the blockchain technology emerges as an evident choice. This research question also deals with the ability of intelligent agents to maintain a blockchain in a MAS context. Given the large spectrum of this use case, it is to be considered validated by means of a case study and the attained results. Research Question 5:Can a collaborative platform allow VRUs to have a better perception of their surroundings and become active actors of the city’s ecosystem? This research question deals with the ability of a platform to make use of models to sense the city’s environment and provide actionable information to its users so that they can use it to have a better perception of their surroundings. Having a larger perception of the environment will allow VRUs to make informed, fact-based decisions. The collaborative aspect is related to the ability of users to contribute to the platform. This research question will be considered validated if such a platform is produced, deployed, and legitimized by the scientific community. The previously elicited research questions aim to further specify the research hypothesis by taking into consideration the addressed domains, thus providing a stronger validation to the research hypothesis. 1.3.3 Research Methodology and Plan Adopting a well-defined research methodology assumes an increased importance when conducting scientific research. The goal is to have an organized and logical sequence of standardized procedures to build scientific knowledge. The process must be replicable, precise, falsifiable, and parsimonious. The research conducted in this PhD thesis follows a scientific research methodology that combines 29
CHAPTER 1. INTRODUCTION both the Hypothetical-Deductive scientific method with the Engineering Process, as depicted in Appendix A. Following the engineering background of this doctoral course, one should bear in mind that it intends to research and develop a solution for a problem. Thus, this work focused on creating knowledge for a purpose produced by scientific applied research, having its validity in a matter of efficacy, efficiency, and utility. It did not aim at creating knowledge that conveys understanding human, group, or social phenomena, which is often referred to as theories or laws. The followed methodology starts with the identification of the problem based on the reviewed literature. A research hypothesis is then devised as a solution to the identified problem. This initial phase is followed by the Design one, which focuses on designing and proposing solutions’ specimens based on the devised hypothesis. In this work, such specimens are to be understood as the research questions defined in Section 1.3.2. The Validation phase is where one focuses on planning and executing experiments, recording observations, interpret results, and draw conclusions. The goal is to validate the conceived specimens in order to prove the research hypothesis. This doctoral plan aims to produce empirical research, i.e., aims to test the feasibility and validity of an hypothesis and the corresponding solution with a set of experiments. In fact, in this work the research methods may be defined as experiments, in the laboratory, both through computer and simulated experiments, as well as proof-of-concepts and field experiments, when deploying the prototypes for people to use it for a period of time. Five main tasks were defined to lead this project to a fruitful conclusion and achieve the proposed objectives. Such tasks were developed during the last three years of the doctoral program, the research period, being as follows: Task 1:Definition, design, and conception of an IoP architecture and a MAS on the context of the VRUs problem. Duration: October 2017 to December 2017 (3 months). IoT has been assuming an increased importance in our lives. However, it leaves aside people as an active, reactive, and participative actor. The IoP came to address this issue. However, being the IoP an emerging paradigm, there is a clear lack of hypothesizing meanings and properties. This task aims to postulate a set of essential properties in the development of the IoP and, based on such features, proceed towards the design of a descriptive IoP-based architecture. This task aids defining the foundations on where the research work rests and intends to help providing an answer to research question nº 1. Task 2:Affective computing and ML models for the citizen sensor. Duration: October 2017 to September 2018 (12 months). The final system is intended to consider the emotional states of its users in order to establish them as more than simple ”things” holders. Therefore, models to extract VRUs-relevant information are defined using ML and AI approaches, with particular focus on Affective Computing. Two main features are considered, i.e., boredom prediction and personality assessment using mobile and/or wearable devices and 30
CHAPTER 1. INTRODUCTION non-intrusive approaches. This task provides the answer to research question nº 2. Task 3:Conception, definition, and implementation of methods and models for city and crowd sensing. Duration: July 2018 to June 2019 (12 months). This task aims to give answer to two goals. On the one hand, it consists in the design and conception of AmI methods to create a sensed city environment. It focuses on two major features: traffic flow forecasting and environmental sustainability, in particular, air pollutants, using DL models. Such information is of the utmost importance for VRUs to have a better perception of their city status. It also focuses on the design and conception of an agent-based system to autonomously go through the entire ML pipeline. On the other hand, this task aims to sense large groups of individuals without requiring the crowd to install any software on their mobile and wearable devices, allowing the possibility of gathering insights at certain points of interest for VRUs such as pedestrian crossings or busier roads. This task provides an answer to research questions nº 1 and 3. Task 4:Experimentation, exploration, and definition of standards and ontologies for data storage. Duration: January 2019 to March 2020 (15 months). Smart cities, to emerge as such, are required to have the ability to create knowledge and reason upon data describing its environment. Such an ability introduces novel problems related to the management of inordinate amounts of data of different types and sources. Hence, solutions are required where data may be committed by any actor, being, at the same time, freely available to anyone that aims to derive knowledge from it. Combined with the need for an immutable, distributed, decentralized approach and the blockchain technology emerges as evident. This task aims to design and conceive a MAS blockchain and evaluate its ability to store structure data committed by any actor. This task provides the answer to research question nº 4. Task 5:Platform implementation. Duration: April 2019 to June 2020 (15 months). The last task focuses on the development of the project’s platform archetype, making use of the conceived solution specimens. The goal is to have a collaborative platform where VRUs are felt, have opinion, and have access to a set of information that can increase their safety on the road. The platform is intended to have front-ends where information is visible. This task provides the answer to research question nº 5, the last research question. Two more tasks go throughout the entire research period. One is related to the analysis of the state of the art. This happens due to the novelty of the addressed domains and to guarantee that one is fully aware of how the art advances during the three years of the research period. The second one is related to 31
CHAPTER 1. INTRODUCTION the scientific dissemination, being focused on the production and publishing of scientific papers in peerreviewed conference proceedings, book chapters, and international journals, sharing the attained results and the main research conclusions. It is important to highlight that the followed methodology is entirely non-invasive, and preserves data and people’s privacy. This research work has no intention of harm. Instead, it aims to commit benefits to our society by contributing with solutions to improve our quality of life. 1.3.4 Research Team and Host Institution The research team is made of three people. The candidate, Bruno Fernandes, holds a Master’s degree in Informatics Engineering from the University of Minho, in Braga, Portugal. He is a scientific researcher at the ALGORITMI Centre, a research unit of the School of Engineering at the University of Minho. He is also an Invited Assistant Professor at the same university, lecturing ML and Intelligent Systems. His current research interests include Smart Cities, IoP,ML,MAS, blockchain, and road safety. Cesar Analide, the supervisor, is a scientific researcher in the AI field. He is also a Professor at the Department of Informatics of the University of Minho, being a founder member of the Synthetic Intelligence Laboratory (ISLab). His main research interests are in the domains of AmI, knowledge representation, MAS, and ML. In the road safety field, he has been producing knowledge regarding the assessment of road traffic expression, driving behavior, well-being, and ambient sensorization. José Neves, the co-supervisor, is an Emeritus Professor in Computer Science at the Department of Informatics of the School of Engineering at the University of Minho, being also a researcher at the ALGORITMI Centre. He was the founder of the AI area at the University of Minho. His research interests include, among others, AI,ML, knowledge representation and reasoning, and evolutionary computing. The research team conducts scientific research at the ALGORITMI Centre, a research unit of the School of Engineering at the University of Minho, focusing its activity on projects that explore a strong link with the community. It is a center of excellence, receiving a Very Good in FCT’s last R&D Units evaluation. Bruno Fernandes, José Neves, and Cesar Analide belong to the ISLab, which has, over the years, made important contributions to the domains of knowledge representation, sensorization, MAS, and ML, just to name a few. The group also has strong partnerships with the School of Medicine, the School of Law, and the Institute of Social Sciences of the University of Minho as well as with other national and international institutions, having large experience in joint projects. 1.3.5 Document Structure This document is organized into six chapters as follows: Chapter 1 established the foundations on where this work rests. It initiated with an introduction to the main research domains. It then provided a thorough review of the state of the art as well as an analysis of related projects. This chapter ends with the conceptualization and formalization of the research plan, research questions, and working hypothesis. 32
CHAPTER 1. INTRODUCTION Chapters 2 to 5 detail the experiments that were conducted throughout the execution of the research plan to validate the postulated research hypothesis. Each chapter has a similar structure, i.e., starts with the theoretical foundations and the rationale behind the performed experiments, it then details each experiment, ending with an analysis and discussion of the case study and the obtained results. These chapters are presented using the 3-C concept, i.e., City,Crowd, and Citizen sensing. Chapter 2, City Sensing, presents and details all experiments that aim to sense the city in itself. It starts with the MAS that was conceived to collect data for a city and automatically create and fit ML models. It then details two major experiments in regard to a city’s environment, i.e., traffic flow forecasting and Ultraviolet (UV) index forecasting. Chapter 3, Crowd Sensing, details the experiments that were conducted for crowd sensing. Particularly, it describes and discusses a passive sensing approach, where users are passive actors and sensed without the need to carry anything, and an active sensing approach, using geofences and an emotional map that quantifies people’s feelings towards certain zones of a city. Chapter 4, Citizen Sensing, describes and discusses experiments that aim to sense the citizen. In particular, this chapter presents an approach to boredom detection in smartphones as well as a novel method for personality assessment, and knowledge representation and reasoning. Chapter 5 presents, details, and discusses KnowLedger, a MAS blockchain solution to store structured data, where a new protocol, entitled as Proof-of-Confidence (PoC), is used to award those who commit accurate and reliable data. To reduce the computational load of the entire solution KnowLedger includes a novel multi-chain architecture. Chapter 6, the last chapter of this thesis, provides an in-depth analysis of the obtained results, presenting the conceived archetype, SafeCity, which aggregates multiple solution specimens. It also presents fundamental considerations regarding the research hypothesis and outlines further research directions. Quantitative results, in the form of scientific publications, participation and organization of scientific events, lectures, invited talks, and supervision of students, are also described. 33
Chapter 2 City Sensing Cities, to become smart, must evolve technologically, must implement systems and techniques to enhance data collection and knowledge creation, and, last but not the least, must create means for their citizens to become active actors of the city’s ecosystem. With road safety as background, cities must promote new measures to guarantee the safety of their citizens in order to decrease accidents and injuries. The way to address such points is not monolithic. Instead, it should be grounded on multiple contributions that, when summed, allow people to have available a set of information that may help increase their quality-of-life. 2.1 Rationale An important goal of this research work consists of sensing the city in itself and on conceiving methods to extract knowledge from the city’s environment. Such knowledge may then be shared with VRUs so that they become aware of their surroundings and may adapt their behavior accordingly. Obviously, many distinct parameters can be sensed and modeled, depending on the underlying domain. This research work focused on two main features: traffic flow forecasting and environmental sustainability. The first aims to create models that are able to accurately forecast how the traffic flow will stand in future hours. The second focuses on forecasting the UV index. Forecasts are then used to provide actionable information to VRUs, allowing them to avoid streets and zones with high traffic as well as to adapt their behavior upon dangerous UV index values. To achieve the proposed goals, state of the art RNNs based-models were designed, conceived, tuned, and evaluated. In particular, several candidate LSTMs models were experimented. It should not be forgotten that data are mandatory. Hence, relevant attention was given to the development of an agent-based system responsible for collecting data from a city’s environment, as detailed in subsequent lines. 34
CHAPTER 2. CITY SENSING Considering the strong ML background of this research work, all ML-based tasks followed the Cross- Industry Standard Process for Data Mining (CRISP-DM) methodology. This methodology provides a structured approach for planning and executing a ML project, being a robust, well-proven, and widely used methodology. Figure 2.1 details the methodology’s pipeline, starting from business and data understanding, followed by data preparation, modeling, evaluation, and deployment of the best candidate model. This iterative process allows tasks to be performed in a different order, allowing one to backtrack to previous tasks and repeat actions when required. Business Understanding Data Understanding Data Preparation Modeling Evaluation Deployment Determine Business Goals Assess Situation Determine Data Mining Goals Produce Project Plan Collect Initial Data Describe Data Explore Data Verify Data Quality Select Data Clean Data Construct Data Integrate Data Format Data Select Modeling Technique Generate Test Design Build Model Assess Model Evaluate Results Review Process Determine Next Steps Plan Deployment Plan Monitoring & Maintenance Produce Final Report Review project Figure 2.1: CRISP-DM methodology for ML projects. Adapted from crisp-dm.eu. 2.2 A Conceptual Architecture for the Internet of People The IoP aims to complement the IoT by considering people as active, reactive, and proactive actors of the city’s ecosystem [25]. However, being in its infancy, the foundations on where the IoP rests are not yet well established. To help strengthen the IoP, this research work proposes a set of properties that should be seen as relevant when conceiving IoP-based environments: •Interoperability: ensuring proper communication between all elements of the IoP is an essential feature. A possible definition of interoperability corresponds to the ability of heterogeneous systems to exchange information transparently [40]. It assumes the use of open and well-defined standards and protocols, rather than having each manufacturers using proprietary technologies; •Citizen Sensor: the exponential use of smartphones and wearable devices, which have exceptional sensing capabilities, empowers the citizen sensor. This enables citizens to sense themselves, 35
CHAPTER 2. CITY SENSING others, and the environment where they stand, allowing the creation of knowledge from extended and deeper sets of data [41]; •Ambient Intelligence: with devices becoming smaller, integrated, and autonomous, they tend to go unnoticed. One should take advantage of such devices to create intelligent environments, allowing the conception of truly Smart Cities [63]. More properties to have a secure, powerful, and open IoP may be set as follows: •Intelligence,Analytics, and Dashboards:IoP systems are expected to be able to gather important insights and depict it using front-ends, allowing the creation of user awareness; •Cloud Platforms: due to the lower computational power of wearable devices, it should be possible to communicate with centralized platforms in case they require on-demand access to services, storage, or reporting, among others; •Device Authentication,Privacy, and Security: privacy and security of things and people is a major issue, ranging from the collection of information to its exposure. Sensors, actuators, and other devices typically tend to delegate their authentication to reduce their exposure [143]; •Transparency,Monitoring, and Auditing: communication among things and people should follow open and robust standards and protocols for higher transparency. Users should be able to define their privacy policies and to monitor how their data are being used [143]; •Scalability,High-Availability, and Efficiency: platforms should be scalable and as flawless as possible. Possibilities such as the use of asynchronous communication or MAS are interesting solutions to support scalability, availability, and fault tolerance [144]. Examples of IoT architectures have already been proposed in the literature [23,81,145]. However, when the subject matter is the IoP, there is a clear shortage of proposals. Hence, this research work conceptualized a high-level architecture for the IoP that is compliant with the properties defined before. Such architecture, as depicted in Figure 2.2a, consists of three layers. One, the Backend, should ideally be built on a cloud platform for scalability and availability factors. It should also contain a set of modules, including (1) an Intelligence module responsible for providing the platform with reasoning capabilities; (2) an Analytics and Dashboarding module focused on the analysis and production of accessible information for people and entities; (3) an Authentication and Control module responsible for protecting and securing the platform; and (4) a Communication module, the only entry point to the backend [25]. On a second layer, entitled as Ambient Sensing, one may find the actors of the platform, with VRUs in the form of citizen sensors. It is in this middle layer that the environment is felt, with the elements ideally equipped with three distinct modules, i.e., (1) a Sensing module, responsible for the use of sensors and techniques to sense and understand the environment and the others; (2) an Intelligence module, which intends to work on the data gathered by the first module and employ models for Affective Computing or 36
CHAPTER 2. CITY SENSING •𝛾𝑡−1, …, 𝛾𝑡−𝑝are the previous 𝑝values of the time series 𝑦(and form the auto-regression terms); •Φ1, …, Φ𝑝are coefficients to be determined by fitting the model; •𝑎𝑡, …, 𝑎𝑡−𝑞is a zero mean white noise process (and forms the moving average terms); •Θ𝑡, …, Θ𝑡−𝑞are coefficients to be determined by fitting the model. ARIMAX is considered an ARIMA extension to a multi-variable problem, i.e: 𝜙(𝐿)(1−𝐿)𝑑𝑌𝑡=𝜃(𝐿)𝜀𝑡(2.2) The expression 𝜙(𝐿)represents the auto-regressive polynomial 1+𝜙1𝐿+ · · · + 𝜙𝑞𝐿𝑞,𝜃(𝐿)the moving average polynomial 1−𝜃1𝐿−𝜃2𝐿2− · · · −𝜃𝑝𝐿𝑝and 𝐿the lag operator. ARIMAX(𝑝,𝑑,𝑞)extends ARIMA(𝑝,𝑑,𝑞)equation, resulting in the following formulation: Φ(𝐿)(1−𝐿)𝑑𝑌𝑡=𝜃(𝐿)𝑋𝑡+𝜃(𝐿)𝜀𝑡(2.3) 𝑋𝑡is the exogenous variable at time 𝑡. This model is adequate to forecast a stationary phenomenon with additional multi-variate data with context. ARIMA has been implemented on many domains such as temperature and pollution prediction [146] as well as short-term traffic flow forecasting [151]. On the same note, ARIMAX has been applied in scenarios where there is the need to use a multi-variate forecasting model. Regarding traffic flow forecasting, a comparison between ARIMA and ARIMAX is depicted in [152]. The obtained results demonstrate the better performance of ARIMAX and the use of additional contextual variables to achieve better forecasting accuracy [45]. Recent times came with very promising results in regard to the use of RNNs [6,8,45]. As opposed to classical ANNs,RNNs allow information to persist due to its recurrence and chain-like nature. The promise of RNNs, and LSTMs in particular, is that the temporal dependence and contextual information in the input data can be learned. LSTMs were introduced in 1997, by Hochreiter and Schmidhuber, but many more contributed to current LSTMs [153,154]. LSTMs are a type of RNNs capable of learning long and shortterm temporal dependencies. LSTMs computational units are called memory cells and have cell state. In addition, unlike typical RNNs, each memory cell of LSTMs contains additional neural network layers interacting with each other. These layers, or gates, give LSTMs the ability to further govern the information flow. Gates are composed of a sigmoid neural network layer, which specifies how much information the cell wants to forget (𝑓𝑡), input (𝑖𝑡) or output (𝑜𝑡) at a timestep 𝑡, and a point-wise multiplication operation over the cell state: • The forget gate, 𝑓𝑡, is the first gate inside the memory cell and decides which information the cell should discard from the cell state; • The input gate, 𝑖𝑡, decides which values to add to the cell state; 43
CHAPTER 2. CITY SENSING • The output gate, 𝑜𝑡, decides what to output based on the input and the cell state. Due to its characteristics, LSTMs have achieved important results in sequence problems such as text classification [155,156], music generation [157,158], handwriting recognition [159,160], or speech recognition [161,162], just to name a few. Traffic forecasting is yet another domain where LSTMs have been applied with some success [148,163,164]. 2.4.1.2 The Literature Recent studies have emerged where LSTMs are used for traffic flow forecasting. However, it is possible to verify that many exhibit flaws and leave untreated several important aspects of LSTMs. For instance, in [148], the authors conceived two distinct RNNs models for short-term traffic flow forecasting over the PeMS dataset, an open dataset describing the occupancy rate of several car lanes at the San Francisco bay area. Their experiments were based on an input sequence of six timesteps of five minutes each (thirty minutes) to predict the traffic flow for the next five minutes (single-step). No experimentation was performed in order to find the optimized values for any of the time parameters. No reference is made about the update pattern of the internal state of a memory cell. In [163], the PeMS dataset was again used to develop LSTMs for short-term traffic flow forecasting. The focus is again to develop a single-step model. However, several figures depict predictions for a time window far superior (one day) without any explanation on the method that was used to evaluate this multistep model. On the other hand, the authors clarify the features provided as input to the model. The authors opted to tune the number of memory cells of each layer and the size of the input layer. In regard to this last parameter, it is expected that the authors are indeed referring to the input shape of the first layer. Hence, the authors are tuning the number of timesteps that make an input sequence. All values from one to twelve were tried, meaning, in the first case, a sequence with just one timestep (five minutes of data) and, in the last case, a sequence with twelve timesteps (one hour of data). In [164], the authors propose a deep stacked bidirectional LSTMs in order to consider both forward and backward dependencies in time series data. Their goal is to predict traffic speed using two distinct datasets, even though later the authors claim that only one was used to evaluate the model. To fully capture the spatial dimension of the problem, and since the dataset contains observations of multiple roads, the authors opted to develop a multi-variate, multi-road model receiving, as input, multiple observations from different roads at the same timestep. Each input sequence is composed of ten timesteps of five minutes, with a prediction being provided for the subsequent timestep (single-step). The number of timesteps in the input sequence was set based on some experiments, using six, eight, ten, and twelve timesteps. The obtained results were very similar, which can be explained by the fact that all attempted values are also very close. Indeed, it would be interesting to know how would the model behave with higher input timesteps that could represent, for example, an entire day instead of a few tens of minutes. No reference is made about the update pattern of the cell state. 44
CHAPTER 2. CITY SENSING In [165], the authors left aside traffic and focused on electric load forecasting using a uni-variate dataset collected by themselves. Interestingly, the authors of this work clearly describe the multi-step forecasting concept, having used a forecasting horizon of ninety-six timesteps. Such a long forecasting horizon directly affects the accuracy of the model. Nonetheless, the authors found that LSTMs still outperformed traditional forecasting methods, such as Seasonal ARIMA. On the other hand, input sequences were composed of ten days of timesteps. No details were provided regarding how this value was found. Other studies focused on different deep learning models for time series forecasting. Indeed, new trends are emerging regarding the use of CNNs [166–168] and attention mechanisms [169,170]. In [166], the authors focused on deep learning-based techniques, in particular RNNs and CNNs, for day-ahead multistep load forecasting in commercial buildings, comparing the obtained results with ARIMAX. The gated 24-h CNNs based model was the one achieving the best results, improving ARIMAX’s accuracy by 22.6%. On the other hand, in [168], the authors integrated, in a platform called DeepSense, both CNNs and RNNs.CNNs were responsible for learning intra-interval interactions, with the intra-interval representations along time being inputted to the RNNs. In [167] the authors proposed a deep learning fault detection approach based on CNNs, with the goal being to diagnose anomalies in the output of wind turbine systems. Time series data were converted as 2d images and fed to the conceived CNNs, with deeper CNNs outperforming shallow ones. On the other hand, attention mechanisms, initially applied to machine translation [171], have been growing in popularity for time series forecasting. Indeed, in [170] the authors propose a Transformer that is solely based on attention mechanisms, discarding recurrence and convolutions. Such mechanisms allow models to selectively focus on some parts of the input data, which may be important when handling long input sequences. For instance, in [169], convolutional attention mechanisms based on the temporal output of CNNs were used to conceive a network that is able to convert variable-length time to a fixed-length low-dimensional time series representation [45]. 2.4.2 Exploring spatial-temporal dependencies in time series Traffic flow forecasting is a stochastic, non-linear time series problem, where space and time are of the utmost importance. For instance, no two countries are the same in regard to traffic dynamics. Even inside a country, cities and roads may have significantly different dynamics. Hence, it becomes extremely difficult, not to say unfeasible, to deploy a model to predict the traffic of several roads of a specific city when the model was trained on data from California roads, for example. To deploy accurate solutions that make realtime predictions, models require information on the space they are working. Hence, possible solutions would include the conception of road-specific models or the categorization of roads that share similar dynamics. Another possibility, even though computationally heavier, would be to create a multi-variate, multi-road model receiving, as input, multiple observations from different roads at the same timestep. In typical MLPs, when tuning the network, the goal is to find the best set of hyperparameters that provide the best accuracy. It is usual to find models that have been tuned in regard to their depth, the number of neurons, the learning rate used by the optimizer, or the activation function. However, in time 45
CHAPTER 2. CITY SENSING series problems, special attention should be given to all hyperparameters that are related to time. Tuning such hyperparameters assumes, as demonstrated by our experiments, an increased importance in a model’s accuracy and performance. There are, essentially, two main time hyperparameters to consider. The first is the number of timesteps that compose an input sequence. This assumes critical importance when performing Backpropagation Through Time (BPTT), a gradient-based technique that unfolds a RNNs in time to find the gradient of the cost, allowing LSTMs to learn from input sequences of timesteps. Let us consider, for example, an hourly dataset: if it is defined that each input sequence is composed of twelve timesteps, it means that each input sequence will correspond to twelve hours. If we set this value to twenty-four, then it will correspond to an entire day being used when computing. Longer input sequences were problematic for classical RNNs mainly due to the vanishing and the exploding gradient problems. LSTMs, on the other hand, are able to handle longer sequences with success. Alternatively, it is possible to use a truncated version of BPTT, which limits the number of used timesteps when finding the gradient of the cost. A second hyperparameter that may influence the model’s accuracy is related to the reset frequency of the cell state. Indeed, memory cells are stateful. However, different libraries handle these states differently. For instance, by default, Keras assumes that internal states are reset after each batch. If one aims to maintain state between batches, one must explicitly define such behavior. Usually, such behavior is useful when it is assumed that information from past sequences may be useful for future sequences. Hence, some logic should be applied so that the model may understand patterns between input sequences and how they relate to each other. There is no obvious rule of thumb but some experimentation may be performed to find a tuned value for the problem, and data, in hands [45]. Finally, it should be noted that the goal of any model is to provide accurate and reliable forecasts. In time series problems, the goal is to forecast what will happen in a future time. Hence, models could be conceived to be single-step, i.e., provide a single forecast for the next immediate timestep, or multi-step, i.e., provide a set of forecasts for several future timesteps. Using the hourly dataset example, a single-step model that receives twelve input timesteps will give a forecast for the thirteenth timestep. A multi-step model would give forecasts for the thirteenth, fourteenth, and fifteenth timesteps, for example. If single-step models are fairly easy to conceive and evaluate, multi-step models are, on the other hand, harder. In essence, there are two main options to consider when conceiving multi-step models. The first is to have as many neurons in the output layer of the model as timesteps to forecast (Multi-Step Vector-Output). Hence, if one aims to forecast three future timesteps the model would have three output neurons. The second option would be to conceive a single-step model and recursively call it for as many future timesteps as one aims to forecast (Recursive Multi-Step). Again, as an example, let us consider the hourly dataset and an input sequence of twelve timesteps. First, we would conceive the model as single-step, i.e., the model would receive twelve hours as input and would output the thirteenth hour. Then, we would evaluate its performance, i.e., how accurate the model is in forecasting the thirteenth timestep. We would then push the forecast value of the thirteenth timestep to the input sequence, remove the oldest timestep (to ensure that the input sequence consists of just twelve timesteps) and give the updated input sequence to the model to get the forecast 46
CHAPTER 2. CITY SENSING of the fourteenth timestep. We would keep repeating this process until the forecasting horizon is reached. This is what we call a blind prediction using a Recursive Multi-Step model. Obviously, this strategy suffers from the accumulation of errors with higher forecasting horizons [165]. However, there is no other valid way to evaluate such a model since the only way to know multiple future values is by using forecasts of the future itself. Literature is evasive in regard to the used methodology for forecasting. Nonetheless, as we show in the next sections, even though Multi-Step Vector-Output models are easier to conceive and evaluate, Recursive Multi-Step models perform better, both in terms of forecast accuracy and computational performance [45]. 2.4.3 Data Preparation and Pre-processing Data used in this study was made available by The Collector, having the features depicted in Table 2.2 and Table 2.3, i.e., weather and traffic flow features, respectively. Both datasets included observations from 24th July 2018 to 30th April 2019, in twenty minutes intervals. In the traffic flow dataset, as feature engineering, two more features were created: •speed_diff feature, which corresponds to the difference between the speed, in km/h, that is expected under ideal conditions on a road and the speed, in km/h, that is being currently observed on that same road; •time_diff feature, which corresponds to the difference between the travel time that is expected under ideal conditions on the road and the travel time that is being currently observed on that same road, in seconds. The speed_diff feature will be the one used to quantify traffic. High speed_diff values mean that one is going much slower than what would be expected at that road, while low values mean that one is going almost at the ideal speed. A speed_diff of zero means no traffic for that road while a value of, for example, 40 km/h means that one is going 40 km/h slower than expected. Then, to prepare the datasets, a specific road of the city of Braga was selected, with all other cities and roads being filtered out. The next step was to remove all static and non-informative features, such as the id,city_type,seq_num,latitude,longitude, and the functional_road_class, among others. The time_diff,free_flow, and current_speed features, which are highly correlated with the speed_diff, were also filtered out. Regarding the weather dataset, the only considered features were, besides the creation_date and city_name, the temperature and precipitation. For both datasets, six new temporal and contextual features were created based on the creation_date of each observation. The year,month,day,week_day,hour, and minutes were the created features. The minutes feature was further normalized to have one of three possible values: 0, 20 or 40. Hence, all observations with minutes between [0,20[were normalized to belong to the 0 split, all that were between [20,40[belong to the 20 split and all those between [40,60[belong to the 40 split. Having now consistent dates, a date-time index was created. It became now possible to join both datasets by 47
CHAPTER 2. CITY SENSING city_name and index. By the end of this step, we had a dataset, in ascending order by index, with five features, i.e., the speed_diff,temperature,precipitation,week_day, and hour (Table 2.5) [45]. Table 2.5: Features present in the dataset used for traffic flow forecasting. # Feature Observation Example 0timestep index 2019-04-23 17:40 1speed_diff 32 2temperature 10 3precipitation 0 4week_day 1 5hour 17 No missing values were present. However, due to API limitations or to the fact that The Collector was down, there are missing timesteps. In a time series, missing timesteps may lead to the creation of incorrect patterns in input sequences. Consider, for example, the situation where a sequence contains observations for the fourth, fifth, and sixth hours of a day and then, due to the nonexistence of observations, it is followed by the fourteenth and fifteenth hours of that same day. This sequence would not describe the traffic pattern of a road. Different approaches may be followed to solve this situation. The approach followed in this work was to first include all missing timesteps with NaN, which means ”Not a Number”. After performing this operation, all timesteps, from July until April, were present in the dataset in twenty minutes intervals. Missing values, previously filled with NaN, were interpolated when the amount of consecutive missing observations corresponded to less than six hours for weather features and less than ten hours for traffic features. Weather features (temperature and precipitation) were linearly interpolated. On the other hand, speed_diff was computed based on the mean value of that same timestep at the three previous weeks. The dataset was iterated, observation per observation, from the oldest to the newest. In the case there was no information about the three previous weeks, the subsequent three weeks were the ones used. In the case of timestep gaps longer than ten hours, the entire day would be removed. Algorithm 2.1 describes, using pseudocode, the method that was developed for the computation of missing timesteps. Considering that LSTMs work internally with the Hyperbolic Tangent (tanh), all features were normalized to fit into the interval [−1,1], i.e.: 𝑥𝑖−min(𝑥) max(𝑥) − min(𝑥)(2.4) Finally, the dataset was grouped by hour. The final multi-variate dataset contains 5050 timesteps, or observations, with a shape of (5050, 5). However, it was still not ready to be used by LSTMs networks. In order to create such networks one is required to set the problem as a supervised one, with inputs and corresponding labels. Hence, data were divided into smaller sequences, with its length depending on the number of input timesteps to be used. The label of each new sequence was the next immediate timestep, or a sequence of timesteps, depending if the model was to be Single-Step and Recursive Multi-Step, or Multi-Step Vector-Output, respectively (Algorithm 2.2). 48
CHAPTER 2. CITY SENSING Algorithm 2.1 Computation of missing timesteps. dataset.resample(’20min’) dataset[’temperature’, ’precipitation’].interpolate(method=’linear’, limit_direction=’forward’, limit=’6h’) initialize consequent_missing_obs for i, row ∈enumerate(dataset, 0) do if row[’speed_diff’] == NaN and consequent_missing_obs <10h then increment consequent_missing_obs if i−(3 ×one_week) >0then value_1w_before ⇐dataset[i −one_week] value_2w_before ⇐dataset[i −one_week ×2] value_3w_before ⇐dataset[i −one_week ×3] row[’speed_diff’] ⇐mean(value_1w_before, value_2w_before, value_3w_before) else value_1w_after ⇐dataset[i +one_week] value_2w_after ⇐dataset[i +one_week ×2] value_3w_after ⇐dataset[i +one_week ×3] row[’speed_diff’] ⇐mean(value_1w_after, value_2w_after, value_3w_after) end if else if row[’speed_diff’] ≠NaN then reset consequent_missing_obs end if end for To evaluate the effectiveness of the candidate models, two error metrics were used. The first one corresponds the Root Mean Squared Error (RMSE), allowing one to penalize outliers and easily interpret the obtained results since they are in the same unit of the feature that is being predicted by the model. Its formula is as follows: RMSE =sÍ𝑛 𝑖=1(𝑦𝑖−b𝑦𝑖)2 𝑛(2.5) The second error metric corresponds to the Mean Absolute Error (MAE). It was mainly used to complement and strengthen the confidence on the obtained values. Its formulas is as follows: Algorithm 2.2 From an unsupervised to a supervised problem. Require: dataset, timesteps, multi_steps Ensure: X, y X, y = list(), list() while i∈range(len(dataset) −(timesteps +multi_steps)) do input_index ⇐i+timesteps label_index ⇐input_index +multi_steps X.append(dataset[i:input_index, :]) y.append(dataset[input_index:label_index, speed_diff]) end while 49
CHAPTER 2. CITY SENSING MAE = 1 𝑛 𝑛 Õ 𝑖=1 |𝑦𝑖−b𝑦𝑖|(2.6) All the developed models were evaluated in regard to the mentioned metrics. A time series crossvalidator was also used to provide train/test indices. In this case, the 𝑘𝑡ℎ split returns the first 𝑘folds as train set and the (𝑘+1)𝑡ℎ fold as test set. Unlike standard cross-validation methods, successive training sets are supersets of those that came before. Each training set was further split into training and validation sets in a ratio of 9:1. A forecast function was also created to predict three days of the last test set (72 timesteps). The predicted value is compared with the real value in order to compute both error metrics. In the case of Recursive Multi-Step models, blind forecasting pushes prediction values to the input sequence to forecast subsequent timesteps [45]. 2.4.4 Experiments The main goal of this research study was to develop and tune the best possible LSTMs for traffic flow forecasting while addressing important pitfalls. All candidate models were conceived as multi-step, i.e., all models aim to forecast twelve consecutive hours. Python, version 3.6, was the used programming language for data preparation and pre-processing as well as for model development and evaluation. Pandas, NumPy, scikit-learn, matplotlib, and statsmodels were the used libraries. Tensorflow v1.12.0 was the machine learning library used to conceive the deep learning models. tf.keras, TensorFlow’s implementation of the Keras API specification, was also used. For increased performance, and to fit the models in reasonable times, Tesla T4 GPUs were used as well as an optimized version of LSTMs using CuDNN (CudnnLSTM), NVIDIA’s deep neural network library of primitives for deep neural networks. It is worth mentioning that all this hardware was made available by Google’s Colaboratory. Due to the random initialization of LSTMs’ weights, multiple repetitions of each combination of hyperparameters were performed on incremental sets of data, taking the mean RMSE and MAE to verify the model’s quality. Several experiments were performed to find the best set of hyperparameters for the final model. An experiment was also set where ARIMA models are deployed, evaluated, and later compared with LSTMs. Algorithm 2.3 details the generic function that was written for the conception and compilation of the LSTMs. This function is used in all experiments that use LSTMs, with the inputs of the function defining the model’s structure and time frames [45]. 2.4.4.1 ARIMA and ARIMAX When compared to LSTMs,ARIMA and ARIMAX are considered more traditional approaches to time series forecasting. The literature shows several examples of their usage. Therefore, ARIMA and ARIMAX models shall be used as benchmarks for the developed LSTMs. Hence, using the collected data, models were 50
CHAPTER 2. CITY SENSING Algorithm 2.3 LSTM model’s conception and compilation. Require: timesteps, multisteps, features, h_layers, h_neurons, activation, dropout_rate, deep_dense Ensure: Sequential LSTM Model model ⇐Sequential() while i∈range(h_layers) do if i== 0then if i+1 == h_layers then model.add(LSTM(h_neurons, return_seq=False, input_shape=(timesteps, features))) else model.add(LSTM(h_neurons/2, return_seq=True, input_shape=(timesteps, features))) model.add(Dropout(dropout_rate)) end if else if i+1 == h_layers then model.add(LSTM(h_neurons×2, return_seq=False)) else model.add(LSTM(h_neurons, return_seq=True)) model.add(Dropout(dropout_rate)) end if end while model.add(Dense(h_neurons, activation=activation)) model.add(Dropout(dropout_rate)) if deep_dense then model.add(Dense(h_neurons/2, activation=activation)) model.add(Dropout(dropout_rate)) end if model.add(Dense(multisteps)) model.compile(loss=rmse, optimizer=Adam(), metrics=[mae, rmse]) trained in order to mimic the conditions in which LSTMs were trained, i.e., using ARIMA for uni-variate and ARIMAX for multi-variate problems. The experiments made with the ARIMA model used a grid search approach to fine tune the (𝑝,𝑑,𝑞) parameters. For a better comparison between ARIMA and LSTMs, the 𝑝parameter was based on large windows ([12,8]), with LSTMs models achieving even higher windows. The remaining parameters were computed from the range [0,3]. An obvious limitation of this approach is the unfeasibility of training models with some specific parameters due to internal errors of the ARIMA algorithm. These errors are essentially related with stationary data. ARIMAX followed the same approach, however contextual data were added through the use of exogenous variables. The fine tune of the (𝑝,𝑑,𝑞)parameters was the same as with ARIMA. The features introduced as contextual data included the precipitation and weekday, for each timestep. In order to tackle multi-step predictions, a forecasting method was used, which allows to directly forecast multiple instances from the last point in the train dataset. This is consistent with the blind multi-step forecasting approach. For a multi-step approach incorporating real observations, the model needs to be retrained after each dataset change. The time used to train an ARIMA or ARIMAX model is usually faster than LSTMs, but in the case of forecasting one step ahead with real observations, the need for retrain at each 51
CHAPTER 2. CITY SENSING timestep, and the number of experiments being performed, made the ARIMA and ARIMAX slower than the worst performing LSTMs. For simplicity, only blind multi-step forecasting models were considered [45]. 2.4.4.2 Recursive Multi-Step vs Multi-Step Vector Output LSTMs The goal of this experiment was to compare the performance, both computationally and in terms of accuracy, of two distinct multi-step approaches. It soon became obvious that the Multi-Step Vector Output model would require a more complex architecture. That came, however, with a significantly higher computational and training time cost. Therefore, for this experiment, only uni-variate models were considered. Both models receive input sequences of one feature, i.e., speed_diff, and provide speed_diff forecasts for the next 12 hours. Random search was used to reduce the hyperparameters’ configuration space. Recursive Multi-Step LSTMs were conceived and tuned in regard to a set of hyperparameters. As explained before, such models predict the next immediate timestep, being then called recursively twelve times. RMSE and MAE values are gathered both for blind and non-blind predictions. Non-blind predictions use real values when iterating recursively. Obviously, non-blind predictions produce a better result than blind ones since this last approach suffers from the accumulation of errors with higher forecasting horizons. This serves the purpose of showing that misconceptions may lead researchers to present models that have been inappropriately evaluated. Nonetheless, blind predictions are the ones to be considered. Table 2.6 describes the hyperparameters searching space considered for the candidate models. Table 2.6: Recursive Multi-Step uni-variate hyperparameters’ searching space. Parameter Searched Values Rationale Epochs [200, 300, 500] - Timesteps [12, 24, 48, 96] Input of 0.5 to 4 days Batch size [24, 168, 252, 336, 672] 1 day to 4 weeks LSTM layers [3, 4, 5] Number of LSTM layers Dense Layers 1 Number of dense layers Dense Activation [ReLU, tanh] Activation function Neurons [32, 64, 128] For dense and LSTM layers Dropout rate [0.0, 0.2, 0.5] For dense and LSTM layers Learning rate Tuned via callback Keras callback Multisteps 12 12 hours Features speed_diff Uni-variate CV Splits 3 Time series cross-validator As soon as the first Multi-Step Vector Output candidate model started its training, it became obvious that, computationally, it would be much expensive and it would take a considerable amount of time to go through all hyperparameters’ possibilities. Therefore, a smaller hyperparameters searching space was considered (Table 2.7). Intuition and random search helped reduce the number of fits performed and the amount of time it took to gather all results. 52
CHAPTER 2. CITY SENSING Figure 2.7: Six random multi-step predictions of the best Recursive Multi-Step Multi-Variate LSTM model (#53). Comparison of real values vs predicted ones using blind forecasting vs predicted ones using known observations. ARIMA and ARIMAX presented results that are two times worse than the best LSTMs. In addition, the fit frequency of ARIMA-based models is significantly higher when compared to LSTMs, which may be problematic in open data streams scenarios. All this is in agreement with what the literature has been presenting, confirming that these statistical-based models have now been superseded by deep learning ones. Table 2.12 summarizes the achieved results. Table 2.12: Summary results for the best model for each approach. Model RMSE MAE Recursive Multi-Step Multi-Variate 2.907 1.346 Recursive Multi-Step Uni-Variate 3.496 1.567 Multi-Step Vector Output Uni-Variate 5.040 1.846 ARIMAX (Multi-Variate) 6.110 4.918 ARIMA (Uni-Variate) 6.336 5.088 As expected, the time frames impact the model’s accuracy. The obtained results show that the number of input timesteps, as well as the batch size, may affect accuracy significantly. It was interesting to note that the presence of more input features led to a decrease in the number of input timesteps required by the model. While the best uni-variate models required four days of input, the multi-variate ones require just a single day. The batch size required by multi-variate models is also substantially lower when compared to uni-variate ones. As direct answers to the elicited research questions, it can be said that (RQ2.1) LSTMs have significantly better forecasting accuracy than ARIMA-based models; (RQ2.2) LSTMs are able to accurately forecast several future timesteps; (RQ2.3) it has been demonstrated that recursive multi-step LSTMs 59
CHAPTER 2. CITY SENSING have better accuracy than multi-step vector output ones, with these last ones requiring a more complex and deeper architecture, which, in turn, increases training times; and (RQ2.4) the addition of more input features, namely the day of the week and the hour of the day, allowed LSTMs to behave 20% better when compared to the uni-variate ones. 2.5 UV Index Forecasting Recent times came with an increased importance being given to sustainability, in several domains. In fact, sustainability refers to the assurance of steadiness, viability, and efficiency in any domain, i.e., the ability to meet present needs without compromising future generations [37]. The three main pillars of sustainability are the social, economic, and environmental ones [172], with many stakeholders being focused in implementing sustainable transportation systems [173,174], smart agriculture [175,176], sustainable houses [177], and sustainable energy recovery from municipal solid wastes [178], just to name a few. The work here presented focuses on environmental sustainability. In particular, it focuses on forecasting the UV index to provide actionable information to people, i.e., having access to such forecasts allow VRUs to adapt their behavior on the road, avoiding solar exposure in dangerous days or by taking other protective measures [179]. In fact, a significant increase in the incidence of skin cancers has been observed since the early 1970s, being strongly correlated to sun exposure and the thought that a tan is desirable [180]. The most effective strategy to control skin cancer is to avoid sun exposure during peak UV levels [179]. Other primary prevention strategies include the use of protective clothing, sunscreen protection, and avoiding artificial tanning devices [181]. In fact, it is believed that four out of five skin cancer cases could be prevented since UV damage is highly avoidable [182]. The sun emits several types of radiation that are characterized by their wavelength. Such emissions include UV, visible light, and heat, among others. UV covers the wavelength range between 100–400 nm, being split into three bands: UVA in the range 315-400 nm, UVB in the range 280-315 nm, and UVC in the range 100-280 nm. UV radiation reaching the Earth’s surface is almost entirely composed of UVA radiation, since UVC is fully absorbed when passing through the atmosphere and approximately 90% of all UVB radiation suffers the same fate. UVA can penetrate into tissue, being less biologically damaging than UVB [180]. UV radiation levels are influenced by sun elevation, latitude, cloudiness, altitude, ozone levels, and ground reflection. Despite harmful at high concentrations, UV radiation is still essential to the humanity. For instance, small amounts of UV radiation are essential for the production of vitamin D, a key regulator in calcium and phosphate homeostasis [183]. UV radiation, under medical supervision, is also used to treat rickets, psoriasis, and eczema [180]. The UV index is a standard metric describing the magnitude of solar UV radiation reaching Earth’s surface at a particular time, at a given region [180]. It has been adopted and standardized by the WHO and the World Meteorological Organization. In its essence, the higher the index value, the greater the risk for damage. The UV index should be presented as a value rounded to the nearest integer, with values 60
CHAPTER 2. CITY SENSING between [0,2]describing low risk; between [3,5]describing moderate risk; between [6,7]start carrying some risk; between [8,11]being very dangerous to the human being; and values higher than 11 being of extreme danger (Figure 2.8). When cloudiness is variable, the UV index should be presented as a range of values. Forecasts not considering cloud effects should refer to themselves as ”clear sky” or ”cloud free” UV index forecasts [180]. Exposure Category UV index range Low ≤ 2 Moderate [3, 5] High [6, 7] Very High [8, 10] Extreme ≥ 11 Figure 2.8: UV index exposure categories. Colors are associated to each category. Adapted from [180]. Radiation levels differ throughout the day. However, most reports are focused on depicting the maximum UV radiation level on a given day, which occurs during the four-hour period around the solar noon [180]. Hence, this study makes use of data gathered by The Collector to conceive the best possible candidate model to forecast the maximum daily ”clear sky” UV index, for the next three days. State of the art LSTMs models are conceived, tuned, and evaluated, based on the results obtained from the traffic flow forecasting experiment, which allowed us to perceive the better performance of Recursive Multi-Step Multi-Variate networks. This study aims to give an answer to the following research question: RQ2.5. Are LSTMs networks capable of accurately forecast the maximum daily ”clear sky” UV index for multiple future timesteps? 2.5.1 State of the Art The literature depicts two main UV index forecasting methods: one based on solar total radiance and other environmental parameters, and another based on previous UV index values. The second method has been shown to produce better results, with the first being more suitable for epidemiological studies [184]. In this study, we are particularly interested in framing UV index forecasting as a time series problem, where one considers a series of past UV points ordered in time. UV index forecasting is essentially performed through means of static mathematical models. It is interesting to note that online platforms, such as Open Weather Maps or OpenUV, provide several days of UV index forecasts. However, many of them do not disclose how forecasts are performed and which features are used. On the other hand, scientific literature using ML or DL-based models is practically nonexistent. One example is the work of Deo et al. (2017), where the authors focused on short-term UV index forecasting (10 minutes) [185]. The authors employed an Extreme Machine Learning (EML) model based 61
CHAPTER 2. CITY SENSING on a shallow ANNs, using RMSE and MAE as evaluation metrics. The conceived model outperformed mathematical based ones [185]. A different study proposed a DL model to forecast UV index with the goal being to predict erythema formation in the human skin, which corresponds to skin redness due to the dilation of superficial capillaries [186]. The conceived model receives, as input, the temperature, cloudiness, insolation, and the UV index of the day before the one it aims to forecast. The used dataset contained records extracted from the National Aeronautics and Space Administration. Models achieved an overall accuracy of 66.8% of correct classifications [186]. In 2018, Purananunak et al. proposed an UV index monitoring, alert, and prediction system. To forecast future timesteps the authors employed a linear regression model using the Weka software. The conducted experiments were poorly explained, not describing how were the models evaluated, which metrics were used, and how the tuning was performed [187]. In 2017, Mei et al. (2017) proposed the use of smartphone cameras to measure UV radiation, developing a mobile application for such end [188]. The rationale is that sensors inside smartphone cameras are very sensitive to UV radiation. The authors conducted several experiments, under different conditions, evaluating the feasibility of using smartphones as UV sensors. In fact, results showed that the proposed procedure achieved an average 95% accuracy when compared to professional digital UV meter, being significantly better than UV sensors equipped on smartwatches. No forecasts were performed. 2.5.2 Data Preparation and Pre-processing Data used in this study were made available by The Collector, having the features depicted in Table 2.1, i.e., pollution features. Since only pollution data are used, from this point forward, forecasts are to be understood as ”clear sky” UV index forecasts [180]. The used dataset includes 16375 observations collected by three hard sensors from 24th July 2018 to 24th February 2020. Only observations with pollution_type as ”Ultraviolet” were considered. The case study focused on one Portuguese city. Observations from all other cities were discarded. Since at the same timestep several UV measures are made available by distinct sensors, data were grouped by creation_date to contain the mean UV value at each timestep. Data were further grouped, to contain the maximum UV value per day for the selected city. Features without any value assigned or always filled with the same value, such as the last_updated or data_precision ones, were removed. In fact, since the goal is to forecast the UV index using previous UV values as input, all features were removed except for the value and creation_date ones. Based on the latter, a feature engineering process allowed us to create a set of features including the year,month, and day for each observation. Being this a time series problem, one must be aware about the existence of missing timesteps. In the collected dataset, 102 timesteps were missing. Some of which corresponded to periods of roughly 1 month, between December 13th, 2018 to January 14th, 2019, and between March 7th, 2019 to April 9th, 2019. As discussed previously, missing timesteps are problematic. Hence, to fill the missing gaps, Open 62
CHAPTER 2. CITY SENSING 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 period 0 2 4 6 8 10 UV Index (a) Mean UV index per month. 2018-07 2018-08 2018-09 2018-10 2018-11 2018-12 2019-01 2019-02 2019-03 2019-04 2019-05 2019-06 2019-07 2019-08 2019-09 2019-10 2019-11 2019-12 2020-01 2020-02 period 0 2 4 6 8 10 UV Index (b) Max UV index per month. Figure 2.9: UV index values per month in the collected dataset. Weather Map’s Historical Ultraviolet API was used. By the end of this step, the dataset consisted of 581 daily timesteps. No missing values are present in the dataset. As explained in Section 2.4.3, since LSTMs work internally with the tanh activation function, all features were further normalized to fit into the interval [−1,1]. Figure 2.9 depicts the mean (Figure 2.9a) and max (Figure 2.9b)UV index values, per month, in the dataset. It is easily noticeable the existence of seasonality and cycles. Lower UV index values emerge during autumn and winter, with higher values appearing during spring and summer (data for the the northern hemisphere). Overall, the mean UV index is higher in July, but the peak value is usually found in June. Figure 2.10 depicts the maximum UV value, per day, of two months in 2019. Figure 2.10a shows a steady line of low values during January. On the other hand, during August the values are considerably higher and with greater amplitude, offering an increased risk to the population (Figure 2.10b). Two distinct datasets were created to achieve the goal of accurately forecast the UV index using previous UV values as input. Both contain 581 timesteps, varying only in the number of features. One dataset, the uni-variate, only contains the value of the UV index for each timestep (shape of (581, 1)). The second dataset, the multi-variate, also contains temporal information, i.e., the day and the month of the year 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 day 0 2 4 6 8 10 UV Index (a) UV index values for January, 2019. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 day 0 2 4 6 8 10 UV Index (b) UV index values for August, 2019. Figure 2.10: UV index values per day during two months of 2019 in the collected dataset. 63
CHAPTER 2. CITY SENSING (shape of (581, 3)) [189]. Algorithm 2.2 was used to set the problem as a supervised one, with inputs and corresponding labels. Recursive Multi-Step LSTMs were the ones considered since the goal is to forecast three days ahead and also because such multi-step architecture has already been shown to produce better results than others [45]. 2.5.3 Experiments To achieve the goal of forecasting the UV index for the next three days, we were required to develop and tune several candidate LSTMs. The effectiveness of the candidate models was evaluated using the RMSE and MAE error metrics. The predicted value is compared with the real value in order to compute both values. A time series cross-validator was also used to provide the train/test indices. Algorithm 2.3 details the generic function that was used to conceive and compile the DL models. Several experiments were conducted to find the best combination of hyperparameters for both univariate and multi-variate approaches. The first uses previous UV index values to recursively forecast the future value. The latter, besides the UV index value also uses the day and month, giving a stronger temporal context to the models. Table 2.13 describes the searched hyperparameter configuration, for both approaches. The Knime platform was used for data exploration. On the other hand, Python, version 3.7, was the used programming language for data exploration and preparation, and for model development and evaluation. Pandas, NumPy, scikit-learn, and matplotlib were the used libraries. Tensorflow v2.0.0 was used to implement the deep learning models. Tesla T4 GPUs were used as well as CUDNNLSTM layers for optimized performance in a GPU environment. Hardware was made available by Google’s Colaboratory. Table 2.13: Uni-variate vs multi-variate hyperparameters’ searching space for UV forecasting. Parameter Uni-Variate Multi-Variate Rationale Epochs [150, 300] [300, 500] - Timesteps [7, 14] [7, 14] Input of 1 to 2 weeks Batch size [16, 23] [16, 23] Batch of 2 to 3 weeks LSTM layers [3, 4] [3, 4] Number of LSTM layers Dense Layers 1 1 Number of dense layers Dense Activation [ReLU, tanh] [ReLU, tanh] Activation function Neurons [32, 64, 128] [32, 64, 128] For dense and LSTM layers Dropout rate [0.0, 0.5] [0.0, 0.5] For dense and LSTM layers Learning rate callback callback Keras callback Multisteps 3 3 3 days forecasts Features 1* 3** Used features CV Splits 3 3 Time series cross-validator * Used features: UV index **Used features: UV index,day, and month 64
CHAPTER 2. CITY SENSING 2.5.4 Results and Discussion The conducted experiments outputted similar results for both approaches. The best overall candidate model was a multi-variate one, with a RMSE of 0.306. This indicates that a stronger temporal context may lead to an overall decrease in error metrics. On the other hand, the best uni-variate models present a lower MAE than the best multi-variate ones, which implies that the multi-variate models output more stable forecasts (as RMSE penalizes outliers). Table 2.14 depicts the top-three results for each approach when forecasting three days. Table 2.14: Uni-variate vs multi-variate LSTMs top-three results for UV forecasting. # Timesteps Batch Layers Neurons Dropout Act. RMSE MAE Recursive Multi-Step Uni-Variate 116 7 16 4 64 0.5 tanh 0.325 0.236 108 7 16 3 128 0.5 tanh 0.349 0.271 8 7 16 3 64 0.5 tanh 0.354 0.260 Recursive Multi-Step Multi-Variate 31 14 16 3 64 0.0 tanh 0.306 0.249 125 14 16 3 64 0.0 relu 0.339 0.284 73 14 23 3 32 0.0 relu 0.340 0.275 Overall, the best uni-variate model had a RMSE of 0.325 and a MAE of 0.236. On the other hand, the best multi-variate one had a RMSE and MAE of 0.306 and 0.249, respectively. Since both metrics are in the same unit of measurement as the UV index, such error values testify the ability of these models to accurately predict the UV value for the next three days. Interestingly, multi-variate models required a higher number of input timesteps (14 days) when compared to uni-variate ones (7 days). Both approaches required batches of two weeks. All the best uni-variate models required the tanh as activation function. The best uni-variate model required a more complex architecture, of 4 hidden LSTMs layers, to achieve similar performances to the multi-variate ones, who required a shallow architecture. In addition, this shallow architecture ruled out the use of dropout, which was required by the best uni-variate models. On the other hand, the deeper architecture of the uni-variate LSTMs made them costly, in terms of time, to train. Figure 2.11 illustrates the architecture of the best multi-variate model. The obtained results show promising prospects for UV index forecasting, with the best candidate models being able to accurately forecast the UV index for the next three days using only previous UV index values and some temporal data (an error of 0.3 units of measure). As a direct answer to the elicited research question (RQ2.5), it can be said that deep LSTMs models are able to accurately forecast the maximum daily ”clear sky” UV index value for multiple future timesteps using a Recursive Multi-Step approach [189]. 65
CHAPTER 2. CITY SENSING Month Day of Month UV index UV index Input Layer 3 Hidden LSTM Layers (32 > 64 > 128 neurons) Output Layer 1 Hidden Dense Layer (64 neurons) Figure 2.11: Representative architecture of the best multi-variate model for clear-sky UV index forecasting. 2.6 Summary One important goal of this doctoral work (Task 3) focuses on sensing the city and conceiving methods to extract knowledge from the city’s ecosystem, which may then be shared with VRUs in order to make them more aware of their surroundings and adapt their behavior accordingly. It also aims to promote Smart Cities, i.e., give cities the ability to sense their environment, act on problematic situations, and provide actionable information to their citizens. The first step to enable City Sensing was to develop a MAS responsible for the entire data collection process and ML pipeline (Automated ML), based on the envision of an architecture for the IoP (Task 1). The MAS is remotely deployed in an Ubuntu 18.04 machine hosted at the University of Minho, being up and running since 24th July 2018. One software agent, The Collector, is a modular and configurable software agent that can, at any time, start collecting data for any city worldwide. It currently gathers data about the weather, pollution levels, traffic flow, and traffic incidents. Another software agent, the ML Architect, is responsible for using ML and DL models to provide accurate forecasts and predictions, following a publisher-subscriber pattern. It holds all non-mobile ML models and uses real-time data gathered by The Collector. Establishing the data collection process was a crucial step towards the conception of models to be used by the ML Architect. To conceive such models, state of the art LSTMs were designed, conceived, 66
CHAPTER 2. CITY SENSING tuned, and evaluated. Considering the strong ML background of this research work, CRISP-DM proved to be an effective methodology. To provide actionable information to VRUs, two main case studies were implemented. The first focused on forecasting the traffic flow status for the next twelve hours. With such information, VRUs can opt to avoid highly congested hours, which not only pose an increased risk of road injuries but also correspond to a scenario of higher atmospheric pollution given the number of vehicles on the road. This study also allowed us to understand and clarify the better performance of LSTMs when compared to statistical-based models, as well as their ability to accurately forecast future timesteps using a Recursive Multi-Step Multi-Variate approach. The second case study focused on forecasting the ”clear sky” UV index for the next three days. The goal is again to allow VRUs to have a better perception of the city’s environment and adapt their behavior in situations of increased risk. It must be noted that the most effective strategy to control skin cancer is to avoid sun exposure during peak UV radiation levels. Multiple experiments were conducted, using a wide combination of hyperparameters for all the candidate models. The best candidate model was able to forecast the UV index for the next three days with an error of just 0.3 units of measure. The research methodology being followed in this PhD work considered an initial Design phase where solutions’ specimens, i.e., the main Research Questions in Section 1.3.2, were defined based on the devised hypothesis. The work presented in this chapter is part of the Validation phase, which aims to validate the defined solutions’ specimens to prove the research hypothesis. In particular, the work here presented aims to give an answer to Research Question 1: Is a MAS able to autonomously capture city’s data and produce actionable knowledge from such sources? It can be said that it is viable to conceive a MAS to collect data about a city’s environment by taking advantage of several public APIs. In addition, ML and DL models can be trained and then used by software agents to provide forecasts and predictions to the community. The work performed in this chapter closes Task 1 and fulfills, by 50%, Task 3, which also encompasses Crowd Sensing, as described in the next chapter. The first C, from the 3-C, i.e., City,Crowd, and Citizen sensing, has now been addressed. The work presented in this chapter gave origin to multiple scientific papers ([8,16,25,45,189]) as well as to the participation in several scientific events. The work performed on the UV domain was also distinguished with the Best Application Paper award by the program committee of the 17th International Conference on Distributed Computing and Artificial Intelligence (DCAI’20), held in L’Aquila, Italy. To conclude, the work presented in this chapter was performed in collaboration with researchers from the ALGORITMI Centre, Braga, Portugal; the Polytechnic Institute of Porto, Felgueiras, Portugal; and the Department of Electrical and Systems Engineering, Universidad de Leon, Spain. 67
C h a p t e r 3 Crowd Sensing Smart Cities, to emerge as such, are required to sense and understand their environment. Such an environment comprises vehicles, infrastructures, the weather, pollution levels, and many others, including people. In fact, people are not only the city’s main stakeholders but also an active element of the city’s ecosystem. Hence, the ability to sense groups of people, here entitled as crowd sensing, assumes an increased importance for the development of truly Smart Cities, the rise of the IoP, and the emergence of new proposals to enhance road safety. 3.1 Rationale The research work presented in the next lines aims to sense people in order to gather insights at certain points of interest for VRUs. Such places can include pedestrians’ crossings, sidewalks, or busier roads, among others. More than tracking individuals, the goal is to sense large groups of people in an anonymized fashion. Crowd sensing approaches can be divided into two distinct groups: the first, passive sensing, aims to sense people without requiring them to do or carry anything, i.e., they are completely passive actors; the second, active sensing, requires people to install software or carry specific hardware in order to be sensed. Both have their advantages and disadvantages. Achieve passive sensing is more challenging but allows one to build artifacts that are able to sense everyone without requiring users to actively participate in the conceived solution. Active sensing, on the other hand, is easier to conceive and develop, but requires users to carry specific software/hardware artifacts that make them visible and recognizable. The next lines describe and analyze the conception of passive methods for crowd sensing, i.e., the ability to sense people without requiring them to do anything. On the other hand, a set of active sensing solutions are also described. While the former aims to sense people at specific points of interest for VRUs, the latter focuses on conceiving geofences and emotional maps for the benefit of VRUs. 68
CHAPTER 3. CROWD SENSING Listing 3.2: Crowd Sensing newSighting function. bool newSighting(const WiFiEventSoftAPModeProbeRequestReceived& evt){ String mac = macToString(evt.mac); long currTime = millis(); //start by the end as array is ordered - new sightings are at the end //break as soon as it finds the mac in the list for(int i = currIndex-1; i>=0; i--){ //if this mac has already been captured if(mac.equals(probeArray[i].mac)){ //check if enough time has passed //(sightingsInterval milliseconds since last sighting) if(currTime-probeArray[i].previousMillisDetected < sightingsInterval){ return false; } break; } } return true; } 8. stopHandlers() and restartHandlers(), responsible for stopping/starting the capture handlers and timers; 9. startTimer() and stopTimer(), which starts/stops a timer that decides when to push data to a cloud server (default value as 45 seconds); 10. printProbeArray(), to print the internal array with the captured probe requests (useful for debugging purposes); 11. macToString(const unsigned char* mac), that sets a MAC address to a string (Listing 3.3). Listing 3.3: Crowd Sensing macToString function. String macToString(const unsigned char* mac){ char buf[20]; snprintf(buf, sizeof(buf), ”%02x:%02x:%02x:%02x:%02x:%02x”,mac[0], mac[1], mac[2], mac ↩→[3], mac[4], mac[5]); return String(buf); } The two mandatory functions, setup() and loop(), make use of the auxiliary ones to achieve the goal of capture probe requests of client stations in the vicinity of the ESP board. Listing 3.4 depicts the setup() function responsible for setting the data rate in bits per second (baud) for serial data transmission; the Wi-Fi mode of the board as WIFI_AP_STA, meaning the board will work, simultaneously, as an AP and as a station; initialize the Firebase or MQTT connection; setup the timer for handling data collection and 75
CHAPTER 3. CROWD SENSING the transmission of information to the cloud server; and register the handlers that are called every time a connection/disconnection is made and every time a probe request is captured by the board [66]. Listing 3.4: Crowd Sensing sketch’s setup function. void setup() { Serial.begin(9600); //don't save WiFi configuration in flash - optional WiFi.persistent(false); //set up an access point WiFi.mode(WIFI_AP_STA); WiFi.softAP(AP_SSID, AP_PASSWORD); //connect to the network WiFi.begin(STATION_NETWORK, STATION_PASSWORD); if(WiFi.status() == WL_CONNECTED) { Serial.print(”Connected to ”); Serial.print(STATION_NETWORK); Serial.print(”; IP address: ”); Serial.println(WiFi.localIP()); isConnected = true; }else{ Serial.print(” Connection to ”); Serial.print(STATION_NETWORK); Serial.println(” failed! Board will only work as an AP......”); } //setup the MQTT/Firebase Connection if(useMqtt){ setupMqtt(); }else { setupFirebase(); } //setup timer os_timer_setfn(&theTimer, timerCallback, NULL); os_timer_arm(&theTimer, sendTimer, true); //callbacks stationConnectedHandler = WiFi.onSoftAPModeStationConnected(&onStationConnected); stationDisconnectedHandler = WiFi.onSoftAPModeStationDisconnected(&onStationDisconnected); probeRequestPrintHandler = WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint); probeRequestCaptureDataHandler = WiFi.onSoftAPModeProbeRequestReceived(& ↩→onProbeRequestCaptureData); Serial.print(”*** All setup has been made! ”); if(isConnected){ startTimer(); }else { Serial.println(”Timer is DISABLED! ***”); } } On the other hand, listing 3.5 depicts the loop() function that, if the board is connected to a computer, is capable of receiving additional user commands such as Stop/Restart,Count,Start/Stop_Timer and 76
CHAPTER 3. CROWD SENSING Clear, among others. This allows one to enforce additional behavior from the board, which, by default, starts with all handlers and services enabled [66]. Listing 3.5: Crowd Sensing sketch’s loop function. void loop() { if(Serial.available() > 0) { command = Serial.readString(); if(command.equalsIgnoreCase(CMD_RESTART)){ restartHandlers(); }else if(command.equalsIgnoreCase(CMD_STOP)){ stopHandlers(); }else if(command.equalsIgnoreCase(CMD_COUNT)){ Serial.println(currIndex); delay(1000); }else if(command.equalsIgnoreCase(CMD_PRINT)){ printProbeArray(); delay(1000); }else if(command.equalsIgnoreCase(CMD_CLEAR)){ clearData(); delay(1000); }else if(command.equalsIgnoreCase(CMD_SEND)){ sendDataCmd(); delay(1000); }else if(command.equalsIgnoreCase(CMD_START_TIMER)){ startTimer(); }else if(command.equalsIgnoreCase(CMD_STOP_TIMER)){ stopTimer(); }else{ Serial.println(F(”Unknown command!”)); } } if(sendNow){ //if timer told us it is time to send data buildAndPublish(true); sendNow = false; if(useMqtt){ client.loop(); } } } When using of the conceived sketch, one may change variables’ default values for specific behavior, in particular: •DEVICE_ID, which sets the device identifier; •useMqtt, which defines the use of a MQTT broker or Firebase; 77
CHAPTER 3. CROWD SENSING •FIREBASE_HOST,FIREBASE_AUTH and FIREBASE_PUSH, to set Firebase authentication; •MQTTSERVER,MQTTPORT,MQTTUSER and MQTTPASSWORD, to set MQTT authentication; •STATION_NETWORK and STATION_PASSWORD, to define the network the board is going to connect to; •AP_SSID and AP_PASSWORD, to define the network’s SSID and password that is provided by the board to client stations. The sketch should then be uploaded to the board using Arduino IDE. An upload speed (baudrate) of, at least, 57600 should be used otherwise timeouts will occur when uploading the sketch. A set of libraries are also required, including FirebaseArduino and PubSubClient. While the first allows the board to push data to Firebase, the second provides the ability to publish and subscribe to a server that supports MQTT. It uses a quality-of-service set to 0, which means that there are no guarantees data will reach the broker. In addition, the PubSubClient library limits the payload to 128 bytes on the MQTT_MAX_PACKET_SIZE variable. As we may sense several devices at once, this value will limit the payload from being sent to a MQTT broker. Hence, MQTT_MAX_PACKET_SIZE value in PubSubClient.h was updated to 4096 bytes. 3.2.3 Range Measurement Experiment The ESP boards come with a built-in antenna. However, there is no default value for its range. In fact, its range significantly depends on the environment where the board stands. Indoor scenarios, with walls, chairs, and tables, will limit the antenna’s range to a few dozen meters. On the other hand, line-of-sight propagation in outdoor scenarios can reach several hundred meters. This value will, however, decrease if a shell is used to protect the board from the weather. All experiments were performed using only the board’s built-in antenna. No external antenna was used. 3.2.3.1 Outdoor Experiment For this study, it was important to have a clear sense of the range of the ESP8266 ESP-12E NodeMCU Amica board in an outdoor scenario with a shell all around the board (to make it weatherproof). This allows one to know the exact area covered by a single board in such conditions. The adopted procedure focused on field experiments and was as follows: 1. Upload the sketch to the board and place the board inside its shell; 2. Select the point-of-interest, which consisted of a pedestrians’ crossing; 3. Power up the board; 78
CHAPTER 3. CROWD SENSING 4. Connect a smartphone to the board’s network; 5. Periodically connect/disconnect the smartphone from the board’s network, while moving away from the board in a straight line. While performing this action, the board collects the RSSI, which decreases to the point where one is unable to connect to the board’s network and no RSSI is received by the board; 6. Repeat the previous step multiple times, in different directions. Then, with the collected data, a straight line was drawn and it was calculated the distance between the board and the place where the signal was lost. The mean value indicated a range of, approximately, 27 meters on a straight line, covering an area of 2290 meters2(Figure 3.3) [66]. Figure 3.3: Range of the second-generation ESP8266 ESP-12E NodeMCU Amica board within a point-of- interest for VRUs: a pedestrian crossing. 3.2.3.2 Indoor Experiment To have an estimate of the indoor range of the ESP8266 ESP-12E NodeMCU Amica board, a similar procedure to the one described in the outdoor experiment was conducted. The sketch was initially uploaded to the board, which was then placed on a table, against a wall, at ISLab (Figure 3.4). An important difference is related to the lack of a shell surrounding the board, which is unnecessary in indoor environments. The board was then powered up, with a smartphone connecting to the board’s network. The next step was to periodically connect/disconnect the smartphone from the board’s network while moving away from the board in several directions, both inside and outside the laboratory. While performing this action, the board collects the RSSI, which decreases to the point where one is unable to connect to the board’s network and no RSSI is received by the board. Interestingly, the board’s range in an indoor environment is similar to its range in an outdoor scenario with a shell all around the board. Inside ISLab, which has an area of approximately 68 meters2, the board’s 79
CHAPTER 3. CROWD SENSING Figure 3.4: ISLab blueprint illustrating the location of the second-generation ESP8266 ESP-12E NodeMCU Amica board (circled in red) for the indoor range measurement experiment. signal was perfect. Outside ISLab, the board’s signal was able to cross several horizontal and vertical walls. The signal was received with low to medium strength on the floor below ISLab, in a vertical line. Two floors below, no signal was caught. Within the same floor as ISLab, the signal’s range varied according to the number of obstacles it faced. The signal was still caught 20 meters way from the sensor with four to five walls as obstacles. With fewer walls as obstacles, the signal had a range higher than 30 meters. Such signals were caught inside other laboratories, offices, and corridors. Based on the obtained results, it is estimated that one board is able to cover half a floor of the Department of Informatics of the University of Minho. 3.2.4 Passive Crowd Sensing Experiment The ESP board, i.e., the Smart Scanner when deployed with the developed software, was used for crowd sensing in both outdoor and indoor scenarios. Greater importance was given to the sensorization of the outdoor environment since it allows one to sense and gather insights at important points-of-interest for VRUs. The indoor experiment is to be understood as a further validation of the Smart Scanner’s sensing capabilities. 3.2.4.1 Outdoor Experiment Having defined the Smart Scanner’s range in an outdoor environment, the crowd sensor was again placed in the location depicted in Figure 3.3 (geographic coordinates =41.561889, -8.397561). On March 23rd, 2018, four measurements were made with a duration of fifteen minutes each. While the Smart Scanner 80
CHAPTER 3. CROWD SENSING was sensing the environment and communicating its findings, an observer would be counting each person and each vehicle that would enter within the Smart Scanner’s range (observational method). This allowed one to have a validation measure. Figure 3.5 depicts the serial monitor output of the ESP8266 board, with several probe requests being captured, logged, and sent to Firebase’s cloud server. Figure 3.5: Serial monitor output of the ESP8266 board when working as a Smart Scanner. Figure 3.6 depicts the cloud-hosted database that was set to store probe requests captured and communicated by the Smart Scanner. It uses Firebase Realtime Database, a NoSQL database where data are stored as one large JSON tree. The Collector uses this feed to collect its crowd sensing data. Table 3.1 shows the outcome of the observational method vs the Smart Scanner’s data, for each one of the four periods. During these periods, the observer reported a total of 640 people and 90 vehicles within the Smart Scanner’s range, for a total of 730 people (assuming one occupant per vehicle). On the other hand, the Smart Scanner handled a grand total of 1062 requests from 722 distinct devices. The number of distinct devices is unscrambled from the received MAC address, the corresponding RSSI, and the timestamp associated with each request. Table 3.1: Outcome of the observational method vs the Smart Scanner’s data. Measurement Observation Smart Scanner People Vehicles Total Distinct Total 1st Period (11h46 - 12h01) 104 10 114 91 172 2nd Period (12h01 - 12h16) 164 20 184 224 322 3rd Period (12h16 - 12h31) 180 21 201 170 266 4th Period (12h31 - 12h46) 192 39 231 237 302 Total 640 90 730 722 1062 81
CHAPTER 3. CROWD SENSING Figure 3.6: Probe requests’ data model in Firebase Realtime Database. 3.2.4.2 Indoor Experiment For the indoor experiment, the crowd sensor was again placed in the location depicted in Figure 3.4 (geographic coordinates =41.561391, -8.397263). The board was powered up on July 25th, 2018, and sensed the environment until September 19th of the same year, for a total of 57 days. However, between August 21st and 26th, inclusive, the board was down and, so, no data were collected during the referred days. During the 51 days the crowd sensor was on, it collected a total of 232421 WiFi probe requests. From the grand total, 43590 correspond to distinct MAC addresses. However, if the analysis is performed per month, this number increases to 44762, meaning that several MAC addresses were sensed in multiple months (Table 3.2). Table 3.2: Data captured by the Smart Scanner for indoor crowd sensing. Measurement Active Days Probe Requests Probe Requests/Day Distinct MACs July 25th-31st 7 47205 6744 10188 August 1st-31st 25 45057 1802 9094 September 1st-19th 19 140159 7377 25480 Total 51 232421 15923 44762 82
CHAPTER 3. CROWD SENSING 3.2.5 Results and Discussion First and foremost, it must be highlighted that the followed method is entirely non-invasive, requiring no user interaction with the developed system. Not in any way did we try to decrypt any data or perform active actions to stimulate or alter normal network behavior. This study presents no expectation of harm. Instead, it aims to commit a benefit to our society. 3.2.5.1 Outdoor Experiment Regarding the results of the outdoor experiment, as depicted in Table 3.1, it is possible to identify some fluctuations between the values reported by the observer and the distinct devices detected by the Smart Scanner. The overall value displays, however, promising results, with the Smart Scanner showing only a two percent deviation from the real count of people in the sensed area (722 vs 730 people). It is also noticeable that the number of people tends to increase over time (Figure 3.7). This is explained by the fact that the sensed point-of-interest, a pedestrian crossing, is near a restaurant and the experiment took place close to lunch time. 114 184 201 231 91 224 170 237 0 50 100 150 200 250 11h46 - 12h01 12h01 - 12h16 12h16 - 12h31 12h31 - 12h46 Number of Sensed People Period Observer Smart Scanner Figure 3.7: Observer’s count vs the number of distinct devices captured by the Smart Scanner, per period. Altogether, the Smart Scanner pushed a total of 1062 Wi-Fi probe requests to the cloud-hosted database. It should be noted that this value corresponds only to new sightings captured by the Smart Scanner as it filters repeated sightings that are captured during a certain period of time. Figure 3.8 presents a comparison between the number of pushed probe requests by the Smart Scanner versus the number of distinct ones, per period. For instance, during the second period (12h01 - 12h16) the scanner dealt with a total of 322 Wi-Fi probe requests but only 224 where distinct, meaning that 98 requests were discarded as repeated. This happens, for example, if a person enters the point-of-interest but remains in the region for several minutes. In fact, that was a situation reported by the observer, where people were noticed to stay within the point-of-interest for a few minutes, meaning that several probe requests would be received by the crowd sensor. 83
CHAPTER 3. CROWD SENSING 172 322 266 302 91 224 170 237 0 50 100 150 200 250 300 350 11h46 - 12h01 12h01 - 12h16 12h16 - 12h31 12h31 - 12h46 Probe Requests captured by the Smart Scanner Period Total Distinct Figure 3.8: Probe requests pushed by the Smart Scanner to the cloud-hosted database, per period. Interestingly, when aggregating data for the four periods, the number of distinct devices sensed by the Smart Scanner reduces from 722 to 678. The most obvious explanation is that the same person was sensed in two, or more, periods, meaning that there were 44 people within the designated area in different periods. This is indeed useful because the point-of-interest is a pedestrian crossing near a restaurant, with the measurement periods happening just before lunchtime. Therefore, it is quite plausible that a person went through the point-of-interest on a period (e.g., the first one) to have lunch and then passed again in another period (e.g., the last one) after the meal (Figure 3.9). 730 678 0 100 200 300 400 500 600 700 800 11h46 - 12h46 Number of Sensed People Period Observer Smart Scanner Figure 3.9: Observer’s count vs the number of distinct devices captured by the Smart Scanner for all periods together. 84
CHAPTER 3. CROWD SENSING Listing 3.6: Creating geofences in Android. geofenceList.add(new Geofence.Builder() .setRequestId(geo_name) //requesting the geofence ID, i.e., identify the geofence .setCircularRegion(latitude, longitude, radius) .setExpirationDuration(Geofence.NEVER_EXPIRE) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence. ↩→GEOFENCE_TRANSITION_EXIT) .build() ); 2. The GeofencingRequest class and its nested GeofencingRequestBuilder to specify the geofences to monitor and to set how related geofence events are triggered. Specifying INITIAL_TRIG GER_ENTER tells that GEOFENCE_TRANSITION_ENTER should be triggered if the device is already inside the geofence (Listing 3.7); Listing 3.7: Monitoring geofences. private GeofencingRequest getGeofencingRequest(){ GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); builder.addGeofences(geofenceList); return builder.build(); } 3. Adding, to the geofencingClient object, the created geofences (Listing 3.8). Listing 3.8: Adding the created geofences. GeofencingClient geofencingClient = LocationServices.getGeofencingClient(); geofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent()) .addOnSuccessListener(this,new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid){ //geofences added } }) .addOnFailureListener(this,new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { //failed to add geofences } }); 91
CHAPTER 3. CROWD SENSING 3.3.2.2 Heat-maps API While Google’s Geofencing API is to be used in the Geofencing experiment, for the emotional map we are required to illustrate feelings in a map. For that, the option was to use Google Maps’ Android Heat-map Utility API, which gives the possibility of representing the distribution and relative intensity of data points on a map. With heat-maps, rather than placing markers at each location, one can use colors to represent the density of data points. To use this API a set of methods must be implemented, including: 1. Creation and addition of a collection of geographically tagged data points to create an Heatmap- TileProvider with a customized color gradient. Then calling GoogleMap.addTileOverlay() to add the created overlay to the map (Listing 3.9); Listing 3.9: Creating the heat-map in Android. private fun addHeatMapForCategory(mMap: GoogleMap, categoryData: MutableList< ↩→FirebaseFeelings>, userCategoryData: MutableList<FirebaseFeelings>){ var latLngFeelings = getLatLngPointsFromFirebaseFeelings(categoryData) latLngFeelings.addAll(getLatLngPointsFromFirebaseFeelings(userCategoryData)) if(latLngFeelings.isNotEmpty()){ val gradient = Gradient(heatMapColors, heatMapStartPoints) mProvider = HeatmapTileProvider.Builder() .data(latLngFeelings) .radius(HEATMAP_RADIUS) .gradient(gradient) .opacity(HEATMAP_OPACITY) .build() mOverlay = mMap.addTileOverlay(TileOverlayOptions().tileProvider(mProvider)) } } 2. Ability to change the dataset upon which a heat-map is built (Listing 3.10); Listing 3.10: Changing the dataset of geographically tagged data points that make the heat-map. private fun changeDataset(categoryData: MutableList<FirebaseFeelings>, userCategoryData: ↩→MutableList<FirebaseFeelings>){ if(this::mOverlay.isInitialized) { var latLngFeelings = getLatLngPointsFromFirebaseFeelings(categoryData) latLngFeelings.addAll(getLatLngPointsFromFirebaseFeelings(userCategoryData)) //set new data mProvider.setData(latLngFeelings) //clear cache mOverlay.clearTileCache() } } 92
CHAPTER 3. CROWD SENSING 3. Ability to remove a heat-map (Listing 3.11). Listing 3.11: Removing the heat-map. fun removeHeatmap(){ if(this::mOverlay.isInitialized) mOverlay.remove() } 3.3.2.3 Technologies Both the geofences as well as the city’s map from people’s feelings experiments use APIs that are made available by Google. Both experiments target the Android operating system, using Java and Kotlin as programming languages. Android Marshmallow is the lowest supported version (API version 23), with Android Pie as target version (API version 28). Android Studio 3.5.2 is the used IDE. To store and synchronize data, Firebase’s Cloud Firestore was used. 3.3.3 Geofencing With the goal of providing useful information to people when they are near an area of interest, geofences were conceived to establish virtual perimeters over real-world geographic areas. The focus was set in VRUs and on alerting them as soon as they enter zones of the city where their vulnerability increases. In fact, four distinct categories were elicited and defined, namely high-traffic, polluted, crowded, and dangerous zones. Each geofence is associated with one and only one category, being further characterized by its geographic coordinates, a radius, a name, an expiration duration, and the timestamp that specifies when the geofence was created (Listing 3.12). Listing 3.12: FirebaseGeofence object. data class FirebaseGeofence ( val name: String? = null, val category: GeofenceCategory? = null, val lat: Double? = null, val lng: Double? = null, val radius: Float? = null, val expiration: Long? = null, @ServerTimestamp var timestamp: Date? = null ) Geofences are stored in Firebase’s Cloud Firestore, a cloud-hosted NoSQL database that supports hierarchical data structures (as detailed in Section 2.3.2). In this database, the geofences collection contains all existing geofences in the form of documents. Each document has a unique identifier and a set of fields that characterize the geofence. Figure 3.14 depicts the hierarchical data structure to store 93
CHAPTER 3. CROWD SENSING geofences as well as an example of a geofence categorized as being a dangerous zone due to the existence of unsafe crossroads within the covered area. Figure 3.14: Firebase’s Cloud Firestore cloud-hosted NoSQL database holding geofence objects. Geofences are created by users with an administrator permission (read and write permissions). Only authenticated users are able to access the existing geofences (read permission). Access rules are set in Firebase’s Cloud Firestore database, as depicted in Listing 3.13. Listing 3.13: Access rules to the geofences collection. rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { //default rule match /{document=**} { allow read, write: if false; } //geofences Collection match /geofences/{geofences} { allow read: if request.auth != null; } } } With the data model and the support infrastructure defined, a mobile application, targeting the Android operating system, was conceived to provide alerts to its users as soon as they enter, or leave, a geofence. It presents a map-based layout with geofences being drawn in the map with different colors depending on its category. As permissions, it requires the ACCESS_FINE_LOCATION one, which allows the application to obtain the user’s location as precise as possible from the available location providers, including the GPS, 94
CHAPTER 3. CROWD SENSING WiFi, and mobile cell data, and the ACCESS_BACKGROUND_LOCATION permission, which allows the application to access the user’s location when running in the background. The structure of the developed application consists of several packages, viz. 1. util package, where the GeofenceCategory enum class represents all possible geofence’s categories; 2. model package, containing all classes that represent data objects, including the FirebaseGeofence object (Listing 3.12); 3. handlers package, containing all handlers responsible for the domain’s logic: a) GeofenceHandler, which is responsible for implementing Google’s Geofencing API. Includes sub-classes and methods to load, monitor, and draw geofences as well as to monitor geofence transitions and send notifications as soon as a transition is detected; b) FirebaseHandler, which includes all logic to access, write, and read from Firebase’s Cloud Firestore database; c) PermissionHandler, implementing the required methods to obtain users’ permission. Includes methods to check if a permission was granted as well as to ask the user to grant a permission; d) GpsHandler, which contains the logic to enable and disable the device’s GPS; e) LocationHandler, being responsible for obtaining the user’s current location if the user granted such permission. Includes methods to obtain the current location as well as to start and stop periodic location updates. 4. activity package, where the GeofenceActivity is defined. An activity provides the window in which the application draws its interface, with the Android system initiating the code in an activity by invoking methods that correspond to specific stages of the activity’s life cycle. GeofenceActivity implements methods to inflate the layout, set all button behaviors, and use the referred handlers. Figure 3.15 presents the mobile application’s logic in a simplified sequence diagram. The first steps consist of inflating the view and initializing the buttons’ behavior. Then, if permission is granted by the user to access his position, the application starts the smartphone’s GPS, and the LocationHandler starts updating, periodically, the user’s position in the map in parallel to the main processing flow. This keeps happening until the GPS is turned off or permissions are revoked. Geofences are then loaded and monitored, with the GeofenceHandler handling all notification callbacks as soon as the user enters, or leaves, a geofence. Notifications are still sent even with the application dismissed or running in the background. If the GPS is off or if no permission is granted, the user is still able to see the geofences in the application’s GUI but notifications will not be pushed. 95
CHAPTER 3. CROWD SENSING alt loop alt [Permission Granted] [while GPS on] [geofences successfully loaded] Geofence Handler Location Handler Actor Permission Handler Geofence Activity 3.1: Callbacks Response 3: Monitor Geofences 1.5.2: Load Geofences 1.5.1: Register geofencingClient 2.1: Update user location on map 2: Start Location Updates 1.5: Display Permission Not Granted Msg 1.3: Check and Request Permission 1.4: Display Permission Granted Msg 1.2: Set buttons callbacks 1.1: Inflate View 1: Start Geofence Application Visual Paradigm Standard(Bruno Fernandes(University of Minho)) Figure 3.15: Simplified sequence diagram of the geofencing activity. In regard to the application’s layout, it consists of a ConstraintLayout with an embedded google maps fragment where geofences are illustrated. The user can navigate anywhere on the map and zoom in/out. A button in the bottom right corner allows the user to center the view on his current position. If a geofence is clicked, it displays its category at the top of the screen. As soon as the user enters or leaves a geofence, a notification emerges in the smartphone, warning the user of such a fact. Figure 3.16 depicts the main view of the conceived mobile application. In Figure 3.16a it is shown the map view of the application with several geofences of distinct categories and radius, painted over the map, with the user inside a crowed geofence. On the other hand, Figure 3.16b presents the notification received by the user as soon as he enters a geofence. A case study was implemented to evaluate the conceived application. The first step focused on defining 96
CHAPTER 3. CROWD SENSING (a) User entered a crowded geofence. Red marker sets the user location. (b) Notification from entering a crowded geofence named ”Housing Zone”. Figure 3.16: Main views of the mobile geofencing application. a set of geofences in the city of Braga, in Portugal. Sixteen were defined and categorized. Then, with the GPS on and the application installed in a Xiaomi Mi A1 smartphone running Android 9 (API level 28), the subject moved around the city on a rainy day using two distinct transportation means: on foot and in a car. The goal was to analyze the application’s performance in terms of latency between entering/leaving a geofence and the reception of the corresponding notification. As expected, when walking the application’s performance was better than when inside a car, i.e., the application was quicker to perceive that the subject entered/left a geofence when on foot. In fact, it took around 2 seconds for notifications to be pushed when entering a geofence. To push exit notifications, the application took approximately the same time. When using a car as mean of transport, the performance clearly deteriorates as speed increases. Indeed, in cases where the geofence had a small radius (less than 50 meters), since vehicles go through the geofence almost instantaneously, no entry neither exit notification is pushed to the subject’s smartphone. This happens because the LocationHandler is unable to query the user’s location within an acceptable time frame. On the other hand, geofences with a higher radius would be detected depending on the speed of the vehicle or the traffic status, for example. At low speed, the obtained results on a vehicle show similarities of those when walking, with notifications being pushed successfully and in an acceptable time (a delay of three to four seconds). No experiments were conducted when riding a bike. However, since in an urban context the speed of a cyclist is closer to that of a pedestrian, response times are expected to be similar but with a possible deterioration. On the other hand, when driving a motorcycle, response times 97
CHAPTER 3. CROWD SENSING are expected to be closer to that of a car. Some aspects of the conducted experiments must be highlighted. Firstly, all experiments were conducted on a rainy day, which can significantly influence GPS precision and negatively affect response times. Secondly, smartphone’s GPS quality is yet another factor that may positively, or negatively, affect response times. Finally, with regard to the background operation of the conceived application, notifications were successfully pushed even with the application dismissed or in the background, if the smartphone’s screen is not locked. However, if the subject locks the smartphone’s screen, the notification is only pushed when the screen is unlocked, which can happen several minutes after going through a geofence. As direct answers to the elicited research questions, it can be said that (RQ3.5) Google’s Geofencing API facilitated the conception of geofences and the monitoring of geofence transitions, which were drawn over a map for user convenience. The conceived application (RQ3.6) was able to successfully warn pedestrians and runners as soon as they entered, or left, a geofence within an acceptable time frame. In regard to car occupants, response times depend on the size of the geofence as well as the vehicle’s speed. 3.3.4 Emotional Map from People’s Feelings With the goal of gathering insights from a city’s crowd in regard to their feelings towards certain zones and categories of a city, a mobile application containing an emotional map was conceived to quantify and illustrate such feelings. The expectation is to listen to several individuals and, thus, take advantage of the wisdom of crowds to quantify the overall feeling of people towards their city. Three distinct positive categories were defined, in particular, attractive zones in terms of shopping, sports, and history. One negative category is used to refer to crime hotspots. Feelings are binary and categorically tagged, being further characterized by its geographic coordinates, a title, and the timestamp that specifies its creation date (Listing 3.14). Listing 3.14: FirebaseFeelings object. data class FirebaseFeelings( val title: String? = null, val category: FeelingsCategory? = null, val lat: Double? = null, val lng: Double? = null, @ServerTimestamp var timestamp: Date? = null ) Similar to geofences, feelings are also stored in an instance of Firebase’s Cloud Firestore database. The users_feelings collection holds a document for each user of the application. Each document contains a nested collection of markers. This collection, in turn, contains all feelings of the corresponding user in the form of documents (one document per feeling). Each document is an instance of the FirebaseFeelings object. Figure 3.17 depicts the hierarchical data structure to store feelings as well as an example of a feeling for a historical zone (geographic coordinates =41.551669, -8.422953) named ”Avenida Central”. 98
CHAPTER 3. CROWD SENSING Figure 3.17: Firebase’s Cloud Firestore cloud-hosted NoSQL database holding feelings objects. Listing 3.15 details the access rules to the users_feelings collection. Users are able to write feelings only to their documents (read and write permissions). Authenticated users can read the feelings of the entire community (read permission). This is necessary since the mobile application needs to access all community feelings to draw the emotional map. Listing 3.15: Access rules to the users_feelings collection. service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if false; } match /users_feelings/{userId} { allow create, update: if belongsTo(userId); } match /users_feelings/{userId}/{document=**} { allow write: if belongsTo(userId); } match /{path=**}/markers/{document} { allow read: if request.auth != null; } function belongsTo(userId) { return request.auth.uid == userId } } } 99
CHAPTER 3. CROWD SENSING With the data model and the support infrastructure defined, a mobile application, targeting the Android operating system, was conceived to allow users to add categorized feelings to certain zones of a city as well as view the feelings of the entire community using a heat-map perspective. As permissions, the application only requires the ACCESS_FINE_LOCATION one to obtain the user’s location and display it on the emotional map. An internet connection is required to commit new feelings and update the emotional map with the community’s feelings. In terms of structure, the conceived application consists of the following packages, viz. 1. util package, where the FeelingsCategory enum class represents all possible feelings’s categories; 2. ui package, containing the fragment view for each category; 3. model package, containing all classes that represent data objects, including the FirebaseFeelings object (Listing 3.14); 4. handlers package, containing all handlers responsible for the domain’s logic: a) FeelingsMapHandler, responsible for loading the user’s and the community’s feelings. It is also responsible for implementing Google Maps’ Android Heat-map Utility API. Includes sub-classes and methods to compute and draw the heat-map, per category; to draw the user’s feelings in the map; to add/remove user’s feelings; and to validate that the minimum distance between feelings is respected; b) FirebaseHandler, which includes all logic to access, write, and read from Firebase’s Cloud Firestore database; c) PermissionHandler, implementing the methods to obtain the required permission; d) GpsHandler, which contains the logic to enable and disable the device’s GPS; e) LocationHandler, being responsible for obtaining user’s current location if the user granted such permission. Includes methods to obtain the current location as well as to start and stop periodic location updates. 5. activity package, where the FeelingsMapActivity is defined. It implements methods to inflate the layout, set all button behaviors, and use the referred handlers. Figure 3.18 depicts the application’s logic in a simplified sequence diagram. After inflating and initializing the activity’s view, if the user granted permission, the application starts the smartphone’s GPS and the LocationHandler starts updating, periodically, the user’s position in the map in parallel to the main processing flow. The activity then instantiates the FeelingsMapHandler, which immediately checks if an active internet connection is available. If true, all feelings are loaded, the heat-map is built, and the user’s feelings are drawn on the map. The sequence diagram also shows the addition/removal of a feeling 100
CHAPTER 4. CITIZEN SENSING •Extraversion: related to a state where a person seeks stimulation from being with others. Extroverted people tend to be energetic and talkative, while introverted ones are reserved; •Agreeableness: related to behavioral characteristics such as being kind and sympathetic. Agreeable people tend to be friendly, cooperative, and empathetic. Non-agreeable people are less cooperative and more competitive; •Neuroticism (opposite of Stability): related to being moody and showing signs of emotional instability. Neurotic people tend to be stressed and nervous. Non-neurotic people are more emotionally stable [217]. Goldberg’s test consist of 100 unipolar markers that must be quantified by a subject. An important reduction to the set of markers was performed by Gerard Saucier with The Mini-Marker test, using a sub-set of 40 markers to assess the Big Five with an acceptable performance, leading to the use of less difficult markers [218]. Saucier’s test uses the same rating scale, being made of five disjoint-sets of eight unipolar markers each: •Intellect or Openness trait is made of six positively weighted adjectives (intellectual,creative, complex,imaginative,philosophical, and deep) and two negative ones (average and ordinary); •Conscientiousness trait is made of four positively weighted adjectives (systematic,practical, efficient, and orderly) and four negative ones (disorganized,careless,inefficient, and sloppy); •Extraversion trait is made of four positively weighted adjectives (extroverted,talkative,energetic, and bold) and four negative ones (shy,quiet,withdrawn, and bashful); •Agreeableness trait is made of four positively weighted adjectives (kind,cooperative,sympathetic, and warm) and four negative ones (cold,harsh,rude, and distant); •Emotional Stability trait is made of two positively weighted adjectives (relaxed and mellow) and six negative ones (moody,temperamental,envious,fretful,jealous, and touchy). During the last years, multiple studies have already engaged in using ML models for personality assessment using images, videos, audio, or text as input data. However, no proposals have been made to reduce the complexity of tests using ML. Hence, the conducted research aims to give an answer to the following research question: RQ4.1. Is it possible to use ML-based models to further reduce Saucier’s Mini-Marker to a ”game of words” where the subject, instead of rating forty adjectives, only has to select those he relates the most? The next lines describe the process that was carried out to answer this question and propose the ASAP method, which replaces the entire process of rating adjectives by an adjective selection process. 107
CHAPTER 4. CITIZEN SENSING 4.2.1 State of the Art The use of ML to predict personality traits has been gaining popularity within the field of Affective Computing, with several studies engaging in conceiving ML models for personality assessment [54,55,217,219]. In 2017, Majumder et al. conceived and evaluated DL models to assess personality from text. They conceived and fit a total of five ANNss, one for each personality trait. All networks had the same architecture, with each ANNs behaving as a binary classifier to predict whether the trait was positive or negative [54]. As dataset, the authors used James Pennebaker and Laura King’s stream-of-consciousness essay dataset, which contains 2468 anonymous essays tagged with the binary value for each of the Big Five [220]. This dataset seems to be currently unavailable. In 2017, Yu and Markov conceived and evaluated multiple DL models to learn suitable data representation for personality assessment, using Facebook status update data. This dataset consisted of raw text, user’s information, and standard Big Five labels, which were obtained using self-assessment questionnaires [55]. In fact, it is possible to find several studies focused on inferring personality based on social media feeds. For instance, Kosinski et al. (2014) focused on examining how an individual’s personality manifests in his/her online behavior [217]. The obtained results showed psychologically meaningful links between individuals’ personalities, website preferences, and social media data. The potential applications of these works are essentially related to targeted advertising and personalized recommender systems, which take into consideration one’s personality to deliver useful content. In 2012, Sumner et al., based on Twitter use, focused on identifying signals of the Dark Triad, i.e., the anti-social traits of Narcissism,Machiavellianism, and Psychopathy. Almost three thousand Twitter users, from 89 countries, participated in the study, with an in-built Twitter application being developed to collect self-reported ratings on the Short Dark Triad questionnaire, which measures the anti-social traits, and the Ten Item Personality Inventory test. The authors conclude that even though possible to examine large groups of people, the conceived ML models behave poorly when applied to individuals, being imprecise when predicting Dark Triad traits just from Twitter activity [219]. Another study, performed by Cerasa et al. (2018), focused on conceiving and evaluating ML models to identify individuals with gambling disorder. To build the dataset, a set of healthy and sick individuals were asked to perform the NEO-personality-inventory test. The authors employed Classification and Regression Trees achieving interesting performances evaluated using the Area Under the Curve (AUC). In fact, the best candidate model was able to identify individuals with gambling disorder with an AUC of approximately 77% [221]. On the other hand, studies have been performed where audio and video data are used by DL-based models to predict personality [53]. One study, performed by Levitan et al. (2016), focused on the automatic identification of traits such as gender, deception, and personality using acoustic-prosodic and lexical features [222]. In particular, the authors focused on automatic detection of deception. The authors used Columbia deception corpus, which consists of deceptive and non-deceptive speech from standard American-English and Mandarin-Chinese native speakers, including more than one hundred hours 108
CHAPTER 4. CITIZEN SENSING of speech with self-identified truth/lie labels [223]. The authors then collected demographic data from each subject and administered a NEO-FFI personality test to access the Big Five. Each trait was binned as a three-class classification problem (low,medium, and high), which created an highly unbalanced dataset since the majority of subjects fell into the medium class. Several ML models and feature sets have been experimented, with AdaBoost and Random Forests being the best performing classifiers for personality assessment [222]. Another study, performed by Gurpinar et al. (2016), focused on using DL to predict the Big Five of faces appearing in videos [224]. The authors employed transfer-learning and CNNs to extract facial expressions, as well as ambient information. The conceived models were evaluated on the ChaLearn Challenge Dataset on First Impression Recognition, which consists of ten thousand clips collected from more than five thousand YouTube videos. The label of each clip corresponds to the Big Five personality traits of the person appearing in that clip. Their best candidate model achieved an accuracy of over 90% on the test set [224]. It is also usual to find the use of different data sources combined through means of data fusion for personality assessment. Indeed, personality assessment from multi-modal data has been assuming a greater importance in the computer vision field [225]. For instance, Gucluturk et al. (2017), aimed to analyze what features are used by personality trait assessment models when making predictions, conducting several experiments that characterized audio and visual information that drive such predictions [225]. On the other hand, Zhang et al. (2016) proposed a Deep Bi-modal Regression framework to capture rich information from both the visual and audio aspects of videos, winning the ChaLearn Looking at People challenge. CNNs were conceived to exploit visual cues, while linear regressors were used for audio [58,226]. 4.2.2 Data Collection and Exploration Due to the non-availability of data and the particularities of the proposed method, we were required to develop a web platform for data collection, requesting subjects to rate adjectives and select those describing them the most. This allowed us to build a dataset containing self-reported ratings on Saucier’s Mini-Marker test, the corresponding values of the Big Five as well as the adjectives selected by the subjects. The next lines describe in detail the developed platform, exploring and explaining the collected dataset and the implemented data augmentation techniques. It also details the conceived ML architectures and the experimental setup. 4.2.2.1 Web Platform for Data Collection To bring this study to a fruitful conclusion, we were required to collect a dataset from where we could derive knowledge. Hence, a platform was conceived and made available online1. The platform displays all 40 adjectives used by Saucier’s Mini-Marker test, asking the subject to rate each one. It also allows the subject to select a set of adjectives that describe him the most. Figure 4.1 depicts the main page of the 1http://crowdsensing.di.uminho.pt/ 109
CHAPTER 4. CITIZEN SENSING Figure 4.1: Web platform for data collection allowing the subject to perform Saucier’s Mini-Marker test and, at the same time, select a set of adjectives that describe him the most. conceived platform. The subject can then get the test results and obtain the value of each personality trait (Figure 4.2). The platform provides a rationale to explain the subject how he/she is contributing to the study. No personal data are stored neither it is possible to link subjects to their answers - only information about age, genre, and language are stored, and only if the user explicitly provides it. The platform is available online and any person can access and use it. It was published online on 21st September 2018, and was deployed in an Ubuntu 18.04 machine hosted at the University of Minho. The platform was shared among a diversified population, using social media and the university’s mailing lists. Data were also collected in person, which allowed us to increment the dataset size with records containing both the ratings and the selected list of adjectives [58]. To facilitate the data collection process, the developed platform allows subjects to perform Saucier’s Mini-Markers in three distinct languages. All translations were performed by three Portuguese and Spanish native speakers fluent in English. It should also be highlighted that this study does not aim to examine the psychometric properties of the Portuguese or Spanish versions neither to provide sound validity evidence for the performed translations (even though Tau-Equivalent estimates of score reliability are later examined). The assumption is that ML models are able to quantify, or qualify, the personality traits without requiring any contextual information about the region, genre, language, or age of the subjects. The web platform was conceived using Node.js, an asynchronous and open-source event-driven Java- Script runtime environment that executes JavaScript outside the browser, allowing one to write server-side scripts. A web application framework, Express.js, was also used. Several external packages were used, including i18n, for language translation using dynamic JSON,cookie-parser, to parse cookies attached to the client request object, and mysql, for loading the appropriate Node.js database driver. 110
CHAPTER 4. CITIZEN SENSING Figure 4.2: Results of Saucier’s Mini-Marker test provided by the web platform. A set of routes were created to regulate how the platform answers to client requests for particular endpoints, which includes an Uniform Resource Identifier (URI) and a specific HTTP request method. The routes specify a handler function that is called when the application receives a request to the specified route. Listing 4.1 depicts how the conceived platform routes the received requests. Listing 4.1: Routing of the web platform for personality assessment and data collection. var express = require('express'); var mainRouter = require('./routes/main'); var resultsRouter = require('./routes/results'); var translationRouter = require('./routes/translation') var app = express(); //for any HTTP request method app.use('/', mainRouter); app.use('/main', mainRouter); app.use('/results', resultsRouter); app.use('/translation', translationRouter); //catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); 111
CHAPTER 4. CITIZEN SENSING Listing 4.2 presents the resultsRouter, the one responsible for rendering the subject’s personality traits in the web browser. For the sake of simplicity, only this router is here presented. The remaining routers are similar in terms of structure. Listing 4.2: The resultsRouter is the one responsible for rendering the subject’s personality traits. var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { if(!req.session.results { return res.redirect('/main'); } //get data from the session var results = req.session.results; var extraVal = results.ExtraVal; var agreeVal = results.AgreeVal; var consVal = results.ConsVal; var stableVal = results.StableVal; var openVal = results.OpenVal; //render view res.render('results', { title: 'Big Five Mini-Test', extraversion: extraVal, agreeableness: agreeVal, conscientiousness: consVal, stability: stableVal, openess: openVal } ); }); module.exports = router; The platform consists of three view files developed using EJS, a templating language to generate HTML markup with JavaScript. The main.ejs file is used to dynamically build the main page of the platform (Figure 4.1), the results.ejs is used to build the results page (Figure 4.2) and, finally, the error.ejs is used to display errors. A set of scripts were conceived and are used to compute the traits’ value based on the answers of the subject and to optimize the applications’ GUI. The subject’s answer to the personality test is stored in a MySQL database (version 14.14 and distribution 5.7.29) using an InnoDB engine (version 5.7.29), remotely deployed in the same machine as the web platform. 4.2.2.2 Data Exploration The collected dataset contains 255 observations. Each observation is made of 50 features, viz, age, genre,language, 40 adjectives, 5 personality traits, the selected adjectives, and the creation date. The age, the 40 adjectives, and the 5 personality traits are integers. The genre is a binary attribute and language is either es,en, or pt. On the other hand, the selected adjectives feature (also 112
CHAPTER 4. CITIZEN SENSING Table 4.1: Features available in the personality dataset. # Feature # Feature # Feature 1age 18 philosophical 35 cold 2genre 19 bashful 36 disorganized 3language 20 warm 37 temperamental 4talkative 21 inefficient 38 complex 5sympathetic 22 touchy 39 extraverted 6orderly 23 creative 40 rude 7envious 24 energetic 41 efficient 8deep 25 cooperative 42 fretful 9withdrawn 26 practical 43 imaginative 10 harsh 27 jealous 44 extraversion_trait 11 careless 28 intellectual 45 agreeableness_trait 12 relaxed 29 quiet 46 conscientiousness_trait 13 average 30 distant 47 stability_trait 14 bold 31 sloppy 48 openess_trait 15 kind 32 mellow 49 selected_attr 16 systematic 33 ordinary 50 creation_date 17 moody 34 shy described as selected_attr) consists of a string where the selected adjectives are comma separated. Table 4.1 presents all available features in the personality dataset. In the final dataset, 159 observations have the selected_attr feature filled with the selected adjectives. On the other hand, 96 observations only have the adjectives’ ratings. A few observations have adjectives rated with the value 0. 200 observations belong to male subjects, while 55 belong to female ones. Only two languages were used: 220 observations were done in Portuguese while 35 were done in English. More than 90% of the observations were collected in 2019. The mean age value of subjects is of 30.1 years. Adjectives with lower mean value are essentially related to negative ones such as rude, with 3.13, inefficient, with 3.26, and ordinary, with 3.28. The adjectives that have higher mean value are kind, with 6.004, imaginative, with 6, and cooperative, with 5.73. Mean standard deviation of the 40 adjectives is 2.5, with the lower value being 0 and the maximum 9. Mean skewness is of 0.03, representing a symmetrical distribution. Mean kurtosis is of −0.98, representing a somewhat ”light-tailed” dataset in regard to the 40 adjectives. In regard to the Big Five (Table 4.2), the one having lower mean value is Extraversion, with Agreeableness being the one with higher mean value. Mean standard deviation of all traits is of approximately 10 units of measure. The coefficient alpha for the forty items is of 0.82 [227]. For each individual trait, the Tau-Equivalent estimates of score reliability are lower, specially for the Stability factor. Except for the selected_attr feature, no missing values are present in the dataset. With all features assuming a non-Gaussian distribution (under the Kolmogorov-Smirnov test with 𝑝< 0.05), the non-parametric Spearman’s rank correlation coefficient was used. A few pairs of correlated features, in the form (trait, adjective), appear in the dataset. This is in line with expectations since the Big Five are mathematically based on the adjectives. Higher correlations appear for the pairs (Agreeableness, 113
CHAPTER 4. CITIZEN SENSING Table 4.2: Descriptive statistics for the Big Five. Openness Conscientiousness Extraversion Agreeableness Stability Nº of Items 8 8 8 8 8 Mean 44.976 46.476 39.428 47.148 46.140 Median 46 47 40 48 46 Std. Deviation 10.315 10.547 10.017 10.056 8.860 Skewness −0.212 −0.207 −0.135 −0.216 −0.047 Kurtosis −0.260 −0.492 −0.344 −0.328 −0.484 Coef. Alpha 0.62 0.61 0.56 0.58 0.42 Warm), (Conscientiousness, Efficient), (Openess, Complex) and (Extraversion, Extraverted). The selected_attr feature consists of a string where adjectives are separated by commas. An example of a valid value would be ”Talkative, Sympathetic, Kind, Energetic, Jealous, Intellectual, Extraverted, Efficient, Fretful”. From all 159 observations that have the selected_attr feature filled, 157 are unique values meaning that only three subjects chose the same adjectives. Interestingly, all adjectives were selected at least once. In fact, the least selected adjectives were ordinary, which was selected 14 times, touchy, 18 times, rude, 19 times, and cold and fretful, 23 times. These are, essentially, adjectives with negative connotation. On the opposite spectrum, kind was selected 67 times, imaginative, 59 times, sympathetic, 58 times, creative, 57 times, and withdrawn, 56 times (Figure 4.3). Excluding those who opt not to select adjectives, 10 subjects only chose one adjective to describe themselves, while 14 subjects selected fifteen, or more, adjectives. The mean value is of approximately ten selected adjectives per subject. Approximately 38% of the total number of observations do not have adjectives selected. To overcome this issue, it becomes important to understand the relation between selecting an adjective and its respective rating. For instance, considering all subjects that selected the adjective efficient, the mean rating of that same adjective is of 5.794. On the other hand, the mean rating of the sloopy adjective considering all Kind Imaginative Sympathetic Creative Withdrawn Intellectual Shy Bashful Relaxed Practical Systematic Quiet Bold Mellow Orderly Efficient Deep Talkative Cooperative Philosophical Jealous Energetic Envious Careless Disorganized Harsh Warm Sloppy Complex Average Distant Temperamental Moody Extraverted Inefficient Fretful Cold Rude Touchy Ordinary 0 10 20 30 40 50 60 70 Number of Times Selected 67 59 58 57 56 55 50 50 49 49 48 48 47 47 46 45 43 42 42 41 41 41 38 38 38 33 31 30 30 30 29 29 29 27 24 23 23 19 18 14 Figure 4.3: Number of times each adjective was selected. 114
CHAPTER 4. CITIZEN SENSING sloppy warm imaginative inefficient orderly fretful distant complex practical energetic quiet philosophical cold kind creative disorganized cooperative withdrawn deep harsh talkative shy intellectual touchy mellow careless sympathetic jealous relaxed bashful extraverted rude moody temperamental bold systematic envious average ordinary efficient 1 2 3 4 5 6 7 8 9 Mean Selection Rating 8.0 7.9 7.9 7.9 7.8 7.8 7.8 7.7 7.7 7.7 7.7 7.7 7.7 7.6 7.6 7.6 7.6 7.6 7.5 7.5 7.5 7.5 7.5 7.4 7.4 7.4 7.4 7.4 7.3 7.3 7.3 7.3 7.2 7.2 7.1 7.1 7.0 6.8 6.6 5.8 Figure 4.4: Mean rating values to set an adjective as selected. subjects that selected that adjective is of 8. This tells us that sloopy tends to be selected when receiving higher ratings. On the other hand, efficient is selected even with average ratings. The overall mean, 7.448, tells us that, as expected, adjectives tend to be selected when receiving high values. Figure 4.4 depicts the mean rating values to set an adjective as selected. To discover relations between the selected adjectives, a ML and a pattern mining method, entitled as Association Rules Learning (ARL), was applied. ARL does not consider the order of the items, neither it extracts an individual’s preference. Instead, it looks for frequent itemsets. The goal is to find associations and correlations between adjectives that were selected to describe subjects. In particular, the APRIORI algorithm was used to analyze the list of selected adjectives, and provide rules in the form Antecedent -> Consequent, where -> may be read as ”implies”. To find these rules, three distinct metrics were used: Support, which gives an idea of how frequent an itemset is in all existing transactions, helping identifying rules worth considering; Confidence, an indication of how often a rule is true; and Lift, which measures how much better the rule is at predicting the presence of an adjective compared to just relying on the raw probability of the adjective in the dataset. The returned rules go both ways, i.e., if Aimplies Bthen the reverse is also true. Table 4.3 presents all rules with a support value higher than 0.15. In fact, the support value was tuned to find a representative set of rules. Such a lower support value tells us that rules tend to be less frequent than expected. On the other hand, the obtained confidence values strengthen the possibility of both the antecedent and the consequent being found together for a subject. Lift values higher than 1 tells us that the adjectives are positively correlated [58]. 4.2.3 Data Preparation and Pre-processing A random seed, as 91190530, was defined for replicability purposes. Five observations that had abnormal values were removed. In particular, one observation had abnormally high values, while the other four were filled with the same exact dummy value for all adjectives. None of these observations had the selected_attr feature filled. The final dataset is made of 250 observations. 115
CHAPTER 4. CITIZEN SENSING Table 4.3: Rules with support higher than 0.15 using Association Rules Learning and the APRIORI algorithm. Support Confidence Lift Antecedent Consequent 0.195 0.525 1.466 Creative –> Imaginative 0.189 0.508 1.207 Kind –> Imaginative 0.176 0.418 1.146 Sympathetic –> Kind 0.170 0.551 1.511 Sympathetic –> Relaxed 0.170 0.491 1.394 Withdrawn –> Intellectual 0.170 0.491 1.165 Kind –> Intellectual 0.170 0.540 1.281 Kind –> Shy 0.164 0.464 1.273 Sympathetic –> Withdrawn 0.164 0.634 1.505 Kind –> Jealous 0.157 0.521 1.428 Sympathetic –> Systematic 0.157 0.500 1.371 Sympathetic –> Bashful 0.157 0.500 1.187 Kind –> Bashful 0.151 0.510 1.400 Sympathetic –> Bold 0.151 0.358 1.017 Withdrawn –> Kind 0.151 0.585 1.389 Kind –> Energetic 4.2.3.1 Handling zero-ratings The lowest accepted value by Saucier’s test is one, however, zeros are present in the dataset. To correct this situation and to make all observations mathematically valid, such values were updated to the nearest valid value, with traits’ values being re-calculated based on such changes. 4.2.3.2 One-hot encoding the selected_attr feature The selected_attr feature consists of a string with comma-separated adjectives. Such data were one-hot encoded using a Multi-Label Binarizer, allowing these data to become easier to handle by ML models. Forty new features were created, being entitled as {adjective}_selected, with {adjective} being a placeholder for the corresponding adjective name. A value of 0 means that the adjective was not selected, with a value of 1 meaning selection. 4.2.3.3 Filling the selected_attr feature when empty Approximately 38% of all observations do not have adjectives selected, i.e., the selected_attr feature is empty because the subject did not choose any adjective. However, to be able to propose the ASAP method, we are required to have as many observations as possible with the selected_attr feature filled. Hence, a method was conceived to synthetically mark adjectives as selected based on adjectives’ ratings and frequent patterns of selected adjectives. The first step consists in iterating through the observations without selected adjectives. Then, for each observation, iterate through each adjective. If the adjective’s rating is higher than the mean selection rating of that same adjective (as depicted in Figure 4.4), then the adjective is a candidate to be selected. 116
CHAPTER 4. CITIZEN SENSING Table 4.4: Hyperparameters’ searching space. Parameter Searched Values Rationale a. Number of Estimators [300, 400, 500] Number of trees in a model b. Eta [0.01, 0.05, 0.1] Learning rate c. Gamma [0.02, 0.04, 0.08] Minimum loss reduction required to make a further partition on a leaf node d. Trees’ Max Depth [4, 12, 18] Maximum depth of a tree e. Minimum Child Weight [4, 6, 8] Minimum sum of instance weight needed in a child (higher values for conservative models) f. Colsample by tree [0.2, 0.3] Fraction of columns to be sub-sampled (controlling correlation between trees) 4.2.5 Results and Discussion Two distinct ML architectures were experimented. One uses Gradient Boosted Trees regressors to obtain the exact value of each personality trait (Architecture I) while the other uses Gradient Boosted Trees classifiers to obtain the bin of each personality trait (Architecture II). Different experiments were conducted with two distinct datasets. One with 250 observations (No DA) and another with 5230 observations (With DA). Both architectures receive, as input, the one-hot encoded selection of adjectives. Nested cross-validation was performed to tune the hyperparameters and to have a stronger validation of the obtained results. Inner cross-validation was performed using 𝑘=4, with random search being used to find the best set of hyperparameters. In the inner loop, 700 fits were performed (4 folds ×175 combinations). The outer cross-validation loop used 𝑘=3, totaling 2100 fits (3 folds ×700 fits). Two independent training trials were performed, with a grand total of 4200 fits (2 trials ×2100 fits) per architecture per dataset [58]. 4.2.5.1 Architecture I - Big Five Regressors All candidate models were evaluated in regard to RMSE and MAE error metrics. Table 4.5 depicts the best hyperparameter configuration for Architecture I, for both datasets. What immediately stands out is the better performance of the candidate models when using the larger dataset. In fact, RMSE decreases about 30% when using the dataset With DA. This was already expected since the dataset with No DA was made of only 250 observations. Overall, for Architecture I with No DA the error is of approximately 8 units of measure. Since RMSE outputs an error in the same unit of the features that are being predicted by the model, it means that this Architecture is able to obtain the value of each personality trait with an error of 8 units. On the other hand, for Architecture I With DA,RMSE is of approximately 5.6 units of measure. It is also possible to discern that RMSE tends to be more stable when using the With DA dataset when compared to the No DA 123
CHAPTER 4. CITIZEN SENSING Table 4.5: Architecture I results with and without data augmentation, for each independent trial, with RMSE as metric. Hyperparameters described by letters as follows: a. number of estimators, b. eta, c. gamma, d. trees’ max depth, e. minimum child weight, and f. colsample by tree. Trial CV Split Best Score Evaluation Time (min) a. b. c. d. e. f. No Data Augmentation 1 1 7.813 8.078 3.8 300 0.05 0.04 4 6 0.2 1 2 8.015 7.560 3.8 300 0.05 0.02 4 4 0.2 1 3 8.203 7.512 3.7 300 0.01 0.04 4 4 0.2 2 1 8.024 7.594 3.7 300 0.10 0.08 4 8 0.2 2 2 8.184 7.161 3.7 300 0.05 0.02 4 8 0.2 2 3 7.847 7.961 3.7 300 0.05 0.04 4 8 0.2 With Data Augmentation 1 1 5.692 5.464 64.8 300 0.10 0.02 12 4 0.3 1 2 5.604 5.602 65.9 300 0.01 0.02 18 4 0.3 1 3 5.646 5.520 69.6 300 0.01 0.02 18 4 0.3 2 1 5.637 5.537 68.4 300 0.01 0.02 12 4 0.3 2 2 5.632 5.482 65.7 300 0.01 0.04 18 6 0.3 2 3 5.673 5.467 67.4 300 0.01 0.08 12 4 0.3 dataset, which shows higher error variance. In Table 4.5, the Evaluation column presents the error value of the best candidate model in the outer test fold. These values provide a second and stronger validation of the ability to classify of the best model. The hyperparameter tuning process is significantly faster for Architecture I with No DA, taking around 3.7 minutes to perform 700 fits and around 22 minutes to perform the full run. On the other hand, Architecture I With DA takes more than 1 hour to perform the same amount of fits, requiring more than 6.5 hours to complete. Overall, the models that behaved the best used 300 gradient boosted trees. Interestingly, when using the dataset with No DA, all models required 20% of the entire feature set when constructing each tree (colsample by tree) and used a maximum depth of 4 levels, building shallower trees, which helps controlling overfitting in the smaller dataset. On the other hand, when using the dataset With DA, the best models not only required 30% of the feature set but also required deeper trees, which indicate the need for more complex trees to find relations in the larger dataset. To strengthen this assertion, the learning rate is also smaller in Architecture I With DA allowing models to move slower through the gradient. Focusing the results obtained from testing in the test fold of the outer-split, Architecture I With DA presents a global RMSE of 5.512 and MAE of 3.979. On the other hand, Architecture I with No DA presents higher error values, with a global RMSE and MAE of 7.644 and 6.082, respectively. The fact that RMSE and MAE have relatively close values implies that not many outliers, or distant classifications, were provided by the models. It is also interesting to note that, independently of the dataset, Openness is the most difficult trait to classify. All these data are given by Table 4.6, where the MSE is also displayed, being used to compute the RMSE. 124
CHAPTER 4. CITIZEN SENSING Table 4.6: Evaluation results of Architecture I, with and without data augmentation, obtained from the test folds of the outer-split. Metric Global Extraversion Agreeableness Conscient. Stability Openness No Data Augmentation MAE 6.082 5.495 5.942 5.616 6.205 7.153 MSE 58.527 45.973 55.984 49.230 58.933 82.514 RMSE 7.644 6.778 7.468 7.000 7.668 9.061 With Data Augmentation MAE 3.979 3.937 4.071 3.832 3.798 4.259 MSE 30.385 29.529 31.630 28.813 27.069 34.884 RMSE 5.512 5.433 5.623 5.367 5.201 5.906 Figure 4.8 provides a graphical view of RMSE and MAE for Architecture I for both datasets, being possible to discern that both metrics present a lower error value when conceiving models over the augmented dataset. Figure 4.8: Graphical view of Architecture I RMSE and MAE for both datasets. 4.2.5.2 Architecture II - Big Five Bin Classifiers Architecture II candidate models, which classify personality traits in three bins (low, average, and high), were evaluated using several classification metrics. Table 4.7 depicts the best hyperparameter configuration for Architecture II, for the two datasets, using accuracy as metric. Again, models conceived over the dataset With DA outperform those conceived over the dataset with No DA, more than doubling the accuracy value. In addition, their evaluation values also tend to be more stable and less prone to variations. However, one may argue that the accuracy values attained by the candidate models and presented in Table 4.7 are low. Hence, it is of the utmost importance to assert that such accuracy values correspond to samples that had all five traits correctly classified. I.e., if one trait of a sample was wrongly classified 125
CHAPTER 4. CITIZEN SENSING then that sample would be considered as badly-classified even if the remaining four traits were correctly classified. To provide a stronger validation metric, Table 4.8 provides metrics based on traits’ accuracy instead of samples’ accuracy, presenting significantly higher values. Table 4.7: Architecture II results with and without data augmentation, for each independent trial, with sample accuracy as metric. Hyperparameters described by letters as follows: a. number of estimators, b. eta, c. gamma, d. trees’ max depth, e. minimum child weight, and f. colsample by tree. Trial CV Split Best Score Evaluation Time (min) a. b. c. d. e. f. No Data Augmentation 1 1 0.144 0.131 8.4 500 0.05 0.02 4 6 0.3 1 2 0.180 0.181 8.6 400 0.01 0.08 4 4 0.2 1 3 0.138 0.108 8.4 300 0.01 0.04 12 8 0.3 2 1 0.175 0.143 8.5 300 0.05 0.04 4 4 0.2 2 2 0.138 0.181 8.4 500 0.10 0.02 18 4 0.3 2 3 0.155 0.133 8.4 400 0.05 0.08 18 8 0.3 With Data Augmentation 1 1 0.458 0.486 128.6 300 0.10 0.02 12 4 0.3 1 2 0.464 0.466 130.1 300 0.01 0.08 12 4 0.3 1 3 0.453 0.468 133.6 400 0.10 0.08 12 4 0.2 2 1 0.465 0.490 129.4 300 0.10 0.02 18 4 0.3 2 2 0.466 0.466 123.6 300 0.01 0.04 12 4 0.3 2 3 0.448 0.480 125.3 500 0.10 0.08 18 4 0.2 It becomes clear that the tuning process is significantly faster for Architecture II with No DA, taking around 50 minutes to complete the process. On the other hand, when using the larger dataset, the process takes more than 12 hours to complete. Overall, models tend to use 300 gradient boosted trees and require 30% of the entire feature set per tree. The best classifiers also require deeper trees, with 12 or 18 levels. It is also worth mentioning that all the best models conceived over the dataset With DA required a minimum child weight of 4. This hyperparameter defines the minimum sum of weights of all observations required in a child node, being used to control overfitting and prevent under-fitting, which may happen if high values are used when setting this hyperparameter. As stated previously, all metrics provided in Table 4.8 are based on traits’ accuracy. Using class accuracy instead of sample accuracy, the mean error of Architecture II candidate models using the dataset With DA is of 0.165, which corresponds to an accuracy higher than 83%. On the other hand, the mean error with No DA increases to 0.338 (an accuracy of 66%). In this study, both micro and macro-averaged metrics were evaluated. However, since we are interested in maximizing the number of correct predictions each classifier makes, special importance is given to micro-averaging. In fact, micro f1-score of the classifiers conceived over the dataset With DA displays an interesting overall value of 0.835, with the Openness trait being, again, the one showing the lower value. It is worth mentioning that micro-averaging in a multi-class setting with all labels included, produces the same exact value for the f1-score, precision and recall metrics, being this the reason why Table 4.8 only 126
CHAPTER 4. CITIZEN SENSING Table 4.8: Evaluation results of Architecture II, with and without data augmentation, based on trait’s accuracy obtained from the test folds of the outer-split. Metric Global Extraversion Agree. Conscient. Stability Openness No Data Augmentation Mean Error 0.338 - - - - - Micro F1-Score 0.663 0.728 0.660 0.620 0.648 0.656 Macro F1-Score 0.459 0.532 0.462 0.419 0.443 0.438 Macro Precision 0.477 0.590 0.468 0.413 0.445 0.468 Macro Recall 0.464 0.525 0.469 0.434 0.447 0.447 With Data Augmentation Mean Error 0.165 - - - - - Micro F1-Score 0.835 0.846 0.834 0.831 0.843 0.822 Macro F1-Score 0.776 0.770 0.795 0.801 0.731 0.782 Macro Precision 0.830 0.826 0.854 0.840 0.809 0.819 Macro Recall 0.742 0.731 0.758 0.774 0.691 0.755 displays micro f1-score. On the other hand, macro-averaging computes each error metric independently for each class and then averages the metrics, treating all classes equally. Hence, since models depict a lower macro f1-score when compared to the micro one, this could mean that there may be some classes that are less used when classifying, such as low or high. Nonetheless, macro f1-score still presents a very interesting global value of 0.776. Macro-averaged precision also depicts a high value, strengthening the ability of models to correctly classify true positives and avoid false positives. Finally, models’ global macroaveraged recall is of 0.742, a promising value that tells us that the best candidate models are able, to some extent, to avoid false negatives. Figure 4.9 provides a graphical view of micro and macro-averaged f1-score and precision for Architecture II for both datasets, being again possible to recognize a better performance when using the dataset With DA. Figure 4.9: Graphical view of Architecture II micro and macro-averaged f1-score, and precision for both datasets. 127
CHAPTER 4. CITIZEN SENSING 4.2.5.3 Feature Importance Gradient Boosted Trees allow the possibility of estimating feature importance, i.e., a score that measures how useful each feature was when building the boosted trees. This importance was estimated using gain as importance type, which corresponds to the improvement in accuracy brought by a feature to the branches it is on. A higher value for a feature when compared to another implies it is more important for classifying the label. Figure 4.10 presents the estimated feature importance of Architecture I using an heat-map view. Interestingly, models conceived using the dataset with No DA (Figure 4.10a) give a higher importance to the selection of the adjective inefficient when classifying the Conscientiousness trait. Sloppy,disorganized, and careless are other adjectives that assume special relevance when classifying the same personality trait. Regarding the Extraversion trait, talkative,quiet, and withdrawn are the most important adjectives, being only then followed by the extroverted and energetic ones. The Agreeableness trait gives higher importance to distant,harsh,cold, and rude. On the other hand, feature importance is more uniform in the Stability and Openness personality traits, with the most important adjectives assuming a relative importance of about 7%. Another interesting fact that arises from these results, is that some adjectives have lower importance for all five traits. Examples include bashful,bold,intellectual, and jealous. As for the models conceived using the dataset With DA (Figure 4.10b), results are similar to the smaller (a) Using dataset with No DA. (b) Using dataset With DA. Figure 4.10: Feature importance heat-map of Architecture I. 128
CHAPTER 4. CITIZEN SENSING dataset. In these models, there is a lower number of important features, but the ones considered as important have stronger importance. An example is the case of the adjective talkative for the Extraversion trait, which increases its importance from 16% to 22%, and quiet, which increases from 11% to 17%. Withdrawn and energetic have a reduced importance. Interestingly, for the Agreeableness trait, the adjective kind becomes the most important one, increasing from 3.2% to 15%. The Openness trait still assumes a more uniform importance for all features, being this one of the reasons why it was the trait showing worst performance using Architecture I models. Regarding Architecture II, Figure 4.11 presents the estimated feature importance for both datasets. What immediately draws one attention is the fact that importance values are much more balanced when compared to Architecture I. Indeed, the highest importance value is of 9.1% with No DA and 13% With DA when compared to 20% and 22% of Architecture I, respectively. Nonetheless, except for a few exceptions, adjectives assuming higher importance in Architecture I also assume higher importance in Architecture II. The main difference is that values are closer together, having a lower amplitude. (a) Using dataset with No DA. (b) Using dataset With DA. Figure 4.11: Feature importance heat-map of Architecture II. 4.2.5.4 Summary The proposed ASAP method aims to use ML-based models to reinstate the process of rating adjectives or answering questions by an adjective selection process. To achieve this goal, two different ML architectures 129
CHAPTER 4. CITIZEN SENSING were proposed, experimented, and evaluated. The first architecture uses Gradient Boosted Trees regressors to quantify the Big Five personality traits. Overall, this architecture is able to quantify such traits with an error of approximately 5.5 units of measure, providing an accurate output given the limited amount of available records. On the other hand, Architecture II uses Gradient Boosted Trees classifiers to qualify the bin in which the subject stands, for each trait. This architecture was able to quantify the personality traits with a micro-averaged f1-score of more than 83%. A better performance of both architectures in the augmented dataset was also expected since the original dataset had a limited amount of records. The implemented data augmentation techniques aimed to increase the dataset size following well-defined rationales but also included several randomized decisions based on a probabilistic approach in order to reduce bias and create a more generalized version of the dataset. For this, data exploration and pattern mining, in the form of ARL, assumed an increased importance, allowing us to understand relations between selected adjectives. Results for records with very few adjectives selected may be biased to the dataset used to train the models since the ability to quantify traits based on the selection of just one or two adjectives is of an extreme difficulty. Hence, for the ASAP method to behave properly, subjects should be encouraged to select four, or more, adjectives. A further validation was carried out by means of a significance analysis between the correlation differences of predicted and actual scores. The best overall candidate model of Architecture I was trained using, as input data, 90% of the original dataset, with the remaining being used to obtain predictions. Predictions were compared with the actual scores of the five traits. As expected, the p-value returned a high value (0.968), with a z-score of 0.039. Such values tell, with a high degree of confidence, that the null hypothesis should be retained and that both correlation coefficients are not significantly different from each other. This is in line with expectations since the conceived models are optimizing a differentiable loss function, using a gradient descent procedure that reduces the model’s loss to increase the correlation between predictions and actual scores. Architecture II took significantly more time to fit than Architecture I. However, it provides more accurate results, which are less prone to error. It should be noted that Architecture II only provides an approximation to the Big Five of the subject, i.e., it does not numerically quantify each trait. Instead, it tells in which bin the subject finds himself. This can be useful in cases where the general qualification of each trait is more important than the specific score of the trait. On the other hand, Architecture I will provide an exact score for each personality trait based on a selection of adjectives. Indeed, the working hypothesis has been confirmed, i.e., it is possible to achieve promising performances using ML-based models where the subject, instead of rating forty adjectives or answering long questions, selects the adjectives he relates the most with (RQ4.1). This allows one to obtain the Big Five using a method with reduced complexity and that takes a small amount of time to complete. The obtained results are just estimates, with an underlying error. The conducted experiments showed the ability of ML-based models to compute estimates of personality traits, and should not be seen as a definitive psychological assessment of one’s personality traits. For a full personality assessment, tests such as the one proposed by Saucier, Goldberg, or the NEO-personality- inventory should be used. 130
CHAPTER 4. CITIZEN SENSING The use of augmented sets of data may bring an intrinsic bias to the candidate models. In all cases, preference should always be given to the collection and use of real data. However, in scenarios where data are extremely costly, an approximation may allow ML models to be analyzed with augmented data. In such scenarios, data augmentation processes should make use of several randomized decisions based on probabilistic approaches to create a generalized version of the smaller dataset. In Saucier’s test, each personality trait is computed using the rating of eight unipolar adjectives, i.e, no adjective is used for more than one personality trait. Indeed, it is known, beforehand, which adjectives are used by each trait. For example, the Extroversion trait is computed based on four positively weighted adjectives and four negative ones. However, in the proposed architectures that make the ASAP method, all 40 adjectives are used to compute all traits, allowing the ML models to use adjectives selection/nonselection to compute several traits, thus harnessing inter-trait relationships. For instance, bold, one of the adjectives used by Saucier to compute Extroversion, shows a smaller importance in the conceived architectures when quantifying Extroversion. The same happens for bashful in Extroversion,creative in Openness, and practical in Conscientiousness, just to point a few. This could lead us to hypothesize that, one, the list of forty adjectives could be further reduced to a smaller set of adjectives by removing those that are shown to have a smaller importance and that, two, there are adjectives that can be used to quantify distinct personality traits, such as the case of disorganized, which can be used for the Conscientiousness and the Agreeableness traits. It is also interesting to note the lack of features assuming high importance when quantifying Openness. In fact, one of its adjectives, ordinary, seems to assume higher importance in the Agreeableness trait. Overall, Saucier’s adjective-trait relations are being found and used by the conceived models. Since the conceived ML architectures proved to be both performant and efficient when using a selection of adjectives, future research points towards a reduction to the minimum required set of adjectives that do not harm the method’s accuracy, further reducing complexity and the time it takes to be performed by the subject [58]. 4.3 Boredom Detection Boredom is a subjective feeling that tends to emerge in situations where there is a lack of stimuli, being a state of relatively low arousal and dissatisfaction [233]. In other words, boredom may be a sign that an activity is not sufficiently satisfying neither motivating. Common sense tells us that, when bored, people tend to use their smartphone. Indeed, it is safe to assert that people tend to use their smartphone, if available, in situations where boredom arises. In addition, it has been reported that bored people tend to consume more, which makes them a better candidate to subscribe to promotional campaigns and engage with new content [234]. On the other hand, bored people could also make a more productive use of such idle moments. Hence, the conducted research aims to detect such feeling when using the smartphone, without any kind of biometric data and using only data from smartphones’ sensors and ML models. A research question has been elicited and stands as follows, viz. 131
CHAPTER 4. CITIZEN SENSING RQ4.2. Is it possible to accurately detect and predict boredom using ML models and smartphone’s sensors data? To achieve the proposed goal, it is of the utmost importance the existence of a dataset from where one could conceive and evaluate several candidate ML models. Hence, the next lines describe the conceived mobile application for data collection, with the user being queried, at specific intervals, how bored he felt during that same period. This labeling method is known as the Experience Sampling Method, i.e., a research method that probes participants to report on their thoughts or feelings on multiple occasions over time. The next lines will also go through the current state of the art regarding boredom detection, the collected dataset, and the results obtained from the conceived ML models. 4.3.1 State of the Art Literature reveals that researchers have already engaged in studying ways to measure and detect boredom as well as other feelings, such as stress [235,236], fatigue [237,238], or happiness [239]. Initial attempts to detect boredom focused on specific data collected by sensors that must be carried at all times for continuous monitoring, representing a major limitation [240]. Recent times came, however, with promising results regarding the use of computers and smartphones to detect boredom. In 2013, Bixler and D’Mello focused on the writing periods at a computer to predict boredom, using Decision Trees and Naive-Bayes classifiers, achieving promising results [240]. Their predictions were based on a set of values obtained with the help of a keystroke analysis, task appraisals, and personality traits. It should be noted that the Naive-Bayes classifier obtained an accuracy of 82% while the Decision Trees obtained a precision of 87% when trying to predict boredom. Still regarding computers, Guo et al. (2009) found, with the help of Support Vector Machines, that web interaction events, such as mouse movements or the number of clicks on a page, allow the prediction of whether a person is willing to be distracted, which may be indicative of boredom [241]. In 2019, Seo et al. developed ANNs to classify boredom using data from electroencephalography and galvanic skin response exams, achieving an accuracy of 79.98% [242]. A very similar study of the same authors focused only on data from electroencephalography exams, obtaining higher precision with a K-Nearest Neighbor based-model [243]. Considering smartphones, one important attempt has been made to use the smartphone’s data to predict user boredom. In 2015, Pielot et al. focused, among others, on what aspects of mobile phone usage are the most indicative of boredom. The authors developed a mobile application for data collection, which run for 14 days [244]. The collected data included, among others, user’s demographic and personal information. They framed the problem as a binary one, i.e., whether the user is bored or not. Three distinct classifiers were used, with Random Forests being the one showing the best accuracy (when compared to Logistic Regression and Support Vector Machines). On the other hand, the overhead between precision and recall is significant, since precision levels limited the recall to 30% [244]. Studies have also been carried out in relation to other feelings. Sano and Picard (2013) have reported good results for stress recognition using a combination of mobile devices and clothing-associated sensors, 132