Skip to content

Instantly share code, notes, and snippets.

@gokceneraslan
Created November 4, 2017 22:31
Show Gist options
  • Save gokceneraslan/7e9def2eb53dea473d26598598862ad9 to your computer and use it in GitHub Desktop.
Save gokceneraslan/7e9def2eb53dea473d26598598862ad9 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/gokcen/.miniconda3/lib/python3.6/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.\n",
" from pandas.core import datetools\n",
"Using TensorFlow backend.\n"
]
}
],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"import plotnine as p9\n",
"\n",
"import torch\n",
"from torch.autograd import Variable\n",
"from torch.utils.data import TensorDataset, DataLoader, Dataset\n",
"\n",
"np.random.seed(555)\n",
"torch.manual_seed(555)\n",
"\n",
"num_sample = 300\n",
"num_feat = 10\n",
"num_out = 10\n",
"\n",
"batch_size = 32\n",
"lr = 1e-4\n",
"epochs = 300\n",
"\n",
"X = np.random.normal(0, 0.5, (num_sample, num_feat)).astype(np.float64)\n",
"W = np.random.normal(0, 0.5, (num_feat, num_out)).astype(np.float64)\n",
"b = np.random.normal(0, 0.5, (1, num_out)).astype(np.float64)\n",
"Y = np.dot(X, W) + b\n",
"X -= X.mean(0)\n",
"\n",
"ds = TensorDataset(torch.from_numpy(X).double(), torch.from_numpy(Y).double())\n",
"\n",
"# train torch models with and without shuffling\n",
"model1 = torch.nn.Linear(num_feat, num_out).double()\n",
"opt1 = torch.optim.SGD(model1.parameters(), lr=lr)\n",
"loss1 = torch.nn.MSELoss()\n",
"\n",
"train_hist_torch = []\n",
"\n",
"for epoch in range(epochs):\n",
"\n",
" train_batch_losses = []\n",
" for x, y in DataLoader(ds, batch_size=batch_size, shuffle=True, drop_last=True):\n",
" x_var, y_var = Variable(x, requires_grad=False), Variable(y, requires_grad=False)\n",
" pred = model1(x_var)\n",
" l = loss1(pred, y_var)\n",
" train_batch_losses.append(l.data[0])\n",
"\n",
" opt1.zero_grad()\n",
" l.backward()\n",
" opt1.step()\n",
"\n",
" # save mean of all batch errors within the epoch\n",
" train_hist_torch.append(np.array(train_batch_losses).mean())\n",
"\n",
"\n",
"from keras.models import Model\n",
"from keras.layers import Input, Dense\n",
"from keras.optimizers import SGD\n",
"from keras import backend as K\n",
"\n",
"\n",
"inputs = Input(shape=(num_feat,))\n",
"predictions = Dense(num_out, activation='linear')(inputs)\n",
"model = Model(inputs=inputs, outputs=predictions)\n",
"\n",
"opt = SGD(lr=lr)\n",
"model.compile(optimizer=opt, loss='mse')\n",
"losses = model.fit(X, Y,\n",
" batch_size=batch_size,\n",
" epochs=epochs, verbose=0, shuffle=True)\n",
" \n",
"train_hist_keras = losses.history['loss']\n",
" \n",
"(p9.ggplot(pd.DataFrame({'torch_train_torch': train_hist_torch,\n",
" 'torch_train_keras': train_hist_keras,\n",
" 'epochs': range(len(train_hist_torch))}),\n",
" p9.aes(x='epochs')) +\n",
" p9.geom_path(p9.aes(y='torch_train_torch', color='\"training loss (sgd, torch)\"')) +\n",
" p9.geom_path(p9.aes(y='torch_train_keras', color='\"training loss (sgd, keras)\"')) +\n",
" p9.labs(color='Loss', y=' ') +\n",
" p9.theme_minimal())"
]
}
],
"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.6.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment