<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def fit(self, train_X, train_Y, val_X=None, val_Y=None, graph=None):
 """Fit the model to the data. Parameters train_X : array_like, shape (n_samples, n_features) Training data. train_Y : array_like, shape (n_samples, n_classes) Training labels. val_X : array_like, shape (N, n_features) optional, (default = None). Validation data. val_Y : array_like, shape (N, n_classes) optional, (default = None). Validation labels. graph : tf.Graph, optional (default = None) Tensorflow Graph object. Returns ------- """

        if len(train_Y.shape) != 1:
            num_classes = train_Y.shape[1]
        else:
            raise Exception("Please convert the labels with one-hot encoding.")

        g = graph if graph is not None else self.tf_graph

        with g.as_default():
            # Build model
            self.build_model(train_X.shape[1], num_classes)
            with tf.Session() as self.tf_session:
                # Initialize tf stuff
                summary_objs = tf_utils.init_tf_ops(self.tf_session)
                self.tf_merged_summaries = summary_objs[0]
                self.tf_summary_writer = summary_objs[1]
                self.tf_saver = summary_objs[2]
                # Train model
                self._train_model(train_X, train_Y, val_X, val_Y)
                # Save model
                self.tf_saver.save(self.tf_session, self.model_path)