【问题标题】:Why is my BP neural network's accuracy too low?为什么我的 BP 神经网络的准确率太低?
【发布时间】:2020-04-13 05:33:36
【问题描述】:

作业是通过 BP 神经网络识别手写数字。我试过添加隐藏层,增加单位和改变激活,动量,但结果显示:

测试累计:0.11142061281337047

分割数据集 X:(1797,64) Y(1797,)

np.random.shuffle(X)
np.random.shuffle(y)
offset1=int(len(X)*0.6)
offset2=int(len(X)*0.8)
offset3=len(X)-1
X_train, y_train = X[0:offset1,:], y[0:offset1]
X_valid, y_valid = X[offset1:offset2,:], y[offset1:offset2]
X_test, y_test = X[offset2:offset3,:], y[offset2:offset3]

还有我的神经网络:

def create_network():
  # TODO
  net = tf.keras.Sequential()
  net.add(tf.keras.layers.Flatten())
  net.add(tf.keras.layers.Dense(64, activation='relu'))
  net.add(tf.keras.layers.Dense(64, activation='relu'))
  net.add(tf.keras.layers.Dense(10, activation='softmax'))
  net.compile(
      optimizer='adam',
      #tf.optimizers.SGD(learning_rate=0.01, momentum=0.0, nesterov=False), 
      loss="sparse_categorical_crossentropy", 
      metrics=["accuracy"])
  return net


def train_network(network,
                  X_train,
                  y_train,
                  X_valid,
                  y_valid,
                  n_epoch=32,
                  batch_size=64):
  n_iter = 0
  network.fit(x=X_train, y=y_train, epochs=n_epoch, validation_data=(X_valid,y_valid))
  #opt = tf.optimizers.SGD(learning_rate=0.01, momentum=0.0, nesterov=False) #SGD=Stochastic Gradient Descent



net = create_network()
train_network(net, X_train, y_train, X_valid, y_valid)

# evaluate on test set:
y_test_pred = net(X_test)
y_test_pred = np.argmax(y_test_pred.numpy(), axis=1)
print("Test Acc:", accuracy_score(y_true=y_test, y_pred=y_test_pred))

【问题讨论】:

  • 您的代码中没有任何地方实际训练网络,为什么不使用 network.fit?
  • @MatiasValdenegro 我已续订,请查收,再次感谢

标签: python-3.x numpy tensorflow keras neural-network


【解决方案1】:

假设您的模型和训练是正确的,我看到的一个问题是,您正在分别改组 xynp.random.shuffle 将修改两个数组。之后,训练点将不再与正确的标签正确匹配。因此,您的训练和预测将无法按预期工作。你可以这样做,

# shuffle the ids
shuffled_ids = np.arange(len(x)))
np.random.shuffle(shuffled_ids)
# index x & y with the same shuffled numbers, 
# so the correct relationship is maintained 
shuf_x = x[shuffled_ids]
shuf_y = y[shuffled_ids]

【讨论】:

  • 非常感谢。解决了,我忽略了多么愚蠢的点,大声笑
【解决方案2】:

@NebiyouTen,我同意你所说的。但实际上np.random.shuffle 并没有返回任何东西。也许你需要做一些修改:

shuffled_ids = np.arange(len(x))
np.random.shuffle(shuffled_ids)
shuf_x = x[shuffled_ids]
shuf_y = y[shuffled_ids]

这是另一种打乱数据的方法:

random_state = np.random.get_state()
np.random.shuffle(x)
np.random.set_state(random_state)
np.random.shuffle(y)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2016-12-08
    • 2019-06-13
    • 2017-07-05
    • 2020-07-29
    • 1970-01-01
    • 2015-09-03
    • 2016-10-22
    相关资源
    最近更新 更多