写一段python代码:利用keras.models.Sequential()函数,构造一个多层感知器模型。其中,使用Dense()进行全连接层的构造,把MNIST数据集的image 28*28变成784*1 向量;把label从单个数字变成独热向量,使用不同数量的训练数据(5000,10000,15000,…,60000,公差=5000的等差数列,构造输入层784,第一隐层 128,第二隐层 64,输出层10的双隐层感知器,绘制训练集和测试集准确率(纵轴)关于训练数据大小(横轴)的曲线
时间: 2023-12-08 21:06:17 浏览: 114
好的,以下是按照您的要求写的Python代码:
```
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt
# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 将图像数据转换成784*1的向量
X_train = X_train.reshape(X_train.shape[0], 784).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 784).astype('float32')
# 将标签转换成独热向量
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
# 构建模型
def build_model():
model = Sequential()
model.add(Dense(units=128, input_dim=784, activation='relu'))
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics=['accuracy'])
return model
# 训练模型并绘制准确率曲线
batch_size = 128
epochs = 10
train_sizes = range(5000, 65000, 5000)
train_accs = []
test_accs = []
for size in train_sizes:
X_train_subset = X_train[:size]
y_train_subset = y_train[:size]
model = build_model()
history = model.fit(X_train_subset, y_train_subset, batch_size=batch_size,
epochs=epochs, verbose=0, validation_data=(X_test, y_test))
train_accs.append(history.history['accuracy'][-1])
test_accs.append(history.history['val_accuracy'][-1])
plt.plot(train_sizes, train_accs, 'o-', label="Training Accuracy")
plt.plot(train_sizes, test_accs, 'o-', label="Testing Accuracy")
plt.xlabel("Training Set Size")
plt.ylabel("Accuracy")
plt.title("Accuracy vs. Training Set Size")
plt.legend(loc="best")
plt.show()
```
这段代码会输出一个准确率曲线,其中横轴为训练集大小,纵轴为准确率。您可以根据需要进行修改。
阅读全文