library(mosaicCalc)
## Loading required package: mosaic
## Registered S3 method overwritten by 'mosaic':
##   method                           from   
##   fortify.SpatialPolygonsDataFrame ggplot2
## 
## The 'mosaic' package masks several functions from core packages in order to add 
## additional features.  The original behavior of these functions should not be affected by this.
## 
## Attaching package: 'mosaic'
## The following objects are masked from 'package:dplyr':
## 
##     count, do, tally
## The following object is masked from 'package:Matrix':
## 
##     mean
## The following object is masked from 'package:ggplot2':
## 
##     stat
## The following objects are masked from 'package:stats':
## 
##     binom.test, cor, cor.test, cov, fivenum, IQR, median, prop.test,
##     quantile, sd, t.test, var
## The following objects are masked from 'package:base':
## 
##     max, mean, min, prod, range, sample, sum
## Loading required package: mosaicCore
## 
## Attaching package: 'mosaicCore'
## The following objects are masked from 'package:dplyr':
## 
##     count, tally
## 
## Attaching package: 'mosaicCalc'
## The following object is masked from 'package:stats':
## 
##     D

Diferensiasi dan Pembelajaran Mesin

Dalam pembelajaran mesin, diferensiasi sangat penting, terutama dalam algoritma optimisasi seperti gradien turun. Dengan menggunakan R, kita dapat mengimplementasikan diferensiasi untuk memperbarui parameter model.

Contoh sederhana menggunakan algoritma gradien turun untuk menemukan parameter model:

# Data training
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 5, 4, 5)

# Definisikan fungsi model (misalnya, y = mx + c)
model <- function(m, c, x) {
  return(m * x + c)
}

# Fungsi untuk menghitung error
error <- function(m, c, x, y) {
  return(mean((y - model(m, c, x))^2))
}

# Turunan parsial terhadap m
grad_m <- function(m, c, x, y) {
  return(-2 * mean((y - model(m, c, x)) * x))
}

# Turunan parsial terhadap c
grad_c <- function(m, c, x, y) {
  return(-2 * mean(y - model(m, c, x)))
}

# Inisialisasi parameter awal
m <- 0
c <- 0
learning_rate <- 0.01
epochs <- 100

# Gradien turun untuk memperbarui parameter
for (i in 1:epochs) {
  m = m - learning_rate * grad_m(m, c, x, y)
  c = c - learning_rate * grad_c(m, c, x, y)
}

# Menampilkan parameter yang diperbarui
print(paste("Parameter m:", m))
## [1] "Parameter m: 0.983669400220308"
print(paste("Parameter c:", c))
## [1] "Parameter c: 0.815170731759964"

Dalam contoh ini, kita mendefinisikan model linier sederhana y = m x + c . dan menggunakan algoritma gradien turun untuk memperbarui parameter m dan c agar sesuai dengan data training x dan y

Referensi: Kaplan, Daniel. 2022. MOSAIC Calculus. GitHub Pages. https://dtkaplan.github.io/MC2/