Advertisement
Guest User

Untitled

a guest
Nov 20th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1.  
  2. library(tidyverse)
  3.  
  4. df = read_csv("creditcard.csv")
  5. df = as.data.frame(df)
  6. dffraud = df[df$Class==1, ]
  7. dffraud = sample_n(dffraud, 400)
  8. dfnonfraud = df[df$Class==0, ]
  9. dfnonfraud = sample_n(dfnonfraud, 50000)
  10.  
  11. dftrain = rbind(dffraud, dfnonfraud)
  12. dftrain = as.data.frame(dftrain)
  13. y = dftrain$Class == 1
  14. sigmoid <- function(x) 1 / (1 + exp(-x))
  15.  
  16. feedforward <- function(x, w1, w2) {
  17. z1 <- cbind(1, x) %*% w1
  18. h <- sigmoid(z1)
  19. z2 <- cbind(1, h) %*% w2
  20. list(output = sigmoid(z2), h = h)
  21. }
  22.  
  23. backpropagate <- function(x, y, y_hat, w1, w2, h, learn_rate) {
  24. dw2 <- t(cbind(1, h)) %*% (y_hat - y)
  25. dh <- (y_hat - y) %*% t(w2[-1, , drop = FALSE])
  26. dw1 <- t(cbind(1, x)) %*% (h * (1 - h) * dh)
  27.  
  28. w1 <- w1 - learn_rate * dw1
  29. w2 <- w2 - learn_rate * dw2
  30.  
  31. list(w1 = w1, w2 = w2)
  32. }
  33.  
  34. train <- function(x, y, hidden = 5, learn_rate = 1e-3, iterations = 1e5) {
  35. d <- ncol(x) + 1
  36. w1 <- matrix(rnorm(d * hidden), d, hidden)
  37. w2 <- as.matrix(rnorm(hidden + 1))
  38. for (i in 1:iterations) {
  39. ff <- feedforward(x, w1, w2)
  40. bp <- backpropagate(x, y,
  41. y_hat = ff$output,
  42. w1, w2,
  43. h = ff$h,
  44. learn_rate = learn_rate)
  45. w1 <- bp$w1; w2 <- bp$w2
  46. }
  47. list(output = ff$output, w1 = w1, w2 = w2)
  48. }
  49.  
  50. x = dftrain[, -dftrain$Class]
  51. x = as.matrix(x)
  52.  
  53. #test
  54.  
  55. #nnet = feedforward(x, nnet5$w1, nnet5$w2)
  56. #mean((nnet$output > .5) == y)
  57. #frauds = length(which(nnet$output > 0.05))
  58. #nonfrauds = length(which(nnet$output < 0.05))
  59.  
  60. #train NN
  61. #nnet5 <- train(x, y, hidden = 300, iterations = 1e5)
  62. #mean((nnet5$output > .5) == y)
  63.  
  64. save(nnet5, file = "nnet300_400_50000.RData")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement