Intento construir un red neuronal para juegar al juego de Domineering. Tengo una base de datos de juegos que pueden obtener aqui. Estas son líneas que representan los juegos en las bandejas 8 * 8, luego el reverso en 8 * 8 luego 8 * 8 en las figuras que dicen qué jugada se jugó y finalmente la tabla correspondiente.
Por ejemplo, líneas de csv para una placa 2x2:
0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0
Para juegos 8*8 esto hace 256 cifras. Las dimensiones de la entrada son por lo tanto de 126 columnas para el board y su reverso, los demas son para el output.
Sin embargo cuando intento construir el red neuronal intento construir 12 nodos para 128 inputs parece que hay un problema con la primera capa model.add(Dense(12, input_dim=128, activation='relu'))
# model construction
model = Sequential()
model.add(Dense(12, input_dim=128, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(128, activation='sigmoid'))
print("compile")
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print("fit")
model.fit(X_test, Y_test, epochs=3, batch_size=10)
En efecto me da el siguiente value error :
ValueError: Error when checking target: expected dense_27 to have shape (128,) but got array with shape (127,)
Y cuando intento reemplazar por 127, solo para ver me dice :
ValueError: Error when checking input: expected dense_28_input to have shape (127,) but got array with shape (128,)
Aqui esta el entero codigo, que pueden obtener sobre GitHub tambien. Es el ipython notebook.
#!/usr/bin/env python3
from timeit import default_timer as timer
import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from keras.models import Sequential
from keras.layers import Dense
# we divide data.csv into train and tests
with open("data.csv", 'r') as f:
plays = np.array(list(csv.reader(f, delimiter=",")))
print(plays.shape)
# We take the 126 first columns as input
df = pd.DataFrame(data=plays[0:28961,1:256])
# We take the 126 last columns as output
Y = pd.DataFrame(data=plays[0:28961,129:256])
#plays.reshape((64,64))
#board = np.reshape(plays, (8, 8))
df['split'] = np.random.randn(df.shape[0], 1)
msk = np.random.rand(len(df)) <= 0.7
train_df = df[msk].fillna("sterby")
test_df = df[~msk].fillna("sterby")
# we take the 128 first columns has input
X_train = train_df.iloc[:,0:128].values
# we take the 128 last columns has input
y_train = train_df.iloc[:,129:].values
X_test = test_df.iloc[:,0:128].values
Y_test = test_df.iloc[:,129:].values
# Necesary Keras Importations
from keras.preprocessing import sequence
from keras.models import Model, Input
from keras.layers import Dense, Embedding, GlobalMaxPooling1D
from keras.preprocessing.text import Tokenizer
from keras.optimizers import Adam
# model construction
model = Sequential()
model.add(Dense(12, input_dim=128, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(128, activation='sigmoid'))
print("compile")
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print("fit")
model.fit(X_test, Y_test, epochs=3, batch_size=10)
print("evaluate")
# evaluate the model
scores = model.evaluate(X_test, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
Y el error
compile
fit
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-60-8b0dc569bd70> in <module>()
3
4 print("fit\n")
----> 5 model.fit(X_test, Y_test, epochs=3, batch_size=10)
6
7 # evaluate the model
/usr/local/lib/python3.5/dist-packages/keras/models.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
961 initial_epoch=initial_epoch,
962 steps_per_epoch=steps_per_epoch,
--> 963 validation_steps=validation_steps)
964
965 def evaluate(self, x=None, y=None,
/usr/local/lib/python3.5/dist-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
1628 sample_weight=sample_weight,
1629 class_weight=class_weight,
-> 1630 batch_size=batch_size)
1631 # Prepare validation data.
1632 do_validation = False
/usr/local/lib/python3.5/dist-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
1478 output_shapes,
1479 check_batch_axis=False,
-> 1480 exception_prefix='target')
1481 sample_weights = _standardize_sample_weights(sample_weight,
1482 self._feed_output_names)
/usr/local/lib/python3.5/dist-packages/keras/engine/training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
121 ': expected ' + names[i] + ' to have shape ' +
122 str(shape) + ' but got array with shape ' +
--> 123 str(data_shape))
124 return data
125
ValueError: Error when checking target: expected dense_12 to have shape (128,) but got array with shape (127,)