³µÍ× †numpy¤ò»ÈÍѤ·¤¿½Å²óµ¢Ê¬ÀÏ ¤ä scikit-learn¤ò»ÈÍѤ·¤¿½Å²óµ¢Ê¬ÀÏ¡¢Chainer¤Ç½Å²óµ¢Ê¬ÀϤò¤ä¤Ã¤Æ¤ß¤ë ¤Ç¼ÂÁõ¤·¤¿ÄÂÂß²Á³Ê¤Î¿äÏÀ¤ÈƱ¤¸»ö¤ò PyTorch ¤ò»ÈÍѤ·¤Æ¤ä¤Ã¤Æ¤ß¤ë¡£ Ìܼ¡ †
´Ä¶¹½ÃÛ †mkdir sample_pytorch cd sample_pytorch python3 -m venv venv source venv/bin/activate pip3 install torch torchvision pip3 install sklearn ¼ÂÁõ †¸µ¡¹¤Ï Chainer ¤Î Fork ¤À¤Ã¤¿¤é¤·¤¯¡¢º£²ó¼ÂÁõ¤·¤¿ÆâÍƤÀ¤ÈËؤÉChainer¤ÈÊѤï¤é¤Ê¤«¤Ã¤¿¡£(´ØÏ¢: Chainer¤Ç½Å²óµ¢Ê¬ÀϤò¤ä¤Ã¤Æ¤ß¤ë) sample_pytorch.py import torch import torch.nn as nn import numpy as np from sklearn.preprocessing import StandardScaler # ¥Ñ¥é¥á¡¼¥¿ input_size = 2 # ÀâÌÀÊÑ¿ô¤Î¿ô output_size = 1 # ¿äÏÀÃͤοô alpha = 0.01 # ³Ø½¬Î¨ epochs = 1000 # ³Ø½¬²ó¿ô # ¥µ¥ó¥×¥ë¥Ç¡¼¥¿¤ÎÆɤ߹þ¤ß data = np.loadtxt("data/sample_rent1.csv", delimiter=",", skiprows=1) x_train = data[:, 1:3].astype("float32") # ¹¤µ, ÃÛǯ¿ô y_train = data[:, 3:4].astype("float32") # ²ÈÄ # ¥â¥Ç¥ëÄêµÁ class LinearRegression(nn.Module): def __init__(self, input_size, output_size): super(LinearRegression, self).__init__() self.linear = nn.Linear(input_size, output_size) def forward(self, x): out = self.linear(x) return out model = LinearRegression(input_size, output_size) #model = nn.Linear(input_size, output_size) # »¼º´Ø¿ô loss = nn.MSELoss() # ºÇŬ²½´Ø¿ô optimizer = torch.optim.SGD(model.parameters(), lr=alpha) # ɸ½à²½ÍÑ scaler = StandardScaler() scaler.fit(x_train) # ¥â¥Ç¥ë¤Î·±Îý for epoch in range(epochs): # ɸ½à²½ x_train_scaled = scaler.transform(x_train) # ¥Ç¡¼¥¿¤ò¥Æ¥ó¥½¥ë¤ØÊÑ´¹ inputs = torch.from_numpy(x_train_scaled) targets = torch.from_numpy(y_train) # ¥³¥¹¥È¤ò»»½Ð outputs = model(inputs) cost = loss(outputs, targets) # ¸ûÇۤΥꥻ¥Ã¥È¤È¸ûÇۤη׻» optimizer.zero_grad() cost.backward() optimizer.step() # 100²ó¤´¤È¤Ë¸íº¹É½¼¨ if (epoch + 1) % 100 == 0: print('Epoch [{}], Loss: {:.4f}'.format(epoch + 1, cost.item())) # Ǥ°Õ¤ÎÃͤò¿äÏÀ¤·¤Æ¤ß¤ë x_sample = np.array([[60.0, 10.0], [50.0, 10.0], [40.0, 10.0]]) x_sample_scaled = scaler.transform(x_sample) inputs = torch.Tensor(x_sample_scaled) results = model(inputs) for i in range(results.size()[0]): print('¹¤µ:{}Ö, ÃÛǯ¿ô:{}, ²ÈÄÂ:{:.2f}'.format(x_sample[i,0], x_sample[i,1], results.data[i,0].item())) # ·±ÎýºÑ¤ß¥â¥Ç¥ë¤òÊݸ #torch.save(model.state_dict(), 'sample.pth') ·ë²Ì †·ë²Ì¤Ï¤Û¤Ü Chainer¤Ç½Å²óµ¢Ê¬ÀϤò¤ä¤Ã¤Æ¤ß¤ë ¤ÈƱ¤¸¡£ $ python3 sample_pytorch.py Epoch [100], Loss: 1.2303 Epoch [200], Loss: 0.5337 Epoch [300], Loss: 0.5213 Epoch [400], Loss: 0.5211 Epoch [500], Loss: 0.5211 Epoch [600], Loss: 0.5211 Epoch [700], Loss: 0.5211 Epoch [800], Loss: 0.5211 Epoch [900], Loss: 0.5211 Epoch [1000], Loss: 0.5211 ¹¤µ:60.0Ö, ÃÛǯ¿ô:10.0, ²ÈÄÂ:8.12 ¹¤µ:50.0Ö, ÃÛǯ¿ô:10.0, ²ÈÄÂ:7.19 ¹¤µ:40.0Ö, ÃÛǯ¿ô:10.0, ²ÈÄÂ:6.27 |