machine-learning - TensorFlow 2 XOR 实现
问题描述
我是一个 tensorflow 新手,首先我想训练 XOR 模型,给出 4 个具有 2 个值的输入并学习 4 个具有 1 个值的输出。这是我在 TF 2 中所做的
model = keras.Sequential([
keras.layers.Input(shape=(2,)),
keras.layers.Dense(units=2, activation='relu'),
keras.layers.Dense(units=1, activation='softmax')
])
model.compile(optimizer='adam',
loss=tf.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(
(tf.cast([[0,0],[0,1],[1,0],[1,1]], tf.float32), tf.cast([0,1,1,0], tf.float32)),
epochs=4,
steps_per_epoch=1,
validation_data=(tf.cast([[0.7, 0.7]], tf.float32), tf.cast([0], tf.float32)),
validation_steps=1
)
上面的代码给出错误IndexError: list index out of range
请帮我解决这个问题,我想了解如何想出形状来给模型。
解决方案
您在 fit 函数中分配参数时遇到问题:
history = model.fit(
(tf.cast([[0,0],[0,1],[1,0],[1,1]], tf.float32), tf.cast([0,1,1,0], tf.float32)),
epochs=4,
steps_per_epoch=1,
validation_data=(tf.cast([[0.7, 0.7]], tf.float32), tf.cast([0], tf.float32)),
validation_steps=1)
尝试用以下内容替换该行:
x_train = tf.cast([[0,0],[0,1],[1,0],[1,1]], tf.float32)
y_train = tf.cast([0,1,1,0], tf.float32)
x_test = tf.cast([[0.7, 0.7]], tf.float32)
y_test = tf.cast([0], tf.float32)
history = model.fit(
x=x_train, y=y_train,
epochs=4,
steps_per_epoch=1,
validation_data=(x_test, y_test),
validation_steps=1
)
你的问题应该得到解决。
PS:只是一个建议,当你在进行二元分类时,尝试使用 sigmoid 代替 softmax,并分别使用 BinaryCrossentropy loss 代替 CategoricalCrossentropy。祝你好运
推荐阅读
- memory - 需要 ansible 模块来监控 Solaris 使用的内存
- github-api - 在 GitHub 提交上设置状态时设置状态名称
- python - 如何使用“断言”命令将输入限制为仅获取一组数据中的列数?
- javascript - MUI 错误:无法读取未定义的属性(读取“抽屉”)
- php - 如何处理来自 Google API 的 500 个错误
- c# - 如何创建索引事件处理程序?
- azure-devops - 在 Azure Pipelines 中管理 CI/CD 流?
- kotlin - Kotlin / 值传递给 List<>()
- asp.net-core - 设置默认序列化器/反序列化器
- python - 在不添加权重属性的情况下查找图中两个节点之间的所有最短路径