Last active
May 13, 2018 09:09
-
-
Save RottenFruits/a151c388e3c5fa7eda6b47749cf093d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [], | |
"source": [ | |
"#データ準備\n", | |
"import pandas as pd\n", | |
"from sklearn import datasets\n", | |
"\n", | |
"iris = datasets.load_iris()\n", | |
"df = pd.DataFrame(iris.data, columns=iris.feature_names)\n", | |
"df['target'] = iris.target_names[iris.target]" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [], | |
"source": [ | |
"import torch\n", | |
"import numpy as np\n", | |
"\n", | |
"#ラベルを数値化\n", | |
"y = np.array(df['target'].astype('category').cat.codes).astype(float)\n", | |
"X = np.array(df.iloc[:, :4])\n", | |
"\n", | |
"#学習データと検証データを分割\n", | |
"from sklearn.model_selection import train_test_split\n", | |
"train_X, val_X, train_y, val_y = train_test_split(\n", | |
" X, y, test_size = 0.2, random_state=71)\n", | |
"\n", | |
"\n", | |
"# tensor型に変換\n", | |
"train_X = torch.Tensor(train_X)\n", | |
"val_X = torch.Tensor(val_X)\n", | |
"train_y = torch.LongTensor(train_y)\n", | |
"val_y = torch.LongTensor(val_y)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"Net(\n", | |
" (fc1): Linear(in_features=4, out_features=100, bias=True)\n", | |
" (fc2): Linear(in_features=100, out_features=50, bias=True)\n", | |
" (fc3): Linear(in_features=50, out_features=3, bias=True)\n", | |
")\n" | |
] | |
} | |
], | |
"source": [ | |
"#ネットワーク定義\n", | |
"import torch.nn as nn\n", | |
"import torch.nn.functional as F\n", | |
"from torch.autograd import Variable\n", | |
"\n", | |
"torch.manual_seed(71) #seed固定、ネットワーク定義前にする必要ありそう\n", | |
"\n", | |
"class Net(nn.Module):\n", | |
"\n", | |
" def __init__(self):\n", | |
" super(Net, self).__init__()\n", | |
" self.fc1 = nn.Linear(4, 100)\n", | |
" self.fc2 = nn.Linear(100, 50)\n", | |
" self.fc3 = nn.Linear(50, 3)\n", | |
"\n", | |
" def forward(self, x):\n", | |
" x = F.relu(self.fc1(x))\n", | |
" x = F.relu(self.fc2(x))\n", | |
" x = self.fc3(x)\n", | |
" return F.log_softmax(x, dim = 1)\n", | |
"\n", | |
"model = Net()\n", | |
"print(model)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 4, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"Train Step: 0\tLoss: 1.152\tAccuracy: 0.317\n", | |
"Train Step: 10\tLoss: 0.954\tAccuracy: 0.683\n", | |
"Train Step: 20\tLoss: 0.835\tAccuracy: 0.683\n", | |
"Train Step: 30\tLoss: 0.711\tAccuracy: 0.683\n", | |
"Train Step: 40\tLoss: 0.616\tAccuracy: 0.692\n", | |
"Train Step: 50\tLoss: 0.547\tAccuracy: 0.717\n", | |
"Train Step: 60\tLoss: 0.496\tAccuracy: 0.783\n", | |
"Train Step: 70\tLoss: 0.457\tAccuracy: 0.867\n", | |
"Train Step: 80\tLoss: 0.425\tAccuracy: 0.917\n", | |
"Train Step: 90\tLoss: 0.399\tAccuracy: 0.925\n", | |
"Train Step: 100\tLoss: 0.377\tAccuracy: 0.942\n" | |
] | |
} | |
], | |
"source": [ | |
"#学習\n", | |
"import torch.optim as optim\n", | |
"\n", | |
"optimizer = optim.SGD(model.parameters(), lr=0.02)\n", | |
"train_loss = []\n", | |
"train_accu = []\n", | |
"i = 0\n", | |
"\n", | |
"model.train() #学習モード\n", | |
"for epoch in range(100):\n", | |
" data, target = Variable(train_X), Variable(train_y)#微分可能な型\n", | |
" optimizer.zero_grad() #勾配初期化\n", | |
" output = model(data) #データを流す\n", | |
" \n", | |
" loss = F.nll_loss(output, target) #loss計算\n", | |
" loss.backward() #バックプロパゲーション\n", | |
" train_loss.append(loss.data.item())\n", | |
" optimizer.step() # 重み更新\n", | |
" \n", | |
" prediction = output.data.max(1)[1] #予測結果\n", | |
" accuracy = prediction.eq(target.data).sum().numpy() / len(train_X) #正解率\n", | |
" train_accu.append(accuracy)\n", | |
" \n", | |
" if i % 10 == 0:\n", | |
" print('Train Step: {}\\tLoss: {:.3f}\\tAccuracy: {:.3f}'.format(i, loss.data.item(), accuracy))\n", | |
" i += 1\n", | |
" \n", | |
"print('Train Step: {}\\tLoss: {:.3f}\\tAccuracy: {:.3f}'.format(i, loss.data.item(), accuracy))" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 5, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"Accuracy: 0.867\n" | |
] | |
} | |
], | |
"source": [ | |
"#精度検証\n", | |
"model.eval() #推論モード\n", | |
"\n", | |
"outputs = model(Variable(val_X))\n", | |
"_, predicted = torch.max(outputs.data, 1)\n", | |
"print('Accuracy: {:.3f}'.format(predicted.eq(val_y).sum().numpy() / len(predicted)))" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [], | |
"source": [] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [], | |
"source": [] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.5.4" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment