ValueError:无法压缩dim [1],预期尺寸为1,输入形状为[?,17]

时间:2020-03-10 05:05:10

标签: python numpy tensorflow keras cnn

我正在尝试实施Alexnet来检测糖尿病性视网膜病变。 这是代码

path="D:\\dataset\\train\\t\\"

count = 1
imgList=list()
labelList=list()
ite = 1

print("Loading Model design ....")
json_file = open('Model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

print("Loading weights ....")
loaded_model.load_weights("Model_weight.h5")

opt = Adam(lr=0.001)
loaded_model.compile(optimizer=opt, loss=keras.losses.sparse_categorical_crossentropy, metrics=['accuracy'])

while ite <= 1:
    limit = 10 * ite
    imgList=list()
    labelList=list()
    while count <= limit:
        imgC0 = path+"class_0_img_%d.jpeg" %(count)
        imgC1 = path+"class_1_img_%d.jpeg" %(count)
        imgC2 = path+"class_2_img_%d.jpeg" %(count)
        imgC3 = path+"class_3_img_%d.jpeg" %(count)
        imgC4 = path+"class_4_img_%d.jpeg" %(count)

        lC0 = np.zeros((1,17))
        lC1 = np.zeros((1,17))
        lC2 = np.zeros((1,17))
        lC3 = np.zeros((1,17))
        lC4 = np.zeros((1,17))

        lC0[0,0] = 1
        lC1[0,1] = 1
        lC2[0,2] = 1
        lC2[0,3] = 1
        lC2[0,4] = 1

        im0=cv.resize(cv.imread(imgC0),(227,227))
        im1=cv.resize(cv.imread(imgC1),(227,227))
        im2=cv.resize(cv.imread(imgC2),(227,227))
        im3=cv.resize(cv.imread(imgC3),(227,227))
        im4=cv.resize(cv.imread(imgC4),(227,227))

        imgList.append(im0)
        imgList.append(im1)
        imgList.append(im2)
        imgList.append(im3)
        imgList.append(im4)

        labelList.append(lC0)
        labelList.append(lC1)
        labelList.append(lC2)
        labelList.append(lC3)
        labelList.append(lC4)

        print(count)

        del(imgC0)
        del(imgC1)
        del(imgC2)
        del(imgC3)
        del(imgC4)
        del(lC0)
        del(lC1)
        del(lC2)
        del(lC3)
        del(lC4)
        count += 1

    labelMatrix = labelList

    xtr = np.array(imgList)
    xtr = xtr.reshape(-1,227,227,3)
    ytr = np.array(labelMatrix)
    ytr = ytr.reshape(-1,17)

    print(xtr.shape)
    print(ytr.shape)

    print(type(ytr))

    print("Model Training ....")
    loaded_model.fit(xtr,ytr,epochs=1,batch_size=50,validation_split=0.1)

    print("Saving Model weights ....")
    #loaded_model.save_weights("Model_weight.h5")

    ite += 1
    del(imgList)
    del(labelList)

print("Finished ....")

我收到以下错误消息:

文件“”,第1行,在 runfile('D:/Project/ModelTrain.py',wdir ='D:/ Project')

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ spyder_kernels \ customize \ spydercustomize.py”,行文件中的827行 execfile(文件名,命名空间)

exec文件中的第110行,文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ spyder_kernels \ customize \ spydercustomize.py” exec(compile(f.read(),文件名,'exec'),命名空间)

文件“ D:/Project/ModelTrain.py”,第103行,在 loading_model.fit(xtr,ytr,epochs = 1,batch_size = 50,validation_split = 0.1)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training.py”,第728行,适合 use_multiprocessing = use_multiprocessing)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training_v2.py”,行324,适合 total_epochs = epochs)

run_one_epoch中的第123行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training_v2.py” batch_outs =执行功能(迭代器)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training_v2_utils.py”,行86,在execute_function中 distribution_function(input_fn))

调用中的文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ eager \ def_function.py”,第457行 结果= self._call(* args,** kwds)

文件_call中的第503行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ eager \ def_function.py” self._initialize(args,kwds,add_initializers_to = initializer_map)

文件_initialize中的第408行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ eager \ def_function.py” * args,** kwds))

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ eager \ function.py”,行1848,位于_get_concrete_function_internal_garbage_collected中 graph_function,_,_ = self._maybe_define_function(args,kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ eager \ function.py”,行2150,在_maybe_define_function中 graph_function = self._create_graph_function(args,kwargs)

_create_graph_function中的第2041行,文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ eager \ function.py” capture_by_value = self._capture_by_value),

在func_graph_from_py_func中的行915中的文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ framework \ func_graph.py” func_outputs = python_func(* func_args,** func_kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ eager \ def_function.py”,第358行,位于wrapd_fn中 返回strong_wrapped_fn()。包裹(* args,** kwds)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training_v2_utils.py”,第73行,位于distributed_function中 per_replica_function,args =(model,x,y,sample_weights))

experimental_run_v2中的第760行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ distribute \ distribute_lib.py” 返回self._extended.call_for_each_replica(fn,args = args,kwargs = kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ distribute \ distribute_lib.py”,行1787,位于call_for_each_replica中 返回self._call_for_each_replica(fn,args,kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ distribute \ distribute_lib.py”,行2132,在_call_for_each_replica中 返回fn(* args,** kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ autograph \ impl \ api.py”,第292行,在包装器中 返回func(* args,** kwargs)

train_on_batch中的第264行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training_v2_utils.py” output_loss_metrics = model._output_loss_metrics)

train_on_batch中的第315行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training_eager.py” 模型,输出,目标,sample_weights = sample_weights,masks = masks)

_eager_metrics_fn中第74行的文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training_eager.py” skip_target_masks = model._prepare_skip_target_masks())

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training.py”,第2063行,在_handle_metrics中 目标,输出,output_mask))

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training.py”,第2014行,在_handle_per_output_metrics中 metric_fn,y_true,y_pred,weights = weights,mask = mask)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ training_utils.py”,行1067,在call_metric_function中 返回metric_fn(y_true,y_pred,sample_weight = weights)

调用中的文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ metrics.py”,第193行 copy_local_fn,* args,** kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ distribute \ distributed_training_utils.py”,行1135,在call_replica_local_fn中 返回fn(* args,** kwargs)

replica_local_fn中的第176行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ metrics.py” update_op = self.update_state(* args,** kwargs)#pylint:disable = not-callable

第75行中的文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ utils \ metrics_utils.py” update_op = update_state_fn(* args,** kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ metrics.py”,第581行,处于update_state 匹配= self._fn(y_true,y_pred,** self._fn_kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ keras \ metrics.py”,行2778,以sparse_categorical_accuracy y_true = array_ops.squeeze(y_true,[-1])

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ util \ dispatch.py​​”,包装中的第180行 返回目标(* args,** kwargs)

new_func中的第507行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ util \ deprecation.py” 返回func(* args,** kwargs)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ ops \ array_ops.py”,行3649,被压缩 返回gen_array_ops.squeeze(输入,轴,名称)

文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ ops \ gen_array_ops.py”,第10071行,处于压缩状态 “压缩”,输入=输入,squeeze_dims =轴,名称=名称)

_apply_op_helper中的第793行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ framework \ op_def_library.py” op_def = op_def)

create_op中的第548行“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ framework \ func_graph.py” compute_device)

_create_op_internal中的第3429行,文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ framework \ ops.py” op_def = op_def)

init 中的文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ framework \ ops.py”,行1773 control_input_ops)

文件_create_c_op中的文件“ C:\ Users \ Ammar Ameer \ Anaconda3 \ lib \ site-packages \ tensorflow_core \ python \ framework \ ops.py”,行1613 引发ValueError(str(e))

ValueError:无法压缩尺寸为1的dim [1],预期尺寸为1,对于“ metrics / accuracy / Squeeze”(运算符:“ Squeeze”),输入形状为[?,17],结果为17。

有人可以帮我吗.. 我已将模型另存为

model = Sequential()

# 1st Convolutional Layer
model.add(Conv2D(filters=96, input_shape=(227,227,3), kernel_size=(11,11), strides=(4,4), padding="valid", activation = "relu"))

# Max Pooling
model.add(MaxPool2D(pool_size=(3,3), strides=(2,2), padding="valid"))

# 2nd Convolutional Layer
model.add(Conv2D(filters=256, kernel_size=(5,5), strides=(1,1), padding="same", activation = "relu"))

# Max Pooling
model.add(MaxPool2D(pool_size=(3,3), strides=(2,2), padding="valid"))

# 3rd Convolutional Layer
model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding="same", activation = "relu"))

# 4th Convolutional Layer
model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding="same", activation = "relu"))

# 5th Convolutional Layer
model.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding="same", activation = "relu"))

# Max Pooling
model.add(MaxPool2D(pool_size=(3,3), strides=(2,2), padding="valid"))

# Passing it to a Fully Connected layer
model.add(Flatten())
# 1st Fully Connected Layer
model.add(Dense(units = 9216, activation = "relu"))

# 2nd Fully Connected Layer
model.add(Dense(units = 4096, activation = "relu"))

# 3rd Fully Connected Layer
model.add(Dense(4096, activation = "relu"))

# Output Layer
model.add(Dense(17, activation = "softmax")) #As we have two classes

opt = Adam(lr=0.001)
model.compile(optimizer=opt, loss=keras.losses.sparse_categorical_crossentropy, metrics=['accuracy'])

model.summary()


model_jason = model.to_json()
with open("Model.json","w") as json_file:
    json_file.write(model_jason)

model.save_weights("Model_weight.h5")

请帮我解决这个问题。

0 个答案:

没有答案