神经网络不训练

时间:2019-04-26 08:28:36

标签: tensorflow keras

我正在使用tensorflow / keras玩一点,并尝试创建一个小的神经网络,该网络训练我产生的一些随机数据。但是,无论我更改数据集或图层的大小如何,我总是得到的精度为0。这里我在做什么错了?

import tensorflow as tf
import numpy as np
import math

numbers = np.random.randint(0, 101, (1000000,3))
labels = np.array([0 if x[0] < 50 and x[1] < 50 and x[2] < 50 else
                 1 if x[0] >= 50 and x[1] < 50 and x[2] < 50 else
                 2 if x[0] < 50 and x[1] >= 50 and x[2] < 50 else 
                 3 if x[0] < 50 and x[1] < 50 and x[2] >= 50 else
                 4 if x[0] >= 50 and x[1] >= 50 and x[2] < 50 else
                 5 if x[0] >= 50 and x[1] < 50 and x[2] >= 50 else
                 6 if x[0] < 50 and x[1] >= 50 and x[2] >= 50 else
                 7 for x in numbers])

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(256, input_shape=(3,), activation='relu'))
model.add(tf.keras.layers.Dense(512, activation='relu'))
model.add(tf.keras.layers.Dense(1024, activation='relu'))
model.add(tf.keras.layers.Dense(8, activation='softmax'))

model.compile(optimizer='adam',
             loss='categorical_crossentropy',
             metrics=['accuracy'])

BATCH_SIZE = 5000
train_dataset = tf.data.Dataset.from_tensor_slices((numbers, labels))
train_dataset = train_dataset.repeat().shuffle(len(numbers)).batch(BATCH_SIZE)

model.fit(train_dataset, epochs = 10, steps_per_epoch=len(numbers)/BATCH_SIZE)

我希望它获得的准确度要好于机会(准确度为0.125),但我总是得到0。

1 个答案:

答案 0 :(得分:0)

我刚刚意识到损失函数'categorical_crossentropy'在我的情况下是错误的;将其更改为'sparse_categorical_crossentropy'将我的准确性提高到〜78%,因此我认为这件事已经解决了。但是,如果我的代码还有其他问题,请发表评论,因为我仍然是新手并且正在学习。 :)

相关问题