为什么Keras用我的代码在密集期间会产生尺寸错误?

时间:2018-12-18 10:12:04

标签: python tensorflow keras

你好,我目前正在做一些简单的神经网络,但是有一些我不知道为什么的问题。

代码看起来像这样

import csv
import numpy as np
np.random.seed(123)  # for reproducibility

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist

f = open('training.csv', 'r', encoding='utf-8')
rdr = csv.reader(f)

X_train = list()
Y_train = list()

print(type(X_train))
for ele in rdr :
    # print(type(ele))
    # print(type(ele[0]))
    X_train.append([float(ele[0])])
    Y_train.append([float(ele[1])])
# reshaping the datas

X_train = np.asarray(X_train)
Y_train = np.asarray(Y_train)

print(X_train.shape)
X_train_1 = X_train.reshape(X_train.shape[0], 1,1)
print(X_train_1.shape)

# print(X_train.shape)
# defining models
model = Sequential()
# model.add(Flatten())
model.add(Dense(4, activation='relu',input_shape=((1, 1))))
print ("model.output_shape1: ", model.output_shape)
# model.add(Dropout(0.5))
# print("Hello")
# print(model.input_shape)
# model.add(Dense(4, activation='softmax'))
# model.add(Dense(1, activation='softmax'))
# print(model.input_shape)

# 8. Compile model
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

# 9. Fit model on training data
model.fit(X_train, Y_train, 
          batch_size=32, nb_epoch=10, verbose=0)

# 10. Evaluate model on test data
score = model.evaluate(X_train_1, Y_train, verbose=0)

# print (problem)
# print (answer)

f.close()     

错误消息是

  

预计density_1_input具有3维,但数组具有形状   (863,1)

问题是我想我在进入NN之前将X_train_1数组设置为可用形状,这是怎么做的?

此外,如果我将尺寸再增加1倍

  

X_train_1 = X_train.reshape(X_train.shape [0],1,1,1)

然后会有类似

的错误
  

预计density_1_input具有3维,但数组具有形状   (863,1,1,1)

似乎无法制作3维数组我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的输入的暗淡id1。(863,1)中的第一个数字是样本数量。

错误消息

  

预计density_1_input具有3维,但数组具有形状   (863,1)

建议您输入的是863个浮点数,其形状为(1,),请尝试将输入形状更改为input_shape =(1,)或input_dim = 1

如果您想重塑数据,请查看以下代码:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Flatten


X_train = list()
Y_train = list()

for ele in range(0,10):
    X_train.append([float(ele)])
    Y_train.append([float(ele)])

# reshaping the data
X_train = np.asarray(X_train)
Y_train = np.asarray(Y_train)


X_train = X_train.reshape(X_train.shape[0], 1, 1)
print(X_train.shape)
model = Sequential()
model.add(Dense(4, activation='relu', input_shape=(1, 1)))
model.add(Flatten())
model.add(Dense(1, activation='softmax'))

# 8. Compile model
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
#
# # 9. Fit model on training data
model.fit(X_train, Y_train,
          batch_size=32, epochs=10, verbose=1)

我不得不稍作更改,但是它显示了您应该重塑数据的方式。

请注意,我必须将数据展平以匹配输出形状。我还将输出更改为binary_crossentropy,因为我的输出是二进制数据。如果您想分类为多个类,则必须对输出进行一次热门处理。