【问题标题】:ValueError: Error when checking input: expected dense_9_input to have shape (9,) but got array with shape (1,)ValueError:检查输入时出错:预期dense_9_input的形状为(9,),但数组的形状为(1,)
【发布时间】:2020-02-08 13:39:25
【问题描述】:

首先,我将我的数据设置为如图所示:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from itertools import combinations as comb
import math
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten

dataset = pd.read_csv('Partial_quantarize.csv') #My dataset
print(dataset.columns.values)

pick = np.random.rand(len(dataset)) < 0.7
train = dataset[pick]
test = dataset[~pick]

#ingredient for training/testing the algorithm
coord = ['ra','dec']
cmodel_mags = ['Mag_u','Mag_g','Mag_r','Mag_i','Mag_z']
rad = ['rad_u', 'rad_g', 'rad_r', 'rad_i', 'rad_z']
dered = ['ext_u','ext_g','ext_r','ext_i','ext_z']
dered_color_indices = ['ext_ug','ext_gr','ext_ri','ext_iz']
coindex = ['coindex_u','coindex_g','coindex_r','coindex_i','coindex_z']
cmodel_color_indices = ['ug','gr','ri','iz']
prad50 = ['petroR50_u','petroR50_g','petroR50_r','petroR50_i','petroR50_z']
prad90 = ['petroR90_u','petroR90_g','petroR90_r','petroR90_i','petroR90_z']
#rad = ['petroRad_u','petroRad_g','petroRad_r','petroRad_i','petroRad_z']
#petro_color_indices = ['p_ug','p_gr','p_ri','p_iz']

#training models
model1 = cmodel_mags + cmodel_color_indices
model2 = cmodel_mags + cmodel_color_indices + rad
model3 = cmodel_mags + cmodel_color_indices + rad + coindex
model4 = dered + dered_color_indices
model5 = dered + dered_color_indices + rad
model6 = dered + dered_color_indices + rad + coindex
model7 = cmodel_mags + cmodel_color_indices + dered + dered_color_indices + rad + coindex
fullparms = coord + cmodel_mags + cmodel_color_indices + dered + dered_color_indices + rad + prad50 + prad90 + coindex

print(train[model4].shape,test[model4].shape) #this gives me (70061,9) (29939,9)

def nn_mlp(test, train, labels, k=7):
    ylabel = train['redshift']
    prediction = []
    batch=1
    no_bins = k*100 if k*100 < 1000 else 1000
    max_z = np.max(train['redshift'].values)
    min_z = np.min(train['redshift'].values)
    model = Sequential()
    model.add(Dense(len(labels), input_dim=len(labels), kernel_initializer='normal', use_bias=True, activation='relu'))
    model.add(Dense(1, kernel_initializer='normal', use_bias=True))
    model.compile(loss='mean_squared_error', optimizer='adam')
    edges = np.histogram(train['redshift'].values[::batch], bins=no_bins, range=(min_z,max_z))[1]
    edges_with_overflow = np.histogram(train['redshift'].values[::batch], bins=no_bins+1, range=(min_z, max_z))[1]
    model.fit(train[labels].values[::batch], edges_with_overflow[np.digitize(train['redshift'].values[::batch], edges)], epochs=1)
    for point in test[labels].values:
        prediction.append(model.predict([point])[0])
    return np.array(prediction)

pred_4 = nn_mlp(test, train, model4)

无论我设置哪个时期,我的代码实际上都可以运行, 但我不知道为什么我总是不断得到最终输出为

“ValueError:检查输入时出错:预期的dense_9_input有 形状 (9,) 但得到了形状 (1,) 的数组”

【问题讨论】:

  • 请包含整个错误跟踪。运行 model.predict 时会失败吗?
  • 显然,当我尝试更改 model.fit 中的测试 X 和 y 时,我的错误发生了变化,但仍然是错误。当我更改 model.predict 时让我回复你
  • 嘿,成功了!显然我从“prediction.append(model.predict([point])[0])”更改为“prediction.append(model.predict([[point]])[0])”并且运行顺利。非常感谢

标签: python tensorflow machine-learning keras neural-network


【解决方案1】:

在此处(回答部分)提供解决方案,即使它出现在评论部分,也是为了社区的利益。

此问题与形状不兼容有关,请从 (9,) 重新调整为 (1, 9)。

这里是如何重塑的例子

import tensorflow as tf

a = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9]) 
print(a)

b=tf.constant([[1, 2, 3, 4, 5, 6, 7, 8, 9]])
print(b)

输出:

Tensor("Const_1:0", shape=(9,), dtype=int32)
Tensor("Const_2:0", shape=(1, 9), dtype=int32)

在从prediction.append(model.predict([point])[0])即此处形状为 (9,))更改为 prediction.append(model.predict([[point]])[0])即此处形状为 (1, 9))后,因此问题已解决。

对于重塑,您可以使用 tf.reshapetf.expand_dims

使用 tf.reshape 重塑形状:

a = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9]) 
print(a)
c=tf.reshape(a, [1, 9]) 
print(c)

输出:

Tensor("Const_3:0", shape=(9,), dtype=int32)
Tensor("Reshape_1:0", shape=(1, 9), dtype=int32)

使用 tf.expand_dims 重塑形状:

a = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9]) 
print(a)
d=tf.expand_dims(a, 0) 
print(d)

输出:

Tensor("Const_4:0", shape=(9,), dtype=int32)
Tensor("ExpandDims_1:0", shape=(1, 9), dtype=int32)

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2020-05-17
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多