class_docstr: Neural Attentional Rating Regression with Review-level Explanations
  
  Parameters
  ----------
  name: string, default: 'NARRE'
      The name of the recommender model.
  
  embedding_size: int, default: 100
      Word embedding size
  
  id_embedding_size: int, default: 32
      User/item review id embedding size
  
  n_factors: int, default: 32
      The dimension of the user/item's latent factors.
  
  attention_size: int, default: 16
      Attention size
  
  kernel_sizes: list, default: [3]
      List of kernel sizes of conv2d
  
  n_filters: int, default: 64
      Number of filters
  
  dropout_rate: float, default: 0.5
      Dropout rate of neural network dense layers
  
  max_text_length: int, default: 50
      Maximum number of tokens in a review instance
  
  max_num_review: int, default: 32
      Maximum number of reviews that you want to feed into training. By default, the model will be trained with 32 reviews.
  
  batch_size: int, default: 64
      Batch size
  
  max_iter: int, default: 10
      Max number of training epochs
  
  optimizer: string, optional, default: 'adam'
      Optimizer for training is either 'adam' or 'rmsprop'.
  
  learning_rate: float, optional, default: 0.001
      Initial value of learning rate for the optimizer.
  
  model_selection: str, optional, default: 'last'
      Model selection strategy is either 'best' or 'last'.
  
  user_based: boolean, optional, default: True
      Evaluation strategy for model selection, by default, it measures for every users and taking the average `user_based=True`. Set `user_based=False` if you want to measure per rating instead.
  
  trainable: boolean, optional, default: True
      When False, the model will not be re-trained, and input of pre-trained parameters are required.
  
  verbose: boolean, optional, default: True
      When True, running logs are displayed.
  
  init_params: dictionary, optional, default: None
      Initial parameters, pretrained_word_embeddings could be initialized here, e.g., init_params={'pretrained_word_embeddings': pretrained_word_embeddings}
  
  seed: int, optional, default: None
      Random seed for weight initialization.
      If specified, training will take longer because of single-thread (no parallelization).
  
  References
  ----------
  * Chen, C., Zhang, M., Liu, Y., & Ma, S. (2018, April). Neural attentional rating regression with review-level explanations. In Proceedings of the 2018 World Wide Web Conference (pp. 1583-1592).
class_docstr_tok: ["Neural","Attentional","Rating","Regression","with","Review-level","Explanations","Parameters","--","--","--","--","--","name",":","string",",","default",":","'NARRE'","The","name","of","the","recommender","model",".","embedding_size",":","int",",","default",":","100","Word","embedding","size","id_embedding_size",":","int",",","default",":","32","User\/item","review","id","embedding","size","n_factors",":","int",",","default",":","32","The","dimension","of","the","user\/item","'s","latent","factors",".","attention_size",":","int",",","default",":","16","Attention","size","kernel_sizes",":","list",",","default",":","[","3","]","List","of","kernel","sizes","of","conv2d","n_filters",":","int",",","default",":","64","Number","of","filters","dropout_rate",":","float",",","default",":","0.5","Dropout","rate","of","neural","network","dense","layers","max_text_length",":","int",",","default",":","50","Maximum","number","of","tokens","in","a","review","instance","max_num_review",":","int",",","default",":","32","Maximum","number","of","reviews","that","you","want","to","feed","into","training",".","By","default",",","the","model","will","be","trained","with","32","reviews",".","batch_size",":","int",",","default",":","64","Batch","size","max_iter",":","int",",","default",":","10","Max","number","of","training","epochs","optimizer",":","string",",","optional",",","default",":","'adam'","Optimizer","for","training","is","either","'adam","'","or","'rmsprop","'",".","learning_rate",":","float",",","optional",",","default",":","0.001","Initial","value","of","learning","rate","for","the","optimizer",".","model_selection",":","str",",","optional",",","default",":","'last'","Model","selection","strategy","is","either","'best","'","or","'last","'",".","user_based",":","boolean",",","optional",",","default",":","True","Evaluation","strategy","for","model","selection",",","by","default",",","it","measures","for","every","users","and","taking","the","average","`","user_based=True","`",".","Set","`","user_based=False","`","if","you","want","to","measure","per","rating","instead",".","trainable",":","boolean",",","optional",",","default",":","True","When","False",",","the","model","will","not","be","re-trained",",","and","input","of","pre-trained","parameters","are","required",".","verbose",":","boolean",",","optional",",","default",":","True","When","True",",","running","logs","are","displayed",".","init_params",":","dictionary",",","optional",",","default",":","None","Initial","parameters",",","pretrained_word_embeddings","could","be","initialized","here",",","e.g.",",","init_params=","{","'pretrained_word_embeddings","'",":","pretrained_word_embeddings","}","seed",":","int",",","optional",",","default",":","None","Random","seed","for","weight","initialization",".","If","specified",",","training","will","take","longer","because","of","single-thread","(","no","parallelization",")",".","References","--","--","--","--","--","*","Chen",",","C.",",","Zhang",",","M.",",","Liu",",","Y.",",","&","Ma",",","S.","(","2018",",","April",")",".","Neural","attentional","rating","regression","with","review-level","explanations",".","In","Proceedings","of","the","2018","World","Wide","Web","Conference","(","pp",".","1583-1592",")","."]
code: def _fit_tf(self, train_set, val_set):
      import tensorflow as tf
      from tensorflow import keras
      from .narre import get_data
      from ...eval_methods.base_method import rating_eval
      from ...metrics import MSE
  
      loss = keras.losses.MeanSquaredError()
      if not hasattr(self, "_optimizer"):
          if self.optimizer == "rmsprop":
              self._optimizer = keras.optimizers.RMSprop(
                  learning_rate=self.learning_rate
              )
          elif self.optimizer == "adam":
              self._optimizer = keras.optimizers.Adam(
                  learning_rate=self.learning_rate
              )
          else:
              raise ValueError(
                  "optimizer is either 'rmsprop' or 'adam' but {}".format(
                      self.optimizer
                  )
              )
  
      train_loss = keras.metrics.Mean(name="loss")
      val_loss = float("inf")
      best_val_loss = float("inf")
      self.best_epoch = None
      loop = trange(
          self.max_iter,
          disable=not self.verbose,
          bar_format="{l_bar}{bar:10}{r_bar}{bar:-10b}",
      )
      for i_epoch, _ in enumerate(loop):
          train_loss.reset_states()
          for i, (batch_users, batch_items, batch_ratings) in enumerate(
              train_set.uir_iter(self.batch_size, shuffle=True)
          ):
              (
                  user_reviews,
                  user_iid_reviews,
                  user_num_reviews,
              ) = get_data(
                  batch_users,
                  train_set,
                  self.max_text_length,
                  by="user",
                  max_num_review=self.max_num_review,
              )
              (
                  item_reviews,
                  item_uid_reviews,
                  item_num_reviews,
              ) = get_data(
                  batch_items,
                  train_set,
                  self.max_text_length,
                  by="item",
                  max_num_review=self.max_num_review,
              )
              with tf.GradientTape() as tape:
                  predictions = self.model.graph(
                      [
                          batch_users,
                          batch_items,
                          user_reviews,
                          user_iid_reviews,
                          user_num_reviews,
                          item_reviews,
                          item_uid_reviews,
                          item_num_reviews,
                      ],
                      training=True,
                  )
                  _loss = loss(batch_ratings, predictions)
              gradients = tape.gradient(
                  _loss, self.model.graph.trainable_variables
              )
              self._optimizer.apply_gradients(
                  zip(gradients, self.model.graph.trainable_variables)
              )
              train_loss(_loss)
              if i % 10 == 0:
                  loop.set_postfix(
                      loss=train_loss.result().numpy(),
                      val_loss=val_loss,
                      best_val_loss=best_val_loss,
                      best_epoch=self.best_epoch,
                  )
          current_weights = self.model.get_weights(
              train_set, self.batch_size
          )
          if val_set is not None:
              (
                  self.X,
                  self.Y,
                  self.W1,
                  self.user_embedding,
                  self.item_embedding,
                  self.bu,
                  self.bi,
                  self.mu,
              ) = current_weights
              [current_val_mse], _ = rating_eval(
                  model=self,
                  metrics=[MSE()],
                  test_set=val_set,
                  user_based=self.user_based,
              )
              val_loss = current_val_mse
              if best_val_loss > val_loss:
                  best_val_loss = val_loss
                  self.best_epoch = i_epoch + 1
                  best_weights = current_weights
              loop.set_postfix(
                  loss=train_loss.result().numpy(),
                  val_loss=val_loss,
                  best_val_loss=best_val_loss,
                  best_epoch=self.best_epoch,
              )
          self.losses["train_losses"].append(
              train_loss.result().numpy()
          )
          self.losses["val_losses"].append(val_loss)
      loop.close()
  
      # save weights for predictions
      (
          self.X,
          self.Y,
          self.W1,
          self.user_embedding,
          self.item_embedding,
          self.bu,
          self.bi,
          self.mu,
      ) = (
          best_weights
          if val_set is not None and self.model_selection == "best"
          else current_weights
      )
      if self.verbose:
          print("Learning completed!")
  
file_path: cornac/cornac/models/narre/recom_narre.py
imports: import os
  import pickle
  from tqdm.auto import trange
  import numpy
  from ..recommender import Recommender
  from ..recommender import ANNMixin, MEASURE_DOT
  from ...exception import ScoreException
label_desc: Use image node_id 3 for calling the NARRE obj's underlying member method code with example usage: obj._fit_tf(train_set, val_set) without return types