Example #1
0
def evaluate(batch_size, device, database, latent_graph_dict, latent_graph_list):
    # Set model to evaluation
    #model.eval()
    # Set up loss
    set_loss = []

    with torch.no_grad():
        # Get batches from data loader
        batch_p1, batch_p2, batch_pm, batch_target, batch_Temperature = data_loader(database, latent_graph_dict,
                                                                                    latent_graph_list, batch_size,
                                                                                    shuffle=False
                                                                                    )
        for btc in range(len(batch_p1)):
            # Get molecules 1 and two, as well as the membrane in batches, together with targets and temperature
            p1 = batch_p1[btc].to(device)
            p2 = batch_p2[btc].to(device)
            pm = batch_pm[btc].to(device)
            targ = batch_target[btc].detach().cpu().numpy()
            Temperature = batch_Temperature[btc].to(device)

            # Calculate loss
            out = model([p1, p2, pm, Temperature]).detach().cpu().numpy()
            #loss = criterion(out, targ)

            #loss_avg += loss.item()
            set_loss.append(np.mean(np.abs(out - targ)))

            # Empty CUDA cache
            torch.cuda.empty_cache()

    return np.sum(set_loss)/len(set_loss)
Example #2
0
def train(batch_size, device, database, latent_graph_dict, latent_graph_list):
    # Set model to training mode
    #model.train()
    # Set up loss
    loss_avg = 0

    # Get batches from data loader
    batch_p1, batch_p2, batch_pm, batch_target, batch_Temperature = data_loader(database, latent_graph_dict,
                                                                                latent_graph_list, batch_size,
                                                                                shuffle=True
                                                                                )
    for btc in range(len(batch_p1)):
        # Get molecules 1 and two, as well as the membrane in batches, together with targets and temperature
        p1 = batch_p1[btc].to(device)
        p2 = batch_p2[btc].to(device)
        pm = batch_pm[btc].to(device)
        targ = batch_target[btc].to(device)
        Temperature = batch_Temperature[btc].to(device)

        # Forward pass and gradient descent
        out = model([p1, p2, pm, Temperature])
        loss = criterion(out, targ)
        optimizer.zero_grad()

        loss.backward()
        optimizer.step()

        loss_avg += loss.item()

        # Empty CUDA cache
        torch.cuda.empty_cache()

    return loss_avg/len(batch_p1)
Example #3
0
def evaluate(model, criterion, batch_size, device, database, latent_graph_dict,
             latent_graph_list):
    # Set model to evaluation
    #model = model.eval()
    # Set up loss
    loss_avg = 0

    with torch.no_grad():
        # Get batches from data loader
        batch_p1, batch_p2, batch_pm, batch_target, batch_Temperature = data_loader(
            database,
            latent_graph_dict,
            latent_graph_list,
            batch_size,
            shuffle=False)
        for btc in range(len(batch_p1)):
            # Get molecules 1 and two, as well as the membrane in batches, together with targets and temperature
            p1 = batch_p1[btc].to(device)
            p2 = batch_p2[btc].to(device)
            pm = batch_pm[btc].to(device)
            targ = batch_target[btc].to(device)
            Temperature = batch_Temperature[btc].to(device)

            # Calculate loss
            out = model([p1, p2, pm, Temperature])
            loss = criterion(out, targ)

            loss_avg += loss.item()

            # Empty CUDA cache
            torch.cuda.empty_cache()

    return loss_avg / len(batch_p1)
Example #4
0
def plotter(path, model, database, latent_graph_dict, latent_graph_list,
            batch_size, device, name):

    # --- Making the directory where plots reside
    if not os.path.exists(path + "/" + name):
        os.mkdir(path + "/" + name)

    # --- Torch no grad for evaluation
    with torch.no_grad():
        batch_p1, batch_p2, batch_pm, batch_target, batch_Temperature = data_loader(
            database,
            latent_graph_dict,
            latent_graph_list,
            batch_size,
            shuffle=False)
        # Set up index to indicate which example is being plotted
        b_index = 0
        # Set up empty array for MAE calculation
        MAE_error = np.zeros(15)

        # Calculating each batch
        for btc in range(len(batch_p1)):
            p1 = batch_p1[btc].to(device)
            p2 = batch_p2[btc].to(device)
            pm = batch_pm[btc].to(device)
            targ = batch_target[btc].detach().cpu().numpy()
            Temperature = batch_Temperature[btc].to(device)

            out = model([p1, p2, pm, Temperature]).detach().cpu().numpy()

            for u in range(batch_size):
                # Make and save Dataframe that encompasses real and predicted values
                DF = pd.DataFrame(np.transpose(
                    [list(range(2, 17)), out[u], targ[u]]),
                                  columns=["CARBON", "PREDICT", "REAL"])

                img_name = str(database.loc[b_index]["Papertag"]) + "_" + str(database.loc[b_index]["Molecule1"]) \
                           + "_" + str(database.loc[b_index]["Molecule2"]) + "_" \
                           + str(database.loc[b_index]["Membrane"]) + "_" + str(database.loc[b_index]["molp1"]) \
                           + "_" + str(database.loc[b_index]["molp2"]) + "_" + str(database.loc[b_index]["molpm"]) \
                           + "_" + str(database.loc[b_index]["Temperature"])

                DF.to_csv(path + "/" + name + "/" + img_name + ".txt",
                          sep="\t",
                          index=False)

                # Adding to MAE error
                MAE_error += np.abs(DF["PREDICT"].values - DF["REAL"].values)

                # Plot the real and predicted results
                fig, axs = plt.subplots()
                axs.plot(DF["CARBON"].values,
                         DF["PREDICT"].values,
                         label="PREDICT")
                axs.plot(DF["CARBON"].values, DF["REAL"].values, label="REAL")
                axs.plot(DF["CARBON"].values, np.ones(15) * 10, label=img_name)
                axs.set_ylabel("Order parameter $S$")
                axs.set_xlabel("Carbon position $n$")
                axs.legend(loc=3)
                axs.set_ylim([0, 0.35 * 10])
                axs.legend()
                fig.savefig(path + "/" + name + "/" + img_name + ".png")
                plt.close("all")

                b_index += 1

        # Averaging the MAE error
        MAE_error /= (b_index + 1)

        # Save MAE error
        MAE_DF = pd.DataFrame(np.transpose(
            [list(range(2, 17)), list(MAE_error)]),
                              columns=["CARBON", "MAE_ERROR"])
        MAE_DF.to_csv(path + "/MAE_ERROR_" + name + ".txt",
                      sep="\t",
                      index=False)

    return MAE_DF