import torch as t
from torch import nn
import torch.nn.functional as F
import pandas as pd
import sklearn as sc
from sklearn.feature_extraction import DictVectorizer as DV
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = 'FreeSerif'
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['lines.markersize'] = 12
plt.rcParams['xtick.labelsize'] = 24
plt.rcParams['ytick.labelsize'] = 24
plt.rcParams['legend.fontsize'] = 24
plt.rcParams['axes.titlesize'] = 26
plt.rcParams['axes.labelsize'] = 24
columnNames = ['WKingLetter','WKingPos', 'WRookLetter', 'WRookPos', 'BKingLetter', 'BKingPos',
'optimal depth-of-win for White in 0 to 16 moves/draw']
data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/chess/king-rook-vs-king/krkopt.data',
names = columnNames, header=None)
data.head()
WKingLetter | WKingPos | WRookLetter | WRookPos | BKingLetter | BKingPos | optimal depth-of-win for White in 0 to 16 moves/draw | |
---|---|---|---|---|---|---|---|
0 | a | 1 | b | 3 | c | 2 | draw |
1 | a | 1 | c | 1 | c | 2 | draw |
2 | a | 1 | c | 1 | d | 1 | draw |
3 | a | 1 | c | 1 | d | 2 | draw |
4 | a | 1 | c | 2 | c | 1 | draw |
data.shape[0]
28056
X = data.drop(['optimal depth-of-win for White in 0 to 16 moves/draw'], axis=1)
X.head()
WKingLetter | WKingPos | WRookLetter | WRookPos | BKingLetter | BKingPos | |
---|---|---|---|---|---|---|
0 | a | 1 | b | 3 | c | 2 |
1 | a | 1 | c | 1 | c | 2 |
2 | a | 1 | c | 1 | d | 1 |
3 | a | 1 | c | 1 | d | 2 |
4 | a | 1 | c | 2 | c | 1 |
strings = ['WKingLetter', 'WRookLetter', 'BKingLetter']
for s in strings:
X[s].replace(to_replace=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8), inplace=True)
X.head()
WKingLetter | WKingPos | WRookLetter | WRookPos | BKingLetter | BKingPos | |
---|---|---|---|---|---|---|
0 | 1 | 1 | 2 | 3 | 3 | 2 |
1 | 1 | 1 | 3 | 1 | 3 | 2 |
2 | 1 | 1 | 3 | 1 | 4 | 1 |
3 | 1 | 1 | 3 | 1 | 4 | 2 |
4 | 1 | 1 | 3 | 2 | 3 | 1 |
target = data['optimal depth-of-win for White in 0 to 16 moves/draw']
target.replace(to_replace=dict(zero=0, one=1, two=2, three=3, four=4, five=5, six=6, seven=7, eight=8,
nine=9, ten=10, eleven=11, twelve=12, thirteen=13, fourteen=14, fifteen=15, sixteen=16, draw=17), inplace=True)
target.head()
0 17 1 17 2 17 3 17 4 17 Name: optimal depth-of-win for White in 0 to 16 moves/draw, dtype: int64
model = nn.Sequential()
model.add_module('l1', nn.Linear(6, 1))
model.add_module('l2', nn.Sigmoid())
print("Weight shapes:", [w.shape for w in model.parameters()])
Weight shapes: [torch.Size([1, 6]), torch.Size([1])]
X_data_train, X_data_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.5,
random_state=k)
x = torch.tensor(X_train[:3], dtype=torch.float32)
y = torch.tensor(y_train[:3], dtype=torch.float32)
y_predicted = model(x)[:, 0]
y_predicted