keras - 输入形状与前一层的输出形状不同。

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

我把我的模型从Conv2D转换成了一个简单的DNN。我可以以某种方式解决输入输出形状误差。但现在我的模型给出了疯狂的结果--可怕的损失率和零精度。谁能帮帮我?

"""
trying hands on first ML program - 1D model
"""
import time
import numpy as np
# import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
import keras
from keras.models import Model
from keras.layers import Input, Dense, Activation
from keras.utils import to_categorical
from keras.optimizers import RMSprop
from numba import jit, cuda
start = time.time()

data = pd.read_csv(r"Pets_Data.csv", index_col='Date')
# data = data.reset_index(drop=False)
target = "Hippo"
filter = (data["Cats"] > 0) & (data[target] > 0)
total = data.where(filter).dropna().shape[0]
x_df = data.where(filter).dropna()
y_df = pd.DataFrame(data=x_df, columns=[target], copy=True)
x_df = x_df.drop(target, axis=1)
# input_shape = x_df.shape[1]

Train_ratio = 0.8
train_x = x_df[:int(total * Train_ratio)]
train_y = y_df[:int(total * Train_ratio)]

x = np.array(train_x, copy='True', order='K').flatten(order='C')
y = np.array(train_y, copy='True', order='K').flatten(order='C')

# tr_x = to_categorical(x,959)
# tr_y = to_categorical(y,959)

test_x = np.array(x_df[int(total * Train_ratio):], copy='True', order='K')#.flatten(order='C')
test_y = np.array(y_df[int(total * Train_ratio):], copy='True', order='K')#.flatten(order='C')

# x_test_new = to_categorical(test_x, 240)
# y_test_new = to_categorical(test_y,240)

inputs = Input(shape=(43,))
output_1 = Dense(256, activation='relu')(inputs)
output_2 = Dense(128, activation='relu')(output_1)
predictions = Dense(959, activation ='softmax')(output_2)

# Build the model
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) #loss='mean_squared_error'
model.summary()

jit(target='cuda')
# Fit the model
model.fit(train_x, train_y, epochs=100, batch_size=43, verbose=1)  # starts training
end = time.time()
print(f"time taken : {end-start:.4f} seconds.")

# Evaluate model
score = model.evaluate(test_x, test_y, batch_size=None)
print(f"loss on test: {score[0]*100:>6.2f}%, accuracy {score[1]*100:>6.2f}% ")
endtime = time.time()
print(f"time taken : {endtime-start:>6,.4f} seconds")

'''


层(类型) 输出形状参数#。

input_1 (InputLayer) (None, 43) 0


dense_1 (Dense) (无, 256) 11264


dense_2 (Dense) (无, 128) 32896


dense_3 (Dense) (无,959) 123711

总参数: 167,871可训练的参数: 167,871不可训练的参数: 595.13%,准确度0.00% 所用时间:3.9664秒。

tensorflow keras layer shapes
1个回答
0
投票

你说你只有数字数据(1199行,每行43个特征),没有图像。但在你的模型中,你使用的是2D卷积,而2D卷积通常用于图像。你还指定第一层的输入形状为839x43。我明白了,因为839是1199*0.7的浮动。但这意味着你的模型会把你的输入看成一个单一的图像,而不是839个不同的实例,每个实例有43个特征。你可能喜欢使用1D卷积或者只使用Dense层来完成你的任务。

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