使用《Python 深度学习》中的 Keras 进行多类分类,与教科书中的内容相比,产生的准确度截然不同

问题描述 投票:0回答:1

下面是 François Chollet 所著《Python 深度学习》第 4 章中的多类分类器代码。教科书提到这段代码的准确率将超过 95%,但我的环境似乎停留在 50%。 喀拉拉邦版本 - 3.6 张量流 - 2.18 硬件 - Apple M1 Pro

import keras
from tensorflow.keras.datasets import reuters
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np


(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)


# multi hot encode text. Each sequence is a newswire article

def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        for j in sequence:
            results[i, j] = 1.
        return results


x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)


# model definition

model = keras.Sequential([
    layers.Dense(64, activation="relu"),
    layers.Dense(64, activation="relu"),
    layers.Dense(46, activation="softmax")
])

model.compile(
    optimizer="rmsprop",
    loss="categorical_crossentropy",
    metrics=["accuracy"]
)

# setting aside validation set
x_val = x_train[:1000]
partial_x_train = x_train[1000:]
y_val = y_train[:1000]
partial_y_train = y_train[1000:]

# training the model

history = model.fit(
    partial_x_train,
    partial_y_train,
    epochs=20,
    batch_size=512,
    validation_data=(x_val,y_val)
)

# plotting accuracy

acc = history_dict["accuracy"]
val_acc = history_dict["val_accuracy"]
plt.plot(epochs, acc, "bo", label="Training acc")
plt.plot(epochs, val_acc, "b", label="Validation acc")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()

accuracy vs epochs

python tensorflow machine-learning keras deep-learning
1个回答
0
投票

首先:

导入图层:

from tensorflow.keras import layers

第二:

您需要有分类格式的标签:

y_train = to_categorical(train_labels)
y_test = to_categorical(test_labels)

那么你应该得到教科书上所说的 80 年代中期的准确度。我看了教科书,上面说 95% 是最先进的方法,而不是书中定义的朴素方法。

result

© www.soinside.com 2019 - 2024. All rights reserved.