Convert Pandas dataframe to PyTorch tensor?

前端 未结 4 1506
傲寒
傲寒 2020-12-29 18:59

I want to train a simple neural network on PyTorch using a personal database. This database is imported from an Excel file and stored in df.

One of the

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 19:40

    You can use below functions to convert any dataframe or pandas series to a pytorch tensor

    import pandas as pd
    import torch
    
    # determine the supported device
    def get_device():
        if torch.cuda.is_available():
            device = torch.device('cuda:0')
        else:
            device = torch.device('cpu') # don't have GPU 
        return device
    
    # convert a df to tensor to be used in pytorch
    def df_to_tensor(df):
        device = get_device()
        return torch.from_numpy(df.values).float().to(device)
    
    df_tensor = df_to_tensor(df)
    series_tensor = df_to_tensor(series)
    

提交回复
热议问题