LoginSignup
1
1

More than 1 year has passed since last update.

【python,pytorch】表形式データをpytorchでテンソルにする

Posted at

後で自分が振り返る用の記事。表形式データをテンソルに変換し、NNで訓練できる形にすることが目標。

import

import numpy as np
import pandas as pd
import torch
torch.set_printoptions(edgeitems=2, threshold=50)

表形式データの準備

a = np.arange(1,10)
b = np.arange(11,20)
c = np.arange(21,30)
d = np.arange(1,10)
target = np.random.rand(9)
target = [round(x) for x in target]

d = d.astype('str')
d[:4] = 'a'
d[4:] = 'b'

data = pd.DataFrame([a,b,c,d,target]).T
data.columns = ['A','B','C','D','target']

data

出力結果

A B C D target
0 1 11 21 a 1
1 2 12 22 a 0
2 3 13 23 a 0
3 4 14 24 a 0
4 5 15 25 b 1
5 6 16 26 b 0
6 7 17 27 b 0
7 8 18 28 b 0
8 9 19 29 b 0

one-hot-encoding

テンソルは数値型しか受け付けないのでDカラムを数値に変換する

data.D = pd.get_dummies(data.D, drop_first=True)

データ型を変更

データの型を整えないと後ほど、エラーが出る。

data[['A','B','C','target']] = data[['A','B','C','target']].astype('float32')
エラー内容
# can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

テンソルに変換する2つの方法

numpy配列からテンソルを作る方法

# numpyからテンソルを作る方法
torch.from_numpy(data.to_numpy())

データフレームからテンソルを作る方法

test_tensor = torch.tensor(data.values)
test_tensor.shape, test_tensor.dtype

目的変数と説明変数を切り分け

今回は2次元テンソルなので、場所を特定するには2つの値の指定が必要。

# 説明変数
train = test_tensor[:,:-1]
print(train, train.shape)
# 目的変数
target_tensor = test_tensor[:,-1]
print(target_tensor, target_tensor.shape)

目的変数を整形

# 目的変数をint型に変換
target_tensor = target_tensor.long()
target_tensor.shape
# サイズを出力用の形に整える
target_tensor_unsq = target_tensor.unsqueeze(1)
target_tensor_unsq.shape
# 出力結果 torch.Size([9, 1])

説明変数を標準化

# trainの標準化
train_mean = torch.mean(train)
train_sd = torch.std(train)
train_n = (train - train_mean)/train_sd
train_n
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1