Newer
Older
linguistic_assignments / 07_final_assignment / learnWeights.R
@David-Elias Kuenstle David-Elias Kuenstle on 23 Feb 2016 1 KB Add instructions for updated final assignment
learnWeights.fnc = function(datset=block1, cueset=cues, outcomeset=outcomes, 
                            alpha=sqrt(0.001), beta=sqrt(0.001), lambda=1.0) {
  # set up weight matrix and assign row and column names
  w = matrix(0, length(cueset), length(outcomeset))
  rownames(w)=cueset
  colnames(w)=outcomeset
  # make a list of relevant sets of cues
  cues = strsplit(datset$Cues, "_")
  # loop over all learning events in datset, row by row
  for (i in 1:length(cues)) {
    # apply Rescorla-Wagner equations
    Vtotals = colSums(w[cues[[i]], outcomeset])
    for (j in 1:length(cues[[i]])) {
      if (datset$Type[i]=="nonword") {
        w[cues[[i]][j],"nonword"] =  w[cues[[i]][j],"nonword"] + 
                                     alpha*beta*(lambda-Vtotals["nonword"])
        w[cues[[i]][j],"word"] =  w[cues[[i]][j],"word"] + 
                                     alpha*beta*(0-Vtotals["word"])
      } else {
        if (datset$Type[i]=="word") {
          w[cues[[i]][j],"word"] =  w[cues[[i]][j],"word"] + 
                                       alpha*beta*(lambda-Vtotals["word"])
          w[cues[[i]][j],"nonword"] =  w[cues[[i]][j],"nonword"] + 
                                       alpha*beta*(0-Vtotals["nonword"])
        }
      }
    }
  }
  # and return weight matrix at the end of learning
  return(w)
}