ValueError:检查输入时出错:期望dense_151_input有3个维度,但得到形状的数组(2,1002)

时间:2018-05-31 23:18:02

标签: python tensorflow machine-learning keras deep-learning

我正在使用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)

error message

2 个答案:

答案 0 :(得分:0)

input_shape=(2100,)

输入形状不应包含批量大小。

答案 1 :(得分:0)

我使用Transpose函数将scaled_train_samples从2乘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))