我正在尝试使用用于国际象棋符号的 64 行 FEN 代码为 TensorFlow 创建一个张量,但在尝试定义张量时出现 TypeError。我是 TensorFlow 的新手,如果这是一个菜鸟问题,我深表歉意。但是,我似乎无法在网上找到类似的问题。我的 X 值是每块棋盘一列,加上轮到谁的“白色”或“黑色”值。评估是表示谁获胜的数字,我将其转换为简单的“白色”或“黑色”。
import pandas as pd
from sklearn import preprocessing
df = pd.read_csv ('medchessData.csv')
#rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR
allgames=[]
for game in df.FEN.values:
values = game.split(' ')
game = values[0]
currentgameboard=["X" for i in range(65)]
if values[1] == "w" or values[1] == "b":
turn = values[1]
currentgameboard[64]=turn
squareval=0
for value in game:
if value == "/":
continue
try:
value = int(value)
except:
pass
if value in range (-5,30):
squareval+=int(value)
continue
currentgameboard[squareval]=value
squareval+=1
allgames.append(currentgameboard)
evaluations=[]
for evaluation in df.Evaluation.values:
#evalsign = "neg" if evaluation[0] == "-" else "pos"
#eval = int(evaluation[1:])
#if evalsign == "neg":
#eval=eval*-1
if evaluation[0]=="#":
evaluation=evaluation[1:]
try:
evaluations.append(int(evaluation))
except:
try:
evaluation=evaluation[-1:]
evaluations.append(int(evaluation))
except:
try:
evaluation=evaluation[-2:]
evaluations.append(int(evaluation))
except:
evaluation=evaluation[-3:]
evaluations.append(int(evaluation))
for i in range(len(evaluations)):
if evaluations[i]>1:
evaluations[i]="white"
elif evaluations[i]<1:
evaluations[i]="black"
else:
evaluations[i]="tie"
print(evaluations[0:10])
le = preprocessing.LabelEncoder()
allgamestrans=[]
for game in allgames:
le.fit(game)
le.classes_
allgamestrans.append(le.transform(game))
X = pd.DataFrame(allgames)
y = pd.DataFrame(evaluations)
X=X.join(y,lsuffix='_')
X.rename(columns={ X.columns[65]: "label" }, inplace = True)
print(X.head())
print(y.head())
X.to_csv('X.csv',index=False)
y.to_csv('y.csv',index=False)
print(X.index)
print(y.index)
import numpy as np
import pandas as pd
print("starting")
import tensorflow as tf
from tensorflow import feature_column
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split
dataframe=X
train, val, test = np.split(dataframe.sample(frac=1), [int(0.8*len(dataframe)), int(0.9*len(dataframe))])
print(len(train), 'training examples')
print(len(val), 'validation examples')
print(len(test), 'test examples')
def df_to_dataset(dataframe, shuffle=True, batch_size=32):
df = dataframe.copy()
labels = X.pop("label")
df = {key: value[:,tf.newaxis] for key, value in dataframe.items()}
import numpy as np
np.array(labels)[:, None]
** ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))
** if shuffle:
ds = ds.shuffle(buffer_size=len(dataframe))
ds = ds.batch(batch_size)
ds = ds.prefetch(batch_size)
return ds
batch_size = 5 # A small batch sized is used for demonstration purposes
train_ds = df_to_dataset(train, y, batch_size=batch_size)
val_ds = df_to_dataset(val, y, shuffle=False, batch_size=batch_size)
test_ds = df_to_dataset(test, y, shuffle=False, batch_size=batch_size)
# We will use this batch to demonstrate several types of feature columns
example_batch = next(iter(train_ds))[0]
def demo(feature_column):
feature_layer = layers.DenseFeatures(feature_column)
print(feature_layer(example_batch).numpy())
crossed_feature = feature_column.crossed_column([age_buckets, animal_type], hash_bucket_size=64)
demo(feature_column.indicator_column(crossed_feature))
feature_columns = []
for i in range(64):
feature_columns.append(feature_column.indicator_column(str(i)))
model = tf.keras.Sequential([
feature_layer,
layers.Dense(128, activation='relu'),
layers.Dense(128, activation='relu'),
layers.Dropout(.1),
layers.Dense(1)
])
print("compiling")
model.compile(optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
print("fitting")
model.fit(train_ds,
validation_data=val_ds,
epochs=10)
loss, accuracy = model.evaluate(test_ds)
print("Accuracy", accuracy)
输出为:
['black', 'white', 'black', 'white', 'black', 'white', 'white', 'white', 'white', 'white']
0_ 1 2 3 4 5 6 7 8 9 ... 56 57 58 59 60 61 62 63 64 label
0 r n b q k b n r p p ... R N B Q K B N R b black
1 r n b q k b n r p p ... R N B Q K B N R w white
2 r n b q k b n r p p ... R N B Q K B N R b black
3 r n b q k b n r p p ... R N B Q K B N R w white
4 r n b q k b n r p p ... R X B Q K B N R b black
[5 rows x 66 columns]
0
0 black
1 white
2 black
3 white
4 black
RangeIndex(start=0, stop=196482, step=1)
RangeIndex(start=0, stop=196482, step=1)
starting
157185 training examples
19648 validation examples
19649 test examples
<ipython-input-35-39422f4fd435>:90: FutureWarning: Support for multi-dimensional indexing (e.g. `obj[:, None]`) is deprecated and will be removed in a future version. Convert to a numpy array before indexing instead.
df = {key: value[:,tf.newaxis] for key, value in dataframe.items()}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-39422f4fd435> in <cell line: 100>()
98 return ds
99 batch_size = 5 # A small batch sized is used for demonstration purposes
--> 100 train_ds = df_to_dataset(train, y, batch_size=batch_size)
101 val_ds = df_to_dataset(val, y, shuffle=False, batch_size=batch_size)
102 test_ds = df_to_dataset(test, y, shuffle=False, batch_size=batch_size)
4 frames
/usr/local/lib/python3.9/dist-packages/tensorflow/python/data/util/structure.py in normalize_element(element, element_signature)
91 normalized_components = []
92 if element_signature is None:
---> 93 components = nest.flatten(element)
94 flattened_signature = [None] * len(components)
95 pack_as = element
TypeError: '<' not supported between instances of 'int' and 'str'
抱歉,如果之前已经问过这个问题的一个版本,我能找到的只是与张量无关的类型错误。
我不知道要尝试什么,因为我遵循这里的指南:https://www.tensorflow.org/tutorials/structured_data/preprocessing_layers我相信我是按照指示去做的。我应该创建一个 NeuralNet