报错解决:InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got

报错解决:InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 101

晚上在使用tensorflow时报错如下:

Traceback (most recent call last):

  File "C:\Users\peter\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
    execfile(filename, namespace)

  File "C:\Users\peter\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

    callbacks = [cp_callback])  # pass callback to training

  File "C:\Users\peter\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 880, in fit
    validation_steps=validation_steps)

  File "C:\Users\peter\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py", line 329, in model_iteration
    batch_outs = f(ins_batch)

  File "C:\Users\peter\Anaconda3\lib\site-packages\tensorflow\python\keras\backend.py", line 3076, in __call__
    run_metadata=self.run_metadata)

  File "C:\Users\peter\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1439, in __call__
    run_metadata_ptr)

  File "C:\Users\peter\Anaconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 528, in __exit__
    c_api.TF_GetCode(self.status.status))

InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 101
	 [[{{node metrics/acc/Squeeze}}]]
	 [[{{node loss/dense_loss/broadcast_weights/assert_broadcastable/is_valid_shape/has_valid_nonscalar_shape/has_invalid_dims/concat}}]]

这个错误是因为TensorFlow的Y的标签必须只包括0,1,2等类索引,而不是像[1,0,0],[0,1,0],[0,0,1]这样的单一热编码。
转换代码如下:

import numpy as np
import tensorflow as tf

def change_to_right(wrong_labels):
    right_labels=[]
    for x in wrong_labels:
        for i in range(0,len(wrong_labels[0])):
            if x[i]==1:
                right_labels.append(i+1)
    return right_labels

wrong_labels =np.array([[0,0,1,0], [0,0,1,0], [1,0,0,0],[0,1,0,0]])
right_labels =tf.convert_to_tensor(np.array(change_to_right(wrong_labels)))

你可能感兴趣的:(机器学习,行走的问题解决机,python)