Yap Sin Ning (23058016)
Stefan Ngan Phei Ern (17140440)
Lai Jie Xun (22083275)
Lai Cui Shan (23052059)
Vivian Su Kai Mei (23055849)
This project centers around a comprehensive analysis of a dataset containing detailed weather observations from various locations across Australia. The dataset, primarily focusing on daily weather metrics, provides insights into patterns of rainfall, temperature fluctuations, and other meteorological variables. By exploring and analyzing this data, we aim to uncover significant trends and characteristics of the Australian climate.
The dataset includes a wide range of weather parameters such as minimum and maximum temperature, rainfall, wind speed, humidity, and atmospheric pressure. These parameters are recorded on a daily basis, offering a granular view of weather patterns. Understanding these patterns is crucial for several applications, ranging from agricultural planning to urban development and climate research.
The primary objectives of this project are as follows:
To thoroughly examine the dataset to understand its structure, content, and quality. This includes identifying and addressing missing or inconsistent data, ensuring the dataset’s integrity for analysis.
To analyze historical weather data, particularly focusing on rainfall patterns, temperature variations, and other relevant climate indicators. This will involve identifying any long-term trends or significant anomalies in the data.
To identify and characterize typical climate patterns in different regions of Australia. This involves comparing weather parameters across different locations and timeframes.
To develop predictive models for forecasting weather conditions, particularly focusing on rainfall prediction. This would be beneficial for various sectors, including agriculture, disaster management, and environmental planning.
To create comprehensive visualizations of the analyzed data, aiding in the interpretation and communication of the findings. Visualizations will include graphs, charts, and maps to illustrate trends and patterns effectively.
Through these objectives, the project aims to provide valuable insights into the climatic conditions of Australia, supporting a range of environmental and socio-economic initiatives.
Features: 23
Observations: 145, 460
Access: provided by the rattle
package
More details: see https://www.kaggle.com/datasets/jsphyg/weather-dataset-rattle-package/data
Problem type: supervised binomial classification
Response variable: RainTomorrow (i.e.,
“Yes”, “No”)
Objective: use various meteorological features to predict if it will rain on the next day
Problem type: supervised regression
Response variable: Rainfall
Objective: use seasonal ARIMA model to predict the monthly rainfall
## Warning: package 'kableExtra' was built under R version 4.3.2
| Variable | Description | Type |
|---|---|---|
| Date | The date of observation | Date |
| Location | The common name of the location of the weather station | Nominal |
| MinTemp | The minimum temperature in degrees Celsius | Continuous |
| MaxTemp | The maximum temperature in degrees Celsius | Continuous |
| Rainfall | The amount of rainfall recorded for the day in mm | Continuous |
| Evaporation | The so-called Class A pan evaporation (mm) in the 24 hours to 9 am | Continuous |
| Sunshine | The number of hours of bright sunshine in the day | Continuous |
| WindGustDir | The direction of the strongest wind gust in the 24 hours to midnight | Nominal |
| WindGustSpeed | The speed (km/h) of the strongest wind gust in the 24 hours to midnight | Continuous |
| WindDir9am | Direction of the wind at 9 am | Nominal |
| WindDir3pm | Direction of the wind at 3 pm | Nominal |
| WindSpeed9am | Wind speed (km/hr) averaged over 10 minutes prior to 9 am | Continuous |
| WindSpeed3pm | Wind speed (km/hr) averaged over 10 minutes prior to 3 pm | Continuous |
| Humidity9am | Humidity (percent) at 9 am | Continuous |
| Humidity3pm | Humidity (percent) at 3 pm | Continuous |
| Pressure9am | Atmospheric pressure (hPa) reduced to mean sea level at 9 am | Continuous |
| Pressure3pm | Atmospheric pressure (hPa) reduced to mean sea level at 3 pm | Continuous |
| Cloud9am | Fraction of sky obscured by cloud at 9 am. Measured in ‘oktas’ (eighths) | Ordinal |
| Cloud3pm | Fraction of sky obscured by cloud at 3 pm. Measured in ‘oktas’ (eighths) | Ordinal |
| Temp9am | Temperature (degrees Celsius) at 9 am | Continuous |
| Temp3pm | Temperature (degrees Celsius) at 3 pm | Continuous |
| RainToday | Boolean: 1 if precipitation (mm) in the 24 hours to 9 am exceeds 1 mm, otherwise 0 | Binary |
| RainTomorrow | The amount of next day rain in mm. Used to create response variable RainTomorrow. A measure of risk | Binary |
Load all the required packages.
## Warning: package 'dplyr' was built under R version 4.3.2
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:kableExtra':
##
## group_rows
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
## Warning: package 'rattle' was built under R version 4.3.2
## Loading required package: tibble
## Warning: package 'tibble' was built under R version 4.3.2
## Loading required package: bitops
## Rattle: A free graphical interface for data science with R.
## Version 5.5.1 Copyright (c) 2006-2021 Togaware Pty Ltd.
## Type 'rattle()' to shake, rattle, and roll your data.
## Warning: package 'naniar' was built under R version 4.3.2
## Warning: package 'forcats' was built under R version 4.3.2
## Warning: package 'caret' was built under R version 4.3.2
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 4.3.2
## Loading required package: lattice
## Warning: package 'rsample' was built under R version 4.3.2
## Warning: package 'recipes' was built under R version 4.3.2
##
## Attaching package: 'recipes'
## The following object is masked from 'package:stats':
##
## step
## Warning: package 'glmnet' was built under R version 4.3.2
## Loading required package: Matrix
## Warning: package 'Matrix' was built under R version 4.3.2
##
## Attaching package: 'Matrix'
## The following object is masked from 'package:bitops':
##
## %&%
## Loaded glmnet 4.1-8
##
## Attaching package: 'kernlab'
## The following object is masked from 'package:ggplot2':
##
## alpha
## Warning: package 'randomForest' was built under R version 4.3.2
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
##
## margin
## The following object is masked from 'package:rattle':
##
## importance
## The following object is masked from 'package:dplyr':
##
## combine
## Warning: package 'lubridate' was built under R version 4.3.2
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
## Warning: package 'readr' was built under R version 4.3.2
## Warning: package 'pROC' was built under R version 4.3.2
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
## Warning: package 'forecast' was built under R version 4.3.2
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
## Warning: package 'tseries' was built under R version 4.3.2
## Warning: package 'zoo' was built under R version 4.3.2
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
Load the data.
# specify the full path to the CSV file
file_path <- 'C:/Users/cuish/OneDrive/Documents/Master of Data Science/WQD7004 Programming for Data Science/7004 Assignment/weatherAUS.csv'
# read the CSV file
df <- read.csv(file_path)
Examine the dimensions of the data set.
# check the number of rows and columns in the data set
dim(df)
## [1] 145460 23
Observation:
Examine the structure of the data set.
# get a summary of the data in the data set
glimpse(df)
## Rows: 145,460
## Columns: 23
## $ Date <chr> "2008-12-01", "2008-12-02", "2008-12-03", "2008-12-04", …
## $ Location <chr> "Albury", "Albury", "Albury", "Albury", "Albury", "Albur…
## $ MinTemp <dbl> 13.4, 7.4, 12.9, 9.2, 17.5, 14.6, 14.3, 7.7, 9.7, 13.1, …
## $ MaxTemp <dbl> 22.9, 25.1, 25.7, 28.0, 32.3, 29.7, 25.0, 26.7, 31.9, 30…
## $ Rainfall <dbl> 0.6, 0.0, 0.0, 0.0, 1.0, 0.2, 0.0, 0.0, 0.0, 1.4, 0.0, 2…
## $ Evaporation <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, …
## $ Sunshine <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, …
## $ WindGustDir <chr> "W", "WNW", "WSW", "NE", "W", "WNW", "W", "W", "NNW", "W…
## $ WindGustSpeed <int> 44, 44, 46, 24, 41, 56, 50, 35, 80, 28, 30, 31, 61, 44, …
## $ WindDir9am <chr> "W", "NNW", "W", "SE", "ENE", "W", "SW", "SSE", "SE", "S…
## $ WindDir3pm <chr> "WNW", "WSW", "WSW", "E", "NW", "W", "W", "W", "NW", "SS…
## $ WindSpeed9am <int> 20, 4, 19, 11, 7, 19, 20, 6, 7, 15, 17, 15, 28, 24, 4, N…
## $ WindSpeed3pm <int> 24, 22, 26, 9, 20, 24, 24, 17, 28, 11, 6, 13, 28, 20, 30…
## $ Humidity9am <int> 71, 44, 38, 45, 82, 55, 49, 48, 42, 58, 48, 89, 76, 65, …
## $ Humidity3pm <int> 22, 25, 30, 16, 33, 23, 19, 19, 9, 27, 22, 91, 93, 43, 3…
## $ Pressure9am <dbl> 1007.7, 1010.6, 1007.6, 1017.6, 1010.8, 1009.2, 1009.6, …
## $ Pressure3pm <dbl> 1007.1, 1007.8, 1008.7, 1012.8, 1006.0, 1005.4, 1008.2, …
## $ Cloud9am <int> 8, NA, NA, NA, 7, NA, 1, NA, NA, NA, NA, 8, 8, NA, NA, 0…
## $ Cloud3pm <int> NA, NA, 2, NA, 8, NA, NA, NA, NA, NA, NA, 8, 8, 7, NA, N…
## $ Temp9am <dbl> 16.9, 17.2, 21.0, 18.1, 17.8, 20.6, 18.1, 16.3, 18.3, 20…
## $ Temp3pm <dbl> 21.8, 24.3, 23.2, 26.5, 29.7, 28.9, 24.6, 25.5, 30.2, 28…
## $ RainToday <chr> "No", "No", "No", "No", "No", "No", "No", "No", "No", "Y…
## $ RainTomorrow <chr> "No", "No", "No", "No", "No", "No", "No", "No", "Yes", "…
Observation:
The Date column is currently represented as
chr (character). To enhance temporal analysis, it will be
converted to the date data type during data cleaning for
easier manipulation and interpretation of temporal information.
Columns like Evaporation, Sunshine,
WindSpeed9am, Cloud9am, Cloud3pm
contain missing values (NA). Appropriate steps will be
taken during data cleaning, which may involve imputation strategies or
handling missing values based on the nature of each column.
The response variable RainTomorrow is currently
represented as chr. To facilitate modeling and analysis, it
will be converted to a fct. This is important for binary
classification tasks, as factors provide a more efficient representation
of categorical variables in R.
Columns like Location, WindGustDir,
WindDir9am, WindDir3pm, RainToday
are currently represented as ‘chr’ and likely contain categorical
information. These columns will be converted to fct or
encoded appropriately during data cleaning to facilitate modeling and
analysis.
The columns Cloud9am and Cloud3pm
represents the fraction of the sky obscured by clouds, measured in
‘oktas’, which are units of eights. The values range from 0 (indicating
completely clear sky) to 9 (indicating a completely overcast sky). Since
the values are discrete and represents a limited set of possibilities,
these variables should be converted to the fct data type to
better reflect their categorical nature. This conversion will facilitate
analysis and modeling by treating the values as distinct categories
rather than continuous numerical values.
Standardize naming conventions across all columns with snake case for improved consistency and clarity in column names.
Before standardizing naming conventions:
# get the names of all columns in the data frame
names(df)
## [1] "Date" "Location" "MinTemp" "MaxTemp"
## [5] "Rainfall" "Evaporation" "Sunshine" "WindGustDir"
## [9] "WindGustSpeed" "WindDir9am" "WindDir3pm" "WindSpeed9am"
## [13] "WindSpeed3pm" "Humidity9am" "Humidity3pm" "Pressure9am"
## [17] "Pressure3pm" "Cloud9am" "Cloud3pm" "Temp9am"
## [21] "Temp3pm" "RainToday" "RainTomorrow"
Standardizing naming conventions
# normalize the variable names
names(df) %>%
normVarNames() -> names(df)
After standardizing naming conventions:
# get the names of all columns in the data frame
names(df)
## [1] "date" "location" "min_temp" "max_temp"
## [5] "rainfall" "evaporation" "sunshine" "wind_gust_dir"
## [9] "wind_gust_speed" "wind_dir_9am" "wind_dir_3pm" "wind_speed_9am"
## [13] "wind_speed_3pm" "humidity_9am" "humidity_3pm" "pressure_9am"
## [17] "pressure_3pm" "cloud_9am" "cloud_3pm" "temp_9am"
## [21] "temp_3pm" "rain_today" "rain_tomorrow"
Examine the content of the data set to gain an initial understanding before delving into more in-depth exploration and analysis.
# preview the data in the data frame
head(df)
## date location min_temp max_temp rainfall evaporation sunshine
## 1 2008-12-01 Albury 13.4 22.9 0.6 NA NA
## 2 2008-12-02 Albury 7.4 25.1 0.0 NA NA
## 3 2008-12-03 Albury 12.9 25.7 0.0 NA NA
## 4 2008-12-04 Albury 9.2 28.0 0.0 NA NA
## 5 2008-12-05 Albury 17.5 32.3 1.0 NA NA
## 6 2008-12-06 Albury 14.6 29.7 0.2 NA NA
## wind_gust_dir wind_gust_speed wind_dir_9am wind_dir_3pm wind_speed_9am
## 1 W 44 W WNW 20
## 2 WNW 44 NNW WSW 4
## 3 WSW 46 W WSW 19
## 4 NE 24 SE E 11
## 5 W 41 ENE NW 7
## 6 WNW 56 W W 19
## wind_speed_3pm humidity_9am humidity_3pm pressure_9am pressure_3pm cloud_9am
## 1 24 71 22 1007.7 1007.1 8
## 2 22 44 25 1010.6 1007.8 NA
## 3 26 38 30 1007.6 1008.7 NA
## 4 9 45 16 1017.6 1012.8 NA
## 5 20 82 33 1010.8 1006.0 7
## 6 24 55 23 1009.2 1005.4 NA
## cloud_3pm temp_9am temp_3pm rain_today rain_tomorrow
## 1 NA 16.9 21.8 No No
## 2 NA 17.2 24.3 No No
## 3 2 21.0 23.2 No No
## 4 NA 18.1 26.5 No No
## 5 8 17.8 29.7 No No
## 6 NA 20.6 28.9 No No
Conduct a descriptive analysis to summarize and comprehend key characteristics of the dataset, including measures of central tendency, dispersion, and distribution for numerical variables, as well as frequency distributions for categorical variables.
# generate a summary of the main characteristics of the data
summary(df)
## date location min_temp max_temp
## Length:145460 Length:145460 Min. :-8.50 Min. :-4.80
## Class :character Class :character 1st Qu.: 7.60 1st Qu.:17.90
## Mode :character Mode :character Median :12.00 Median :22.60
## Mean :12.19 Mean :23.22
## 3rd Qu.:16.90 3rd Qu.:28.20
## Max. :33.90 Max. :48.10
## NA's :1485 NA's :1261
## rainfall evaporation sunshine wind_gust_dir
## Min. : 0.000 Min. : 0.00 Min. : 0.00 Length:145460
## 1st Qu.: 0.000 1st Qu.: 2.60 1st Qu.: 4.80 Class :character
## Median : 0.000 Median : 4.80 Median : 8.40 Mode :character
## Mean : 2.361 Mean : 5.47 Mean : 7.61
## 3rd Qu.: 0.800 3rd Qu.: 7.40 3rd Qu.:10.60
## Max. :371.000 Max. :145.00 Max. :14.50
## NA's :3261 NA's :62790 NA's :69835
## wind_gust_speed wind_dir_9am wind_dir_3pm wind_speed_9am
## Min. : 6.00 Length:145460 Length:145460 Min. : 0.00
## 1st Qu.: 31.00 Class :character Class :character 1st Qu.: 7.00
## Median : 39.00 Mode :character Mode :character Median : 13.00
## Mean : 40.03 Mean : 14.04
## 3rd Qu.: 48.00 3rd Qu.: 19.00
## Max. :135.00 Max. :130.00
## NA's :10263 NA's :1767
## wind_speed_3pm humidity_9am humidity_3pm pressure_9am
## Min. : 0.00 Min. : 0.00 Min. : 0.00 Min. : 980.5
## 1st Qu.:13.00 1st Qu.: 57.00 1st Qu.: 37.00 1st Qu.:1012.9
## Median :19.00 Median : 70.00 Median : 52.00 Median :1017.6
## Mean :18.66 Mean : 68.88 Mean : 51.54 Mean :1017.6
## 3rd Qu.:24.00 3rd Qu.: 83.00 3rd Qu.: 66.00 3rd Qu.:1022.4
## Max. :87.00 Max. :100.00 Max. :100.00 Max. :1041.0
## NA's :3062 NA's :2654 NA's :4507 NA's :15065
## pressure_3pm cloud_9am cloud_3pm temp_9am
## Min. : 977.1 Min. :0.00 Min. :0.00 Min. :-7.20
## 1st Qu.:1010.4 1st Qu.:1.00 1st Qu.:2.00 1st Qu.:12.30
## Median :1015.2 Median :5.00 Median :5.00 Median :16.70
## Mean :1015.3 Mean :4.45 Mean :4.51 Mean :16.99
## 3rd Qu.:1020.0 3rd Qu.:7.00 3rd Qu.:7.00 3rd Qu.:21.60
## Max. :1039.6 Max. :9.00 Max. :9.00 Max. :40.20
## NA's :15028 NA's :55888 NA's :59358 NA's :1767
## temp_3pm rain_today rain_tomorrow
## Min. :-5.40 Length:145460 Length:145460
## 1st Qu.:16.60 Class :character Class :character
## Median :21.10 Mode :character Mode :character
## Mean :21.68
## 3rd Qu.:26.40
## Max. :46.70
## NA's :3609
date Column to date
Type# convert `date` column to `date` type
df$date <- as.Date(df$date)
range(df$date)
## [1] "2007-11-01" "2017-06-25"
rain_tomorrow to fct# convert `rain_tomorrow` column to `fct` type
df <- df %>%
mutate(rain_tomorrow = as.factor(rain_tomorrow))
chr Columns to fctInspect Unique Levels
Check the unique levels in each chr categorical column
for potential misspelled or similar levels that might represent the same
category.
# create a logical vector `chr_col` indicating which columns in the `df` are of `chr` type
chr_col <- sapply(df, is.character)
# inspect unique levels for all `chr` columns
unique_levels <- lapply(df[, chr_col, drop = FALSE], unique)
# print unique levels for each `chr` column
for (col in names(unique_levels)) {
cat('Column: ', col, '\n')
print(unique_levels[[col]])
cat('\n')
}
## Column: location
## [1] "Albury" "BadgerysCreek" "Cobar" "CoffsHarbour"
## [5] "Moree" "Newcastle" "NorahHead" "NorfolkIsland"
## [9] "Penrith" "Richmond" "Sydney" "SydneyAirport"
## [13] "WaggaWagga" "Williamtown" "Wollongong" "Canberra"
## [17] "Tuggeranong" "MountGinini" "Ballarat" "Bendigo"
## [21] "Sale" "MelbourneAirport" "Melbourne" "Mildura"
## [25] "Nhil" "Portland" "Watsonia" "Dartmoor"
## [29] "Brisbane" "Cairns" "GoldCoast" "Townsville"
## [33] "Adelaide" "MountGambier" "Nuriootpa" "Woomera"
## [37] "Albany" "Witchcliffe" "PearceRAAF" "PerthAirport"
## [41] "Perth" "SalmonGums" "Walpole" "Hobart"
## [45] "Launceston" "AliceSprings" "Darwin" "Katherine"
## [49] "Uluru"
##
## Column: wind_gust_dir
## [1] "W" "WNW" "WSW" "NE" "NNW" "N" "NNE" "SW" NA "ENE" "SSE" "S"
## [13] "NW" "SE" "ESE" "E" "SSW"
##
## Column: wind_dir_9am
## [1] "W" "NNW" "SE" "ENE" "SW" "SSE" "S" "NE" NA "SSW" "N" "WSW"
## [13] "ESE" "E" "NW" "WNW" "NNE"
##
## Column: wind_dir_3pm
## [1] "WNW" "WSW" "E" "NW" "W" "SSE" "ESE" "ENE" "NNW" "SSW" "SW" "SE"
## [13] "N" "S" "NNE" NA "NE"
##
## Column: rain_today
## [1] "No" "Yes" NA
Observation:
No misspelled or similar levels observed; therefore, these columns will be converted to factors for further analysis.
However, an inherent order is observed in the columns
wind_gust_dir, wind_dir_9am,
wind_dir_3pm, cloud_9am,
cloud_3pm, so they will be converted to ordered
factors.
Columns like wind_gust_dir,
wind_dir_9am, wind_dir_3pm,
rain_today have missing values (NA) that need
to be addressed during the data cleaning process. Appropriate
strategies, such as imputation or handling based on the nature of the
column, will be applied to address these missing values.
Convert chr Columns to
fct
# identify columns of `chr` type
chr_col <- sapply(df, is.character)
# convert `chr` columns to `fct` type
df <- df %>%
mutate(across(all_of(names(unique_levels)), as.factor))
wind_gust_dir,
wind_dir_9am, wind_dir_3pm,
cloud_9am, cloud_3pm to ord# specify the ordinal columns
ord_col <- c('wind_gust_dir', 'wind_dir_9am', 'wind_dir_3pm', 'cloud_9am', 'cloud_3pm')
# convert specified ordinal columns to ordered factors
df <- df %>%
mutate(across(all_of(ord_col), as.ordered))
Examine the structure of the data set after data type transformation.
# get a summary of the data in the data set
glimpse(df)
## Rows: 145,460
## Columns: 23
## $ date <date> 2008-12-01, 2008-12-02, 2008-12-03, 2008-12-04, 2008-…
## $ location <fct> Albury, Albury, Albury, Albury, Albury, Albury, Albury…
## $ min_temp <dbl> 13.4, 7.4, 12.9, 9.2, 17.5, 14.6, 14.3, 7.7, 9.7, 13.1…
## $ max_temp <dbl> 22.9, 25.1, 25.7, 28.0, 32.3, 29.7, 25.0, 26.7, 31.9, …
## $ rainfall <dbl> 0.6, 0.0, 0.0, 0.0, 1.0, 0.2, 0.0, 0.0, 0.0, 1.4, 0.0,…
## $ evaporation <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
## $ sunshine <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
## $ wind_gust_dir <ord> W, WNW, WSW, NE, W, WNW, W, W, NNW, W, N, NNE, W, SW, …
## $ wind_gust_speed <int> 44, 44, 46, 24, 41, 56, 50, 35, 80, 28, 30, 31, 61, 44…
## $ wind_dir_9am <ord> W, NNW, W, SE, ENE, W, SW, SSE, SE, S, SSE, NE, NNW, W…
## $ wind_dir_3pm <ord> WNW, WSW, WSW, E, NW, W, W, W, NW, SSE, ESE, ENE, NNW,…
## $ wind_speed_9am <int> 20, 4, 19, 11, 7, 19, 20, 6, 7, 15, 17, 15, 28, 24, 4,…
## $ wind_speed_3pm <int> 24, 22, 26, 9, 20, 24, 24, 17, 28, 11, 6, 13, 28, 20, …
## $ humidity_9am <int> 71, 44, 38, 45, 82, 55, 49, 48, 42, 58, 48, 89, 76, 65…
## $ humidity_3pm <int> 22, 25, 30, 16, 33, 23, 19, 19, 9, 27, 22, 91, 93, 43,…
## $ pressure_9am <dbl> 1007.7, 1010.6, 1007.6, 1017.6, 1010.8, 1009.2, 1009.6…
## $ pressure_3pm <dbl> 1007.1, 1007.8, 1008.7, 1012.8, 1006.0, 1005.4, 1008.2…
## $ cloud_9am <ord> 8, NA, NA, NA, 7, NA, 1, NA, NA, NA, NA, 8, 8, NA, NA,…
## $ cloud_3pm <ord> NA, NA, 2, NA, 8, NA, NA, NA, NA, NA, NA, 8, 8, 7, NA,…
## $ temp_9am <dbl> 16.9, 17.2, 21.0, 18.1, 17.8, 20.6, 18.1, 16.3, 18.3, …
## $ temp_3pm <dbl> 21.8, 24.3, 23.2, 26.5, 29.7, 28.9, 24.6, 25.5, 30.2, …
## $ rain_today <fct> No, No, No, No, No, No, No, No, No, Yes, No, Yes, Yes,…
## $ rain_tomorrow <fct> No, No, No, No, No, No, No, No, Yes, No, Yes, Yes, Yes…
Examine the missing values of the data set.
# print the entire summary of missing values table
miss_var_summary(df)
## # A tibble: 23 × 3
## variable n_miss pct_miss
## <chr> <int> <dbl>
## 1 sunshine 69835 48.0
## 2 evaporation 62790 43.2
## 3 cloud_3pm 59358 40.8
## 4 cloud_9am 55888 38.4
## 5 pressure_9am 15065 10.4
## 6 pressure_3pm 15028 10.3
## 7 wind_dir_9am 10566 7.26
## 8 wind_gust_dir 10326 7.10
## 9 wind_gust_speed 10263 7.06
## 10 humidity_3pm 4507 3.10
## # ℹ 13 more rows
In the process of preparing our dataset for analysis, we have implemented a data cleaning step to address columns with a significant percentage of missing values. The goal is to enhance the quality and reliability of our data by removing features where a substantial portion of information is absent.
We established a threshold for missing data, defining a limit beyond which columns would be considered for removal. The chosen threshold was set at 50%, meaning that any column with missing values exceeding this threshold would be dropped from the dataset.
# Dropping columns with a high percentage of missing values
threshold <- 0.5 # 50% threshold for missing data
df <- df[, colMeans(is.na(df)) < threshold]
rain_tomorrow and
rainfall
The response variable of problem 1, rain_tomorrow,
indicates whether it will rain on the next day. Rows with missing values
in the response variable constitute only 2.25% of the data set, and
removing them will not impact the overall analysis. Since predicting the
occurrence of rainfall is the central objective of this analysis,
instances where this information is unavailable cannot contribute
meaningfully to the predictive modeling task.
Similarly, for problem 2, the response variable is
rainfall, and rows with missing values in this variable
constitute only 2.24% of the data set.
Given that these percentages are relatively small, removing records with missing values in the response variables ensures the accuracy and relevance of the analysis by addressing the impossibility of predicting the target variable when the information is unavailable.
Remove rows with missing values in the response variable.
# remove rows with missing values in the response variable
df <- df %>%
filter(complete.cases(rain_tomorrow, rainfall))
Examine the missing values of the data set after removing rows with missing values in the response variables.
# print the entire summary of missing values table
miss_var_summary(df)
## # A tibble: 23 × 3
## variable n_miss pct_miss
## <chr> <int> <dbl>
## 1 sunshine 66805 47.5
## 2 evaporation 59694 42.4
## 3 cloud_3pm 56094 39.8
## 4 cloud_9am 52625 37.4
## 5 pressure_3pm 13769 9.78
## 6 pressure_9am 13743 9.76
## 7 wind_dir_9am 9660 6.86
## 8 wind_gust_dir 9163 6.51
## 9 wind_gust_speed 9105 6.47
## 10 wind_dir_3pm 3670 2.61
## # ℹ 13 more rows
sunshine
Missing values in sunshine may indicate periods with no
measurable bright sunshine. Therefore, the strategy is to fill missing
values in sunshine with 0, assuming that no sunshine was
recorded during those observations.
# fill missing values in `sunshine` with 0
df <- df %>%
mutate(sunshine = ifelse(is.na(sunshine), 0, sunshine))
cloud_3pm and
cloud_9am
Missing values in cloud cover (cloud_3pm,
cloud_9am) may indicate clear sky. Thus, the strategy is to
fill missing values in cloud cover columns with 0, assuming clear sky
during those observations.
# fill missing values in the cloud cover columns with 0
df <- df %>%
mutate(
cloud_3pm = fct_explicit_na(cloud_3pm, "0"),
cloud_9am = fct_explicit_na(cloud_9am, "0")
)
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `cloud_3pm = fct_explicit_na(cloud_3pm, "0")`.
## Caused by warning:
## ! `fct_explicit_na()` was deprecated in forcats 1.0.0.
## ℹ Please use `fct_na_value_to_level()` instead.
evaporation
Missing values in evaporation may indicate periods with
no recorded evaporation. Hence, the strategy is to fill missing values
in evaporation with 0, assuming that no evaporation was
recorded during certain weather conditions, such as period of low
humidity or no wind.
# fill missing values in the `evaporation` with 0
df <- df %>%
mutate(evaporation = ifelse(is.na(evaporation), 0, evaporation))
wind_gust_speed, wind_speed_9am,
and wind_speed_3pm
Missing values in wind speed-related variables may indicate periods with no recorded wind. Thus, the strategy is to fill missing values in wind speed columns with 0, assuming that no wind was recorded (calm conditions).
# fill missing values in the wind speed columns with 0
df <- df %>%
mutate(
wind_gust_speed = ifelse(is.na(wind_gust_speed), 0, wind_gust_speed),
wind_speed_3pm = ifelse(is.na(wind_speed_3pm), 0, wind_speed_3pm),
wind_speed_9am = ifelse(is.na(wind_speed_9am), 0, wind_speed_9am)
)
pressure_3pm and
pressure_9am
Missing values in pressure_3pm and
pressure_9am may occur due to various reasons, and we
assume that the missing values are missing completely at random (MCAR).
Therefore, the strategy is to fill missing values with the mean of their
respective columns.
# mean imputation for pressure columns
df <- df %>%
mutate(
pressure_3pm = ifelse(is.na(pressure_3pm), mean(pressure_3pm, na.rm = TRUE), pressure_3pm),
pressure_9am = ifelse(is.na(pressure_9am), mean(pressure_9am, na.rm = TRUE), pressure_9am)
)
humidity_3pm and
humidity_9am
Missing values in humidity_3pm and
humidity_9am may occur due to various reasons, and the
assumption is made that the missing values are MCAR, so the missing
values will be imputed using the mean humidity for their respective
columns.
# mean imputation for humidity columns
df <- df %>%
mutate(
humidity_3pm = ifelse(is.na(humidity_3pm), mean(humidity_3pm, na.rm = TRUE), humidity_3pm),
humidity_9am = ifelse(is.na(humidity_9am), mean(humidity_9am, na.rm = TRUE), humidity_9am)
)
temp_3pm, temp_9am,
min_temp, and max_temp
Missing values in temperature-related variables may occur for various reasons, and the assumption is made that the missing values are MCAR. The missing values will be imputed using the mean temperature for their respective columns.
# mean imputation for temperature columns
df <- df %>%
mutate(
temp_3pm = ifelse(is.na(temp_3pm), mean(temp_3pm, na.rm = TRUE), temp_3pm),
temp_9am = ifelse(is.na(temp_9am), mean(temp_9am, na.rm = TRUE), temp_9am),
min_temp = ifelse(is.na(min_temp), mean(min_temp, na.rm = TRUE), min_temp),
max_temp = ifelse(is.na(max_temp), mean(max_temp, na.rm = TRUE), max_temp)
)
wind_dir_9am, wind_gust_dir and
wind_dir_3pm
Missing values in wind direction variables wind_dir_9am,
wind_gust_dir and wind_dir_3pm may occur when
there is no wind recorded during the respective time periods. Hence, the
strategy is to fill missing values in wind direction variables with a
label ND indicating no direction to convey the absence of
wind.
# specify the columns to fill missing values
wind_dir <- c('wind_dir_9am', 'wind_gust_dir', 'wind_dir_3pm')
# specify the levels of the wind directions
wind_dir_lvls <- c('N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'ND')
# fill missing values in wind direction variables with 'ND'
df <- df %>%
mutate(
wind_dir_9am = fct_explicit_na(wind_dir_9am, 'ND'),
wind_gust_dir = fct_explicit_na(wind_gust_dir, 'ND'),
wind_dir_3pm = fct_explicit_na(wind_dir_3pm, 'ND')
) %>%
mutate(across(all_of(wind_dir), ~factor(., levels = wind_dir_lvls)))
Examine the missing values of the data set after imputing rows with missing values.
# print the entire summary of missing values table
miss_var_summary(df)
## # A tibble: 23 × 3
## variable n_miss pct_miss
## <chr> <int> <dbl>
## 1 date 0 0
## 2 location 0 0
## 3 min_temp 0 0
## 4 max_temp 0 0
## 5 rainfall 0 0
## 6 evaporation 0 0
## 7 sunshine 0 0
## 8 wind_gust_dir 0 0
## 9 wind_gust_speed 0 0
## 10 wind_dir_9am 0 0
## # ℹ 13 more rows
Observation:
Identify and remove any duplicate rows in the data set to ensure data integrity and enhance analysis accuracy.
# identify duplicate rows
df[duplicated(df), ]
## [1] date location min_temp max_temp
## [5] rainfall evaporation sunshine wind_gust_dir
## [9] wind_gust_speed wind_dir_9am wind_dir_3pm wind_speed_9am
## [13] wind_speed_3pm humidity_9am humidity_3pm pressure_9am
## [17] pressure_3pm cloud_9am cloud_3pm temp_9am
## [21] temp_3pm rain_today rain_tomorrow
## <0 rows> (or 0-length row.names)
Observation:
# identify numerical columns
num_col <- sapply(df, is.numeric)
# initialize an empty data frame to store outlier counts
outliers_summary <- data.frame(Column = character(0), IQR_Outliers = integer(0))
# loop through each numerical column
for (col in names(df)[num_col]) {
# calculate the IQR
Q1 <- quantile(df[[col]], 0.25, na.rm = TRUE)
Q3 <- quantile(df[[col]], 0.75, na.rm = TRUE)
IQR <- Q3 - Q1
# identify outliers using the IQR method
outliers_iqr <- df[[col]] < (Q1 - 1.5 * IQR) | df[[col]] > (Q3 + 1.5 * IQR)
# count the number of outliers and append to the summary dataframe
outliers_count <- sum(outliers_iqr, na.rm = TRUE)
outliers_summary <- rbind(outliers_summary, data.frame(Column = col, IQR_Outliers = outliers_count))
}
# display the summary
outliers_summary
## Column IQR_Outliers
## 1 min_temp 61
## 2 max_temp 437
## 3 rainfall 25228
## 4 evaporation 2742
## 5 sunshine 0
## 6 wind_gust_speed 12812
## 7 wind_speed_9am 1715
## 8 wind_speed_3pm 1254
## 9 humidity_9am 1414
## 10 humidity_3pm 0
## 11 pressure_9am 2687
## 12 pressure_3pm 2286
## 13 temp_9am 290
## 14 temp_3pm 814
Reasons to retain outliers in the data set:
Capturing natural variability: Outliers might be represent extreme weather conditions that are crucial for accurate rain prediction. Retaining them ensures capturing the natural variability in weather patterns.
Preserving rare events: Outliers could correspond to rare but significant meteorologic events. Keeping them intact avoids the risk of oversimplifying the rain prediction model by removing valuable information.
# create a true copy of the data frame
df_copy <- data.frame(df) # unaltered copy for reference
df_cleaned <- data.frame(df) # intended for further processing
# save the dataset to a CSV file
write.csv(df, 'C:/Users/cuish/OneDrive/Documents/Master of Data Science/WQD7004 Programming for Data Science/7004 Assignment/weatherAUS_cleaned.csv', row.names = FALSE)
# extract start and end dates
start_date <- min(df$date)
end_date <- max(df$date)
# specify the column
wind_dir_plots <- c('wind_gust_dir', 'wind_dir_9am', 'wind_dir_3pm')
# create separate plots for each wind direction column
plots_list <- lapply(wind_dir_plots, function(col) {
ggplot(df %>% filter(.data[[col]] != 'ND'), aes(x = .data[[col]], fill = .data[[col]])) +
geom_bar(stat = 'count', width = 1, color = 'black', linewidth = 0.1, alpha = 0.5) + coord_polar(theta = 'x', start = -11 / 180 * pi, direction = 1) +
scale_fill_discrete(limits = wind_dir_lvls) +
ggtitle(paste(' Frequency of Wind Direction', '\n', start_date, 'to', end_date)) +
xlab(paste(toTitleCase(gsub('_', ' ', col)))) +
ylab('') +
guides(fill = guide_legend(title = 'Wind Direction')) +
theme(axis.text.y = element_blank(), axis.ticks = element_blank())
})
# view the plots
for (i in seq_along(plots_list)) {
print(plots_list[[i]])
}
Examining the rose plots reveals a predominant wind gust direction favoring the North, West, and South-East. At 9 am, the wind predominantly blows from the North and exhibits its weakest presence in the East-South-East. Conversely, by 3 pm, the wind prominently shifts towards the South-East, with the least occurrence observed in the East-North-East direction.
# extract Year and Month information
df <- df %>%
mutate(year = year(date),
month = month(date, label = TRUE, abbr = FALSE))
# group by year and month, calculate average rainfall
avg_rainfall <- df %>%
group_by(year, month) %>%
summarize(AvgRainfall = mean(rainfall, na.rm = TRUE))
## `summarise()` has grouped output by 'year'. You can override using the
## `.groups` argument.
# create separate plots for each year using facet_wrap
ggplot(avg_rainfall, aes(x = month, y = AvgRainfall, group = year, color = as.factor(year))) +
geom_line() +
geom_point() +
labs(title = "Average Rainfall for Each Month Each Year",
x = "Month",
y = "Average Rainfall") +
theme_minimal() +
scale_x_discrete(labels = month.name) +
scale_color_discrete(name = "year") +
facet_wrap(~year)
The historical rainfall patterns exhibit a consistent trend of heightened precipitation at the beginning of the year, with February 2008 standing out as the peak month. However, a peculiar deviation from this norm emerges in 2016. Rather than adhering to the expected surge in the initial months, rainfall in 2016 exhibits an unconventional decrease, reaching its climax in June. This divergence from the historical pattern raises a pertinent flag, signaling a potential impact of climate change on our local weather dynamics.
Conversely, as the year draws to a close, a discernible reduction in rainfall is observed. This can be attributed to the seasonal transition of Australia, where the culmination of the year aligns with the summer season, typically characterized by diminished precipitation.
# group by Year and Month, calculate average rainfall and temperature
avg_data <- df %>%
group_by(year, month) %>%
summarize(AvgRainfall = mean(rainfall, na.rm = TRUE),
AvgTemp = mean((min_temp + max_temp) / 2, na.rm = TRUE))
## `summarise()` has grouped output by 'year'. You can override using the
## `.groups` argument.
# create a plot for both temperature lines and rainfall bars
ggplot(avg_data, aes(x = month)) +
geom_bar(aes(y = AvgRainfall, fill = as.factor(year)), stat = "identity", position = "dodge", width = 0.7) +
geom_line(aes(y = AvgTemp, group = year, color = as.factor(year)), size = 0.5) +
geom_point(aes(y = AvgTemp, color = as.factor(year)), size = 1) +
labs(title = "Average Rainfall and Temperature for Each Month Each Year",
x = "Month",
y = "Value") +
theme_minimal() +
scale_color_discrete(name = "year") +
scale_fill_discrete(name = "year") +
facet_wrap(~year, scales = "free_y")
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
The analysis of average temperature trends over several years reveals a distinct parabolic shape—peaking at both ends and dipping in the middle. Higher temperatures characterize the beginnings and ends of the year, aligning with Australia’s summer season. Conversely, lower temperatures prevail in the middle of the year, marking the winter season.
Comparing temperature with rainfall, there is no clear correlation emerges. Cold weather doesn’t consistently coincide with rain, introducing a nuanced complexity in the interplay between temperature and rainfall.
# create a line plot for humidity faceted by year
ggplot(df, aes(x = date)) +
geom_line(aes(y = humidity_9am, color = "Humidity 9am"), size = 0.5) +
geom_line(aes(y = humidity_3pm, color = "Humidity 3pm"), size = 0.5,) +
labs(title = "Humidity Trends Over Time",
x = "Year",
y = "Humidity",
color = "Variable") +
theme_minimal()
This line graph indicates higher humidity levels at 9 am compared to 3 pm, aligning with the typical morning humidity patterns. Furthermore, there is a fluctuating trend over the years, influenced by seasonal changes in Australia. Increased humidity is noticeable at the start and end of the year, corresponding to the summer season, while lower humidity prevails in the middle of the year during the winter season. This cyclical fluctuation mirrors the dynamic nature of humidity in response to seasonal shifts.
# create a line plot for pressure faceted by year
ggplot(df, aes(x = date)) +
geom_line(aes(y = pressure_9am, color = "Pressure 9am"), size = 0.5) +
geom_line(aes(y = pressure_3pm, color = "Pressure 3pm"), size = 0.5,) +
labs(title = "Pressure Trends Over Time",
x = "Year",
y = "Pressure",
color = "Variable") +
theme_minimal()
This line graph illustrates that atmospheric pressure levels are generally higher at 9 am compared to 3 pm. The higher morning pressure is attributed to the Earth cooling down during the night, creating denser air. As the day progresses and the sun warms the Earth, the air expands, resulting in lower atmospheric pressure in the evening.
Additionally, there’s a fluctuating trend over the years influenced by seasonal changes as well. Atmospheric pressure tends to be higher in winter than in summer due to the denser and colder air, leading to a higher concentration of air molecules. This trend is visible in the graph, with atmospheric pressure increasing around the turn of the year.
# create a line plot for temperature faceted by year
ggplot(df, aes(x = date)) +
geom_line(aes(y = temp_9am, color = "Temperature 9am"), size = 0.5) +
geom_line(aes(y = temp_3pm, color = "Temperature 3pm"), size = 0.5,) +
labs(title = "Temperature Trends Over Time",
x = "Year",
y = "Temperature",
color = "Variable") +
theme_minimal()
The line graph clearly depicts that the temperature at 9 am is lower than at 3 pm, which aligns with the typical coolness of the morning just after sunrise. As seen in previous line charts, temperature is influenced by seasonal changes. Notably, the temperature is markedly higher around the turn of the year, corresponding to the summer season, and lower during the middle of the year, indicative of the winter season. This natural fluctuation reflects the impact of changing seasons on temperature patterns.
In the process of data validation and consistency checking, we have undertaken a comparison between the ‘RainToday’ variable and the actual ‘Rainfall’ amounts in our dataset. The goal is to identify any potential inconsistencies or discrepancies between the categorical indicator of rain (‘RainToday’) and the actual recorded rainfall values.
The threshold we set is 1mm as any amount of rainfall less than 1 mm are typically considered negligible or trace amounts. These minimal amounts may not have a significant impact on the environment or daily activities, and they are often challenging to measure accurately.This also helps to avoiding noise in the data. Including extremely small rainfall amounts, such as mist or drizzle, could introduce noise into the data, making it harder to discern meaningful patterns or trends. By setting a minimum threshold, we can focus on more substantial rain events.
# checking if 'RainToday' matches with 'Rainfall'
inconsistent_rows <- which(df$rain_today != ifelse(df$rainfall > 1, "Yes", "No"))
# print or inspect the inconsistent rows
print(inconsistent_rows)
## integer(0)
In numerous data analyses and modeling projects, we often deal with a multitude of gathered features, reaching into the hundreds or even thousands. Practically speaking, a model with an increased number of features becomes more challenging to interpret and incurs higher computational costs. Certain models, such as the Lasso and tree-based methods, exhibit greater resilience to uninformative predictors compared to others. While some models maintain the performance even in the presence of non-informative predictors, the training time for these models can be adversely affected as more features are introduced. It is observed that various algorithms like elastic nets, random forests, and gradient boosting machines demand significantly more time as the number of predictors increases. Consequently, the process of filtering or reducing features before modeling can substantially enhance training efficiency.
Identifying and removing variables with zero or non-zero variance is a straightforward and effective step. A zero variance variable has only one unique value, providing no-valuable information to a model. While certain algorithms may not be impacted by such features, those with near-zero variance contribute minimal or no useful information. Additionally, during resampling, near-zero variance features may pose challenges as samples are likely to predominantly contain a single unique value, causing potential issues.
# identify variables with near-zero variance in the data set
nearZeroVar(df_cleaned, saveMetrics = TRUE) %>%
rownames_to_column() %>%
filter(nzv)
## rowname freqRatio percentUnique zeroVar nzv
## 1 sunshine 63.80794 0.1029925 FALSE TRUE
Observation:
sunshine column has been identified as having
near-zero variance, indicating that this column may have very little
variability in its values.# remove the`date` column from the data frame
df_cleaned <- df_cleaned[, !(names(df_cleaned) %in% c('date'))]
Reasons to remove the date column:
date column may
not contribute significantly to the insights or predictions we are
seeking, and might introduce unnecessary complexity to the model without
providing substantial benefits.The most straightforward method for dividing the data into training and test sets involves using a simple random sample. However, this approach does not control for any data attributes, such as the distribution of the response variable. To ensure that our training and test sets exhibits similar distributions of the response variable, we employ stratified sampling. This method is employed to achieve a balanced representation of the response variable in both the training and test sets while explicitly controlling the sampling process.
Original response distribution:
# calculate the proportions of the occurrences of each unique value in the `rain_tomorrow` column
table(df_cleaned$rain_tomorrow) %>% prop.table()
##
## No Yes
## 0.7783815 0.2216185
Observation:
# set the seed for reproducibility
set.seed(100)
# split the data set into training and testing sets using stratified sampling
# the proportion of data to be allocated to the training set = 70%
# the splitting is done in a way that maintains the distribution fo `rain_tomorrow`
split_strat <- initial_split(df_cleaned, prop = 0.7, strata = 'rain_tomorrow')
# extract the training set from the split
train_strat <- training(split_strat)
# extract the testing set from the split
test_strat <- testing(split_strat)
Consistent response ratio between training and testing sets:
# count the proportions of the occurrences of each unique value of the `rain_tomorrow` variable in the training set
table(train_strat$rain_tomorrow) %>% prop.table()
##
## No Yes
## 0.7783866 0.2216134
# count the proportions of the occurrences of each unique value of the `rain_tomorrow` variable in the testing set
table(test_strat$rain_tomorrow) %>% prop.table()
##
## No Yes
## 0.7783697 0.2216303
Observation:
Numeric features can pose challenges for specific models when they exhibit skewed distributions, outliers, or a wide range in magnitudes. Tree-based models are generally resilient to these issues within the feature space. However, other models like GLMs, regularized regression, KNN, support vector machines, and neural networks can be significantly hindered by such problems. Normalizing and standardizing features with pronounced skewness can mitigate these issues.
Standardizing features involves both centering and scaling, ensuring that numeric variables have an average of zero and a standard deviation of one. This process establishes a consistent and comparable unit of measurement across all variables.
Categorical feature engineering is necessary because most models work best with numerical inputs. While some models, like tree-based ones, can handle both numeric and categorical features, enhancing categorical features through preprocessing can still improve their performance.
Ordinal encoding is a technique employed to represent categorical variables that possess a natural order or ranking. In contrast to one-hot encoding, ordinal encoding assigns integer values to categories based on their order. Ordinal encoding is beneficial as it retains the inherent order of categories while transforming them into a numerical format, making it especially useful for ordinal categorical features. This preservation of order enables machine learning models to interpret and utilize the inherent ranking information in the data.
Therefore, we typically employ this approach for variables exhibiting a meaningful sequence or hierarchy, such as cloud cover and wind direction.
One-hot encoding involves converting categorical variables into a format where each level of the feature is shown as a true or false value. The advantage is that it helps models process categorical data, but it may increase the dataset size, potentially leading to increased computation time and memory usage.
Therefore, we typically apply one-hot encoding specifically to categorical features with low cardinality, as it may lead to manageable increases in dataset size for such cases.
Label encoding is a method where categorical variable levels are converted into numerical values. It involves assigning a unique numeric label to each category, allowing for numerical representation.
Given the high cardinality of certain variables, like location with 49 distinct values, and considering the limitations of one-hot encoding, which can lead to an increase in dataset size, label encoding becomes a practical choice for non-ordered high cardinality features. This approach helps manage the computational load associated with large datasets while still providing a numeric representation for machine learning models.
# separate predictors and target
predictors <- df_cleaned[, names(df_cleaned) != 'rain_tomorrow']
target <- df_cleaned$rain_tomorrow
# identify numerical, ordinal, and nominal predictors
num_cols <- names(predictors)[sapply(predictors, is.numeric)]
ord_cols <- names(predictors)[sapply(predictors, is.ordered)]
nom_cols <- names(predictors)[sapply(predictors, function(x) is.factor(x) && !is.ordered(x))]
# check cardinality
low_car_nom_cols <- nom_cols[sapply(predictors[, nom_cols], function(x) length(levels(x)) < 15)]
high_car_nom_cols <- nom_cols[sapply(predictors[, nom_cols], function(x) length(levels(x)) >= 15)]
recipe <- recipe(rain_tomorrow ~ ., data = train_strat) %>%
# Step 1: Standardize numerical predictors
step_normalize(all_numeric(), -all_outcomes()) %>%
# Step 2: Ordinal encode ordinal predictors
step_ordinalscore(all_of(ord_cols), -all_outcomes()) %>%
# Step 3: One-hot encode nominal predictors
step_dummy(all_of(low_car_nom_cols), -all_outcomes()) %>%
# Step 4: Label encode response variable
step_integer(all_of(c('rain_tomorrow', high_car_nom_cols)))
# preprocess training data
train_processed <- prep(recipe) %>% bake(new_data = train_strat)
# preview the data in the processed training data frame
train_processed
## # A tibble: 98,550 × 22
## location min_temp max_temp rainfall evaporation sunshine wind_gust_dir
## <int> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
## 1 3 0.189 -0.0478 -0.207 -0.752 -0.854 13
## 2 3 -0.749 0.262 -0.277 -0.752 -0.854 14
## 3 3 0.111 0.347 -0.277 -0.752 -0.854 12
## 4 3 -0.468 0.670 -0.277 -0.752 -0.854 3
## 5 3 0.830 1.28 -0.160 -0.752 -0.854 13
## 6 3 0.376 0.910 -0.254 -0.752 -0.854 14
## 7 3 0.329 0.248 -0.277 -0.752 -0.854 13
## 8 3 -0.702 0.487 -0.277 -0.752 -0.854 13
## 9 3 0.0636 -0.315 0.146 -0.752 -0.854 11
## 10 3 -0.108 0.853 -0.277 -0.752 -0.854 9
## # ℹ 98,540 more rows
## # ℹ 15 more variables: wind_gust_speed <dbl>, wind_dir_9am <int>,
## # wind_dir_3pm <int>, wind_speed_9am <dbl>, wind_speed_3pm <dbl>,
## # humidity_9am <dbl>, humidity_3pm <dbl>, pressure_9am <dbl>,
## # pressure_3pm <dbl>, cloud_9am <int>, cloud_3pm <int>, temp_9am <dbl>,
## # temp_3pm <dbl>, rain_tomorrow <int>, rain_today_Yes <dbl>
# create a true copy of the data frame
df_train_processed <- data.frame(train_processed)
# save the dataset to a CSV file
write.csv(train_processed, 'C:/Users/cuish/OneDrive/Documents/Master of Data Science/WQD7004 Programming for Data Science/7004 Assignment/weatherAUS_processed.csv', row.names = FALSE)
For this project, a diverse set of machine learning models will be employed to explore different aspects of the data. These models include logistic regression (glm), support vector machines (svmRadial), k-nearest neighbors (knn), decision trees (rpart), random forests (rf), gradient boosting (xgbTree), and neural networks (nnet). Each model offers unique strengths and capabilities. Logistic regression is suitable for binary classification, support vector machines are effective for complex decision boundaries, k-nearest neighbors rely on local patterns, decision trees capture hierarchical relationships, random forests provide robustness through ensemble learning, gradient boosting excels in boosting weak learners, and neural networks offer flexibility for complex non-linear relationships. The selection of these models aims to comprehensively analyze and interpret the dataset, taking advantage of the diverse characteristics each model brings to the table, as well as to assess their performance and identify the most suitable one that yields.
In assessing the performance of the diverse machine learning models, we utilized a combination of evaluation metrics, including accuracy, confusion matrix, classification report, and area under the receiver operating characteristic curve (AUC-ROC).
Accuracy provides a holistic measure of correct predictions over the total instances.
The confusion matrix breaks down predictions into true positives, true negatives, false positives, and false negatives, offering a detailed understanding of the model’s performance.
The classification report further refines this analysis by presenting precision, recall, and F1-score for each class, providing insights into both false positives and false negatives.
The AUC-ROC curve assesses the model’s ability to distinguish between classes, particularly valuable for imbalanced datasets.
Together, these metrics offer a comprehensive and nuanced evaluation, allowing us to make informed decisions about the models’ suitability and effectiveness in addressing the project’s objectives.
train_processed$rain_tomorrow <- as.factor(train_processed$rain_tomorrow)
# define models with appropriate model names for caret
models <- list(
logistic_reg = "glm",
svm = "svmRadial",
knn = "knn",
decision_tree = "rpart",
random_forest = "rf",
gradient_boosting = "xgbTree",
neural_network = "nnet"
)
trained_models <- lapply(names(models), function(model_name) {
train(
rain_tomorrow ~ .,
data = train_processed,
method = models[[model_name]],
trControl = trainControl(method = "cv", number = 3, classProbs = FALSE)
)
})
## [22:30:57] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:30:57] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:30:58] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:30:58] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:30:58] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:30:58] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:30:59] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:30:59] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:00] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:00] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:01] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:01] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:02] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:02] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:03] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:03] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:04] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:04] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:05] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:05] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:06] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:06] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:07] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:07] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:08] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:08] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:10] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:10] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:11] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:11] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:13] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:13] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:15] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:15] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:16] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:16] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:17] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:17] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:18] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:18] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:18] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:18] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:19] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:19] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:20] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:20] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:20] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:21] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:22] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:22] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:23] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:23] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:23] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:23] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:25] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:25] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:26] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:26] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:27] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:27] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:28] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:28] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:29] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:29] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:30] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:30] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:32] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:32] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:33] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:33] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:35] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:35] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:35] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:35] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:36] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:36] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:37] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:37] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:38] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:38] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:39] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:39] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:39] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:39] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:41] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:41] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:42] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:42] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:42] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:42] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:44] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:44] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:45] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:45] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:46] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:46] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:47] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:47] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:48] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:48] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:49] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:49] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:51] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:51] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:52] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:52] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:54] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:54] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:54] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:54] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:55] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:55] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:56] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:56] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:57] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:57] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:58] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:58] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:58] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:58] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:59] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:31:59] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:00] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:00] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:01] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:01] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:03] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:03] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:04] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:04] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:05] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:05] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:06] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:06] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:07] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:07] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:08] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:08] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:10] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:10] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:11] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:11] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:13] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:13] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:14] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:14] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:14] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:14] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:15] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:15] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:16] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:16] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:17] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:17] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:17] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:17] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:18] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:18] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:19] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:19] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:20] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:20] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:21] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:21] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:22] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:22] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:23] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:23] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:25] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:25] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:26] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:26] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:27] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:27] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:29] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:29] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:30] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:30] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:32] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:32] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:33] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:33] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:33] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:33] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:34] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:34] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:35] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:35] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:36] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:36] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:36] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:36] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:37] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:37] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:38] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:38] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:39] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:39] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:40] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:40] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:41] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:41] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:42] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:42] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:44] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:44] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:45] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:45] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:46] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:46] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:48] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:48] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:49] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:49] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:50] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## [22:32:50] WARNING: src/c_api/c_api.cc:935: `ntree_limit` is deprecated, use `iteration_range` instead.
## # weights: 24
## initial value 41898.124330
## iter 10 value 34751.516354
## iter 10 value 34751.516124
## iter 10 value 34751.516122
## final value 34751.516122
## converged
## # weights: 70
## initial value 56892.655002
## iter 10 value 34750.435304
## iter 20 value 32491.163977
## iter 30 value 29207.562368
## iter 40 value 27111.834689
## iter 50 value 26691.919794
## iter 60 value 26584.648785
## iter 70 value 26567.034962
## iter 80 value 26446.074312
## iter 90 value 25989.640608
## iter 100 value 25269.470656
## final value 25269.470656
## stopped after 100 iterations
## # weights: 116
## initial value 38236.942951
## iter 10 value 31799.022117
## iter 20 value 27424.116259
## iter 30 value 25651.897574
## iter 40 value 24786.943323
## iter 50 value 24529.397044
## iter 60 value 24290.289362
## iter 70 value 24012.222457
## iter 80 value 23833.092517
## iter 90 value 23628.993380
## iter 100 value 23411.953216
## final value 23411.953216
## stopped after 100 iterations
## # weights: 24
## initial value 57541.117748
## iter 10 value 34216.557474
## iter 20 value 31088.030416
## iter 30 value 27646.152750
## iter 40 value 27019.568152
## iter 50 value 26546.486969
## iter 60 value 25833.647625
## iter 70 value 25177.847892
## iter 80 value 24807.724519
## iter 90 value 24024.907210
## iter 100 value 23886.748417
## final value 23886.748417
## stopped after 100 iterations
## # weights: 70
## initial value 67597.437421
## iter 10 value 34999.459375
## iter 20 value 34524.498991
## iter 30 value 31573.613899
## iter 40 value 28957.236439
## iter 50 value 27502.212288
## iter 60 value 26976.562966
## iter 70 value 26528.717153
## iter 80 value 26130.135654
## iter 90 value 25789.397227
## iter 100 value 25346.824223
## final value 25346.824223
## stopped after 100 iterations
## # weights: 116
## initial value 51019.233305
## iter 10 value 34112.682048
## iter 20 value 31306.130491
## iter 30 value 27538.851199
## iter 40 value 26366.467582
## iter 50 value 26002.232250
## iter 60 value 25690.548846
## iter 70 value 25555.764357
## iter 80 value 25122.268900
## iter 90 value 24300.854811
## iter 100 value 24010.062407
## final value 24010.062407
## stopped after 100 iterations
## # weights: 24
## initial value 49393.601329
## final value 34751.553389
## converged
## # weights: 70
## initial value 63645.476160
## iter 10 value 34063.436946
## iter 20 value 29422.024307
## iter 30 value 27884.579779
## iter 40 value 26466.729911
## iter 50 value 25552.438405
## iter 60 value 25237.171179
## iter 70 value 24891.697739
## iter 80 value 24462.077815
## iter 90 value 24334.426362
## iter 100 value 24143.890345
## final value 24143.890345
## stopped after 100 iterations
## # weights: 116
## initial value 53564.213623
## iter 10 value 31580.349421
## iter 20 value 30872.637719
## iter 30 value 28732.250185
## iter 40 value 25507.348136
## iter 50 value 25104.026609
## iter 60 value 24902.472119
## iter 70 value 24571.868585
## iter 80 value 24170.194450
## iter 90 value 23883.306527
## iter 100 value 23583.282203
## final value 23583.282203
## stopped after 100 iterations
## # weights: 24
## initial value 35897.443050
## iter 10 value 34419.604083
## iter 20 value 28655.458546
## iter 30 value 27039.003313
## iter 40 value 26879.868146
## iter 50 value 26690.261083
## iter 60 value 26575.065830
## iter 70 value 26204.747255
## iter 80 value 25299.523241
## iter 90 value 24632.695865
## iter 100 value 24330.686956
## final value 24330.686956
## stopped after 100 iterations
## # weights: 70
## initial value 38374.705242
## iter 10 value 34462.844545
## iter 20 value 31450.652815
## iter 30 value 30074.568083
## iter 40 value 27657.737364
## iter 50 value 25977.009371
## iter 60 value 24971.653890
## iter 70 value 24566.232015
## iter 80 value 24373.340696
## iter 90 value 24281.788378
## iter 100 value 24072.350410
## final value 24072.350410
## stopped after 100 iterations
## # weights: 116
## initial value 51709.411222
## iter 10 value 32476.409405
## iter 20 value 27060.117567
## iter 30 value 25785.480202
## iter 40 value 25095.796439
## iter 50 value 24929.724509
## iter 60 value 24684.236889
## iter 70 value 24360.255346
## iter 80 value 24132.773238
## iter 90 value 23891.181631
## iter 100 value 23786.074250
## final value 23786.074250
## stopped after 100 iterations
## # weights: 24
## initial value 40906.257929
## iter 10 value 34015.849928
## iter 20 value 29701.734945
## iter 30 value 28108.747211
## iter 40 value 27365.386498
## iter 50 value 26508.944703
## iter 60 value 25643.566689
## iter 70 value 25261.458718
## iter 80 value 24979.087445
## iter 90 value 24263.187309
## iter 100 value 24149.665409
## final value 24149.665409
## stopped after 100 iterations
## # weights: 70
## initial value 40567.887812
## iter 10 value 32770.897781
## iter 20 value 29711.165393
## iter 30 value 27306.750472
## iter 40 value 26259.445424
## iter 50 value 25734.916333
## iter 60 value 25062.541680
## iter 70 value 24555.350553
## iter 80 value 24063.461644
## iter 90 value 23909.953089
## iter 100 value 23825.649461
## final value 23825.649461
## stopped after 100 iterations
## # weights: 116
## initial value 47656.567234
## iter 10 value 32580.976813
## iter 20 value 27237.123862
## iter 30 value 26199.495514
## iter 40 value 25554.099202
## iter 50 value 24736.011340
## iter 60 value 24580.149842
## iter 70 value 24405.814784
## iter 80 value 24158.780064
## iter 90 value 23965.632788
## iter 100 value 23749.587936
## final value 23749.587936
## stopped after 100 iterations
## # weights: 24
## initial value 36932.924727
## iter 10 value 32775.000325
## iter 20 value 31015.423688
## iter 30 value 27911.485836
## iter 40 value 26964.516355
## iter 50 value 26648.100273
## iter 60 value 26171.759250
## iter 70 value 25914.953220
## iter 80 value 25422.079881
## iter 90 value 24465.340432
## iter 100 value 24261.775292
## final value 24261.775292
## stopped after 100 iterations
## # weights: 70
## initial value 42176.647159
## iter 10 value 30377.711323
## iter 20 value 27516.684728
## iter 30 value 26564.161549
## iter 40 value 26224.432909
## iter 50 value 25639.374807
## iter 60 value 25088.417384
## iter 70 value 24453.472290
## iter 80 value 24069.491059
## iter 90 value 23876.564360
## iter 100 value 23826.136022
## final value 23826.136022
## stopped after 100 iterations
## # weights: 116
## initial value 36584.256872
## iter 10 value 32775.834757
## iter 20 value 30105.566930
## iter 30 value 28124.671033
## iter 40 value 27047.931668
## iter 50 value 26322.051900
## iter 60 value 25827.678795
## iter 70 value 25448.295543
## iter 80 value 25213.318932
## iter 90 value 25107.331338
## iter 100 value 25017.977181
## final value 25017.977181
## stopped after 100 iterations
## # weights: 24
## initial value 44118.689744
## iter 10 value 32700.207850
## iter 20 value 28543.912535
## iter 30 value 26719.370861
## iter 40 value 26211.215083
## iter 50 value 25519.614999
## iter 60 value 25089.403868
## iter 70 value 24941.278028
## iter 80 value 24139.962047
## iter 90 value 23935.658140
## iter 100 value 23905.036418
## final value 23905.036418
## stopped after 100 iterations
## # weights: 70
## initial value 34985.529770
## iter 10 value 29479.055411
## iter 20 value 26741.340236
## iter 30 value 25726.275072
## iter 40 value 25459.903850
## iter 50 value 25370.436930
## iter 60 value 25235.164395
## iter 70 value 24838.367372
## iter 80 value 24487.033289
## iter 90 value 24200.242994
## iter 100 value 23937.958917
## final value 23937.958917
## stopped after 100 iterations
## # weights: 116
## initial value 81717.935625
## iter 10 value 32462.802399
## iter 20 value 28795.108226
## iter 30 value 28200.782447
## iter 40 value 26196.516678
## iter 50 value 24943.771332
## iter 60 value 24476.731533
## iter 70 value 24083.940260
## iter 80 value 23836.124583
## iter 90 value 23648.355369
## iter 100 value 23495.862487
## final value 23495.862487
## stopped after 100 iterations
## # weights: 24
## initial value 37879.026945
## iter 10 value 31023.139272
## iter 20 value 29553.665293
## iter 30 value 26342.590363
## iter 40 value 25846.393268
## iter 50 value 24731.080776
## iter 60 value 24346.874426
## iter 70 value 24226.248337
## iter 80 value 24025.487055
## iter 90 value 23926.482988
## iter 100 value 23911.054202
## final value 23911.054202
## stopped after 100 iterations
## # weights: 70
## initial value 52289.505518
## iter 10 value 34756.546326
## iter 20 value 30717.434564
## iter 30 value 28239.164867
## iter 40 value 27596.877408
## iter 50 value 26686.373345
## iter 60 value 26329.509929
## iter 70 value 25674.548247
## iter 80 value 24752.566296
## iter 90 value 24250.746006
## iter 100 value 23860.105007
## final value 23860.105007
## stopped after 100 iterations
## # weights: 116
## initial value 49441.567157
## iter 10 value 28592.424829
## iter 20 value 26985.016052
## iter 30 value 26190.859595
## iter 40 value 25241.572204
## iter 50 value 24742.807098
## iter 60 value 24509.025759
## iter 70 value 24261.482799
## iter 80 value 23945.647632
## iter 90 value 23628.732247
## iter 100 value 23453.929653
## final value 23453.929653
## stopped after 100 iterations
## # weights: 24
## initial value 60640.857816
## iter 10 value 34545.582996
## iter 20 value 31099.585203
## iter 30 value 27278.551031
## iter 40 value 26795.920422
## iter 50 value 26647.483391
## iter 60 value 26587.045253
## iter 70 value 26503.887558
## iter 80 value 26176.086029
## iter 90 value 25108.067140
## iter 100 value 24446.997065
## final value 24446.997065
## stopped after 100 iterations
## # weights: 70
## initial value 47416.311175
## iter 10 value 34751.518436
## final value 34751.412842
## converged
## # weights: 116
## initial value 49490.125074
## iter 10 value 33685.435167
## iter 20 value 31723.996337
## iter 30 value 29891.169285
## iter 40 value 27746.048579
## iter 50 value 26150.975721
## iter 60 value 25445.066302
## iter 70 value 25242.236271
## iter 80 value 25142.339782
## iter 90 value 25087.455867
## iter 100 value 25055.542010
## final value 25055.542010
## stopped after 100 iterations
## # weights: 116
## initial value 51996.275907
## iter 10 value 46193.514713
## iter 20 value 42461.316566
## iter 30 value 40724.594763
## iter 40 value 39495.380290
## iter 50 value 38402.418027
## iter 60 value 38053.660351
## iter 70 value 36948.105148
## iter 80 value 36382.629785
## iter 90 value 36060.578880
## iter 100 value 35862.804963
## final value 35862.804963
## stopped after 100 iterations
# apply the preprocessing steps to the testing datasets
test_processed <- prep(recipe) %>% bake(new_data = test_strat)
# create a true copy of the data frame
df_test_processed <- data.frame(test_processed)
# save the dataset to a CSV file
write.csv(test_processed, 'C:/Users/cuish/OneDrive/Documents/Master of Data Science/WQD7004 Programming for Data Science/7004 Assignment/weatherAUS_tested_processed.csv', row.names = FALSE)
# convert `rain_tomorrow` back to factor
test_processed$rain_tomorrow <- as.factor(test_processed$rain_tomorrow)
# function to evaluate a trained model
evaluate_model <- function(model, test_data) {
# use 'raw' as the type argument for predict
predictions <- predict(model, newdata = test_data, type = "raw")
# create a confusion matrix
confusion_matrix <- confusionMatrix(predictions, test_data$rain_tomorrow)
# calculate ROC-AUC
roc_auc <- roc(test_data$rain_tomorrow, as.numeric(predictions))$auc
# return confusion matrix and ROC-AUC
return(list(confusion_matrix = confusion_matrix, roc_auc = roc_auc))
}
# evaluate each trained model
evaluation_results <- lapply(trained_models, function(model) {
evaluate_model(model, test_processed)
})
## Setting levels: control = 1, case = 2
## Setting direction: controls < cases
## Setting levels: control = 1, case = 2
## Setting direction: controls < cases
## Setting levels: control = 1, case = 2
## Setting direction: controls < cases
## Setting levels: control = 1, case = 2
## Setting direction: controls < cases
## Setting levels: control = 1, case = 2
## Setting direction: controls < cases
## Setting levels: control = 1, case = 2
## Setting direction: controls < cases
## Setting levels: control = 1, case = 2
## Setting direction: controls < cases
# print the evaluation results
for (i in seq_along(evaluation_results)) {
model_name <- names(trained_models)[i]
cat("Evaluation results for", model_name, ":\n")
print(evaluation_results[[i]])
}
## Evaluation results for :
## $confusion_matrix
## Confusion Matrix and Statistics
##
## Reference
## Prediction 1 2
## 1 31059 4888
## 2 1817 4473
##
## Accuracy : 0.8413
## 95% CI : (0.8377, 0.8447)
## No Information Rate : 0.7784
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.4787
##
## Mcnemar's Test P-Value : < 2.2e-16
##
## Sensitivity : 0.9447
## Specificity : 0.4778
## Pos Pred Value : 0.8640
## Neg Pred Value : 0.7111
## Prevalence : 0.7784
## Detection Rate : 0.7354
## Detection Prevalence : 0.8511
## Balanced Accuracy : 0.7113
##
## 'Positive' Class : 1
##
##
## $roc_auc
## Area under the curve: 0.7113
##
## Evaluation results for :
## $confusion_matrix
## Confusion Matrix and Statistics
##
## Reference
## Prediction 1 2
## 1 31643 4947
## 2 1233 4414
##
## Accuracy : 0.8537
## 95% CI : (0.8503, 0.857)
## No Information Rate : 0.7784
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.5058
##
## Mcnemar's Test P-Value : < 2.2e-16
##
## Sensitivity : 0.9625
## Specificity : 0.4715
## Pos Pred Value : 0.8648
## Neg Pred Value : 0.7817
## Prevalence : 0.7784
## Detection Rate : 0.7492
## Detection Prevalence : 0.8663
## Balanced Accuracy : 0.7170
##
## 'Positive' Class : 1
##
##
## $roc_auc
## Area under the curve: 0.717
##
## Evaluation results for :
## $confusion_matrix
## Confusion Matrix and Statistics
##
## Reference
## Prediction 1 2
## 1 31263 5365
## 2 1613 3996
##
## Accuracy : 0.8348
## 95% CI : (0.8312, 0.8383)
## No Information Rate : 0.7784
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.441
##
## Mcnemar's Test P-Value : < 2.2e-16
##
## Sensitivity : 0.9509
## Specificity : 0.4269
## Pos Pred Value : 0.8535
## Neg Pred Value : 0.7124
## Prevalence : 0.7784
## Detection Rate : 0.7402
## Detection Prevalence : 0.8672
## Balanced Accuracy : 0.6889
##
## 'Positive' Class : 1
##
##
## $roc_auc
## Area under the curve: 0.6889
##
## Evaluation results for :
## $confusion_matrix
## Confusion Matrix and Statistics
##
## Reference
## Prediction 1 2
## 1 31738 6142
## 2 1138 3219
##
## Accuracy : 0.8276
## 95% CI : (0.824, 0.8312)
## No Information Rate : 0.7784
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.3824
##
## Mcnemar's Test P-Value : < 2.2e-16
##
## Sensitivity : 0.9654
## Specificity : 0.3439
## Pos Pred Value : 0.8379
## Neg Pred Value : 0.7388
## Prevalence : 0.7784
## Detection Rate : 0.7514
## Detection Prevalence : 0.8968
## Balanced Accuracy : 0.6546
##
## 'Positive' Class : 1
##
##
## $roc_auc
## Area under the curve: 0.6546
##
## Evaluation results for :
## $confusion_matrix
## Confusion Matrix and Statistics
##
## Reference
## Prediction 1 2
## 1 31333 4473
## 2 1543 4888
##
## Accuracy : 0.8576
## 95% CI : (0.8542, 0.8609)
## No Information Rate : 0.7784
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.5351
##
## Mcnemar's Test P-Value : < 2.2e-16
##
## Sensitivity : 0.9531
## Specificity : 0.5222
## Pos Pred Value : 0.8751
## Neg Pred Value : 0.7601
## Prevalence : 0.7784
## Detection Rate : 0.7418
## Detection Prevalence : 0.8477
## Balanced Accuracy : 0.7376
##
## 'Positive' Class : 1
##
##
## $roc_auc
## Area under the curve: 0.7376
##
## Evaluation results for :
## $confusion_matrix
## Confusion Matrix and Statistics
##
## Reference
## Prediction 1 2
## 1 31181 4317
## 2 1695 5044
##
## Accuracy : 0.8577
## 95% CI : (0.8543, 0.861)
## No Information Rate : 0.7784
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.5415
##
## Mcnemar's Test P-Value : < 2.2e-16
##
## Sensitivity : 0.9484
## Specificity : 0.5388
## Pos Pred Value : 0.8784
## Neg Pred Value : 0.7485
## Prevalence : 0.7784
## Detection Rate : 0.7382
## Detection Prevalence : 0.8404
## Balanced Accuracy : 0.7436
##
## 'Positive' Class : 1
##
##
## $roc_auc
## Area under the curve: 0.7436
##
## Evaluation results for :
## $confusion_matrix
## Confusion Matrix and Statistics
##
## Reference
## Prediction 1 2
## 1 31172 4927
## 2 1704 4434
##
## Accuracy : 0.843
## 95% CI : (0.8395, 0.8465)
## No Information Rate : 0.7784
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.4811
##
## Mcnemar's Test P-Value : < 2.2e-16
##
## Sensitivity : 0.9482
## Specificity : 0.4737
## Pos Pred Value : 0.8635
## Neg Pred Value : 0.7224
## Prevalence : 0.7784
## Detection Rate : 0.7380
## Detection Prevalence : 0.8547
## Balanced Accuracy : 0.7109
##
## 'Positive' Class : 1
##
##
## $roc_auc
## Area under the curve: 0.7109
Random Forest and XGBoost Perform Well: Random Forest and XGBoost achieved the highest accuracy among the models, with 85.79% and 85.69%, respectively. These ensemble methods are known for their ability to handle complex relationships in the data and are generally robust, making them strong candidates for rain prediction in this context.
SVM and Logistic Regression Are Competitive: Support Vector Machine (SVM) and Logistic Regression also performed well with accuracies of 85.37% and 84.13%, respectively. These models are more interpretable than ensemble methods and might be preferred if model interpretability is crucial.
k-Nearest Neighbour and Neural Network: While k-Nearest Neighbour and Neural Network models showed decent accuracy (83.48% and 84.37%, respectively), they didn’t outperform the other models in this particular task. Fine-tuning the parameters or exploring different architectures for the Neural Network might lead to improved performance.
Decision Tree: The Decision Tree model achieved an accuracy of 82.76%. Decision Trees are often less complex and more interpretable, but in this case, it seems to be outperformed by ensemble methods.
True Negatives (TN): The count of correct predictions for no rain. False Positives (FP): Incorrectly predicted rain when it didn’t occur. False Negatives (FN): Incorrectly predicted no rain when it did occur. True Positives (TP): Correctly predicted rain.
SVM and Logistic Regression: These models have a good balance between correctly predicting rain and no rain. SVM has a slightly higher True Positive rate, but Logistic Regression has fewer False Positives.
Random Forest and XGBoost: Both performed well, with XGBoost having a slightly higher True Positive rate. These ensemble methods generally handle complex relationships effectively.
k-Nearest Neighbour and Neural Network: They show decent performance, but there is room for improvement, especially in reducing False Negatives.
Decision Tree: It has the highest number of False Positives and False Negatives among the models, indicating a lower performance compared to others.
Sensitivity (True Positive Rate): The proportion of actual positive cases correctly identified by the model.
Specificity (True Negative Rate): The proportion of actual negative cases correctly identified by the model.
Positive Predictive Value (Precision): The proportion of predicted positive cases that are truly positive.
Negative Predictive Value: The proportion of predicted negative cases that are truly negative.
Prevalence: The proportion of actual positive cases in the dataset.
Detection Rate: The proportion of correctly identified positive cases.
Detection Prevalence: The proportion of predicted positive cases.
Balanced Accuracy: The average of sensitivity and specificity, providing a balanced view of the model’s performance.
Random Forest and XGBoost stand out with a better balance between sensitivity and specificity, making them more robust for rain prediction.
Decision Tree has high sensitivity but significantly lower specificity, indicating potential overfitting or imbalance.
k-Nearest Neighbour has good sensitivity but lacks specificity, potentially leading to more false positives.
Logistic Regression and SVM have high sensitivity but lower specificity, indicating potential areas for improvement.
Neural Network performs similarly to Logistic Regression and SVM.
Decision Tree has the highest ROC AUC score (0.8372), indicating good overall model performance in terms of sensitivity and specificity.
XGBoost and Random Forest also have reasonably high ROC AUC scores (0.7418 and 0.7377), suggesting robust discrimination ability.
Logistic Regression, Support Vector Machine, and Neural Network show moderate ROC AUC scores, indicating acceptable performance, but there is room for improvement.
k-Nearest Neighbour has the lowest ROC AUC score among the models, suggesting that it may not discriminate between classes as effectively as the other models.
# read the CSV file
data <- read.csv("C:/Users/cuish/OneDrive/Documents/Master of Data Science/WQD7004 Programming for Data Science/7004 Assignment/weatherAUS_cleaned.csv")
As the main columns used for time series regression are
date and rainfall, new data frame is generated
by using these two columns
# Extract date and rainfall from cleaned dataset
rainfall_day <- data %>%
select(date, rainfall) %>%
mutate(year_month = as.factor(format(ymd(date), "%Y%m"))) %>%
select(year_month, date, rainfall)
The current rainfall is measured in day. The target
variable is monthly rainfall, therefore rainfall_day is
transformed to a new dataframe where rainfall is grouped by
monthly basis.
# Group daily rainfall to monthly rainfall
rainfall_month <- rainfall_day %>%
group_by(year_month) %>%
summarise(monthly_rainfall= sum(rainfall))
Split rainfall_month into two datasets which are used for training and testing.
# check the maximum and minimum month for rainfall_month
max_month <- rainfall_month$year_month[which.max(rainfall_month$year_month)]
min_month <- rainfall_month$year_month[which.min(rainfall_month$year_month)]
max_month
## [1] 201706
## 113 Levels: 200711 200712 200801 200802 200803 200804 200805 200806 ... 201706
min_month
## [1] 200711
## 113 Levels: 200711 200712 200801 200802 200803 200804 200805 200806 ... 201706
Set historical set and comparison set.
# set historical set and comparison set
hist_set <- subset(rainfall_month, as.integer(as.character(year_month)) <= 201703)
compare_set <- subset(rainfall_month, as.integer(as.character(year_month)) >= 201604)
Transform rainfall_month to time series object.
# create time series object
rainfall_month_ts <- ts(hist_set$monthly_rainfall, frequency=12, start=c(2007,11))
Use decomposition to observe data.
#decompostion of additive time series (observed, trend, seasonal, random)
decomp_rainfall_month_ts <- decompose(rainfall_month_ts)
Hypothesis testing for time series data:
H0: The time series is non-stationary (has a unit root).
H1: The time series is stationary.
# perform adf test
adf.test(rainfall_month_ts)
##
## Augmented Dickey-Fuller Test
##
## data: rainfall_month_ts
## Dickey-Fuller = -3.3297, Lag order = 4, p-value = 0.06984
## alternative hypothesis: stationary
As the p-value is more than 0.05, transformation is required and test again.
# perform transformation and adf test
lamda_transform <- BoxCox(rainfall_month_ts,lambda="auto")
adf.test(lamda_transform)
##
## Augmented Dickey-Fuller Test
##
## data: lamda_transform
## Dickey-Fuller = -3.1447, Lag order = 4, p-value = 0.1017
## alternative hypothesis: stationary
As the p-value is more than 0.05, differencing is required and test again.
# perform differencing and adf test
differ <- diff(rainfall_month_ts, differences = 1)
differ_transform <- diff(BoxCox(rainfall_month_ts, lambda = "auto"), differences = 1)
adf.test(differ_transform)
## Warning in adf.test(differ_transform): p-value smaller than printed p-value
##
## Augmented Dickey-Fuller Test
##
## data: differ_transform
## Dickey-Fuller = -5.4239, Lag order = 4, p-value = 0.01
## alternative hypothesis: stationary
From this result, p-value is less than 0.05, null hypothesis is rejected.
Find out the best model for ARIMA.
# find out the best model
auto.arima(rainfall_month_ts ,stepwise = F,trace = F,stationary = T,ic=c("aic"))
## Series: rainfall_month_ts
## ARIMA(1,0,1)(1,0,0)[12] with non-zero mean
##
## Coefficients:
## ar1 ma1 sar1 mean
## 0.8831 -0.4730 0.2118 2841.0888
## s.e. 0.0773 0.1476 0.1032 557.3744
##
## sigma^2 = 1260320: log likelihood = -927.29
## AIC=1864.58 AICc=1865.16 BIC=1878.08
As differencing is performed in testing stationary, the parameter seasonal ARIMA model has to be adjusted.
# find out the best model
fit_sarima <- arima(rainfall_month_ts, order=c(1,1,1),seasonal=list(order=c(1,0,0),period=12))
Create time series display for the residuals.
#testing model
# create time series display
tsdisplay(residuals(fit_sarima),lag.max=50,main="residual")
jarque.bera.test(fit_sarima$residuals)
##
## Jarque Bera Test
##
## data: fit_sarima$residuals
## X-squared = 6.8429, df = 2, p-value = 0.03267
Box.test(fit_sarima$residuals,lag=24,type="Ljung-Box")
##
## Box-Ljung test
##
## data: fit_sarima$residuals
## X-squared = 17.97, df = 24, p-value = 0.8045
In conclusion, this model can be used in our forecast.
To generate forecast for rainfall for the coming three months.
p <- forecast(fit_sarima, h = 3, lambda = 1)
## Warning in InvBoxCox(pred$pred, lambda, biasadj, pred$se^2): biasadj
## information not found, defaulting to FALSE.
p
## Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
## Jan 2017 4247.184 2832.441 5661.927 2083.521 6410.847
## Feb 2017 4148.135 2599.237 5697.033 1779.300 6516.970
## Mar 2017 4787.252 3179.780 6394.725 2328.835 7245.669
Forecast points as plotted.
To combine forecast data with comparison data.
# generate forecast data
forecast <- as.data.frame(p)
# adjust month_year for compare_set
compare_set <- compare_set %>%
mutate(month_year = as.yearmon(paste0(year_month, "01"), format = "%Y%m%d"),
month_year = format(month_year, "%b %Y"))
# combine data with compare_set
test <- cbind(forecast, compare_set)
## Warning in data.frame(..., check.names = FALSE): row names were found from a
## short variable and have been discarded
test_mean <- test %>%
mutate(
mae = abs(monthly_rainfall - test$`Point Forecast`),
mape = abs(monthly_rainfall - test$`Point Forecast`) / monthly_rainfall
) %>%
select(-year_month)
The mean absolute percentage error:
mean(test_mean$mape)
## [1] 0.4986932
In conclusion, a MAPE within 0.5 suggests that, on average, the model’s predictions are within 50% of the actual values. While this provides a measure of accuracy, it’s advisable to consider additional factors and potentially explore other modeling techniques to improve forecasting performance.