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

在使用TensorFlow时遇到InvalidArgumentError,提示无法挤压维度1,期望为1,实际为101。错误源于Y的标签不正确,需要是类索引0,1,2等,而非一热编码。解决方案是将标签进行转换。" 107627653,9923926,Python基础知识:字典、集合、元组及排序算法解析,"['Python基础', '数据结构', '算法', '字典操作', '集合操作']
部署运行你感兴趣的模型镜像

报错解决: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)))

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值