我正在使用Keras API编写可以使用学习到的.h5文件进行预测的代码。

学习模型如下

#Libraries
import keras
from keras import backend as k
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten, Reshape
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
import numpy as np
from random import randint
from sklearn.preprocessing import MinMaxScaler

#Create 2 numpy lists that will hold both our sample data and raw data
train_labels = []
train_samples = []

#declare array to hold training data as well as label
train_samples_temp_a = []
train_samples_temp_b = []

#Generate data
for i in range(1000):
    #YOUNGER PEOPLE
    random_younger_a = randint(13,64)
    random_younger_b = randint(13,64)
    train_samples_temp_a.append(random_younger_a)
    train_samples_temp_b.append(random_younger_b)
    train_labels.append(0)
    #OLDER PEOPLE
    random_older_a = randint(65,100)
    random_older_b = randint(65,100)
    train_samples_temp_a.append(random_older_a)
    train_samples_temp_b.append(random_older_b)
    train_labels.append(1)

for i in range(50):
    #YOUNGER PEOPLE
    random_younger_a = randint(13,64)
    random_younger_b = randint(13,64)
    train_samples_temp_a.append(random_younger_a)
    train_samples_temp_b.append(random_younger_b)
    train_labels.append(1)
    #OLDER PEOPLE
    random_older_a = randint(65,100)
    random_older_b = randint(65,100)
    train_samples_temp_a.append(random_older_a)
    train_samples_temp_b.append(random_older_b)
    train_labels.append(0)

#Array of Two Arrays
train_samples.append(train_samples_temp_a)
train_samples.append(train_samples_temp_b)

#Convert both train_label and train_sample list into a numpy array
train_samples = np.array(train_samples)
train_labels = np.array(train_labels)

#Scale down train_samples to numbers between 0 and 1
scaler = MinMaxScaler(feature_range=(0,1))
scaled_train_samples=scaler.fit_transform((train_samples))

#Sequential Model
model = Sequential([
    Dense(16, input_shape=(2,2100), activation='relu'),
    Flatten(),
    Dense(32, activation='relu'),
    Dense(2, activation='softmax')
])

#Compile Model
model.compile(Adam(lr=.0001), loss='sparse_categorical_crossentropy',
metrics= ['accuracy'])

#Train Model
model.fit(scaled_train_samples, train_labels, validation_split = 0.20,
batch_size=10, epochs=20, shuffle=True, verbose=2)


python - ValueError:检查输入时出错:预期density_151_input具有3维,但数组的形状为(2,2100)-LMLPHP

最佳答案

我使用了Transpose函数将scaled_train_samples从2 x 2100矩阵重塑为2100 x 2矩阵。谢谢你们的贡献。

#Transpose
scaled_train_samples = scaled_train_samples.transpose()


但是,运行下面的代码行可以保证模型的准确性。目前,我的准确度为51.52%,我可以做些什么来提高此模型的准确度吗?

#Evaluate the model
scores = model.evaluate(scaled_train_samples, train_labels)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

08-25 05:53