解决Union类型转Tensor报错及制表符文本转2D Tensor喂CNN问题
解决制表符文本转TensorFlow 2D Tensor的错误问题
错误原因分析
- 类型匹配错误:
CellType是Union[str, float, int, bool]类型别名,type(CellType)返回的是Union的类型对象(<class 'typing._UnionGenericAlias'>),而你的TF_DATA_TYPES字典键是基础数据类型,因此触发KeyError。 - 文本分割逻辑错误:目标是处理制表符分隔文本,但代码用了
line.split(' '),会错误分割多空格的情况;应根据实际分隔符选择split('\t')(制表符)或split()(任意空白)。 - 未转换实际数据类型:代码仅通过
cast做类型标注,没有把字符串转换成对应的数值类型(int/float),最终生成的Tensor会是字符串类型,无法直接输入CNN。
修正后的代码
from typing import List, Union import tensorflow as tf CellType = Union[str, float, int, bool] RowType = List[CellType] # Mapping Python types to TensorFlow data types TF_DATA_TYPES = { str: tf.string, float: tf.float32, int: tf.int32, bool: tf.bool } def convert_string_to_tensorflow_object(data_string): # Split the string into lines, filter out empty lines lines = [line.strip() for line in data_string.strip().split('\n') if line.strip()] # Split each line: use '\t' for tab-separated, or split() for any whitespace data_str_2d = [line.split() for line in lines] # Replace with line.split('\t') if your data is strictly tab-separated # Convert string cells to actual Python types data_2d: List[RowType] = [] for row_str in data_str_2d: row: RowType = [] for cell_str in row_str: # Try converting to numeric types first, keep string if failed try: num = int(cell_str) row.append(num) except ValueError: try: num = float(cell_str) row.append(num) except ValueError: row.append(cell_str) data_2d.append(row) # Prepare numeric data for CNN (requires numerical tensors) # Extract only numeric columns, or encode string columns if needed numeric_data = [] for row in data_2d: numeric_row = [cell for cell in row if isinstance(cell, (int, float))] numeric_data.append(numeric_row) # Convert to float32 tensor (common input type for CNN) tf_tensor = tf.constant(numeric_data, dtype=tf.float32) return tf_tensor if __name__ == "__main__": # Example data (replace spaces with '\t' if using tab-separated) data_string: str = """ 1 ASN C 7.042 9.118 0.000 1 1 1 1 1 0 2 LEU H 5.781 5.488 7.470 0 0 0 0 1 0 3 THR H 5.399 5.166 6.452 0 0 0 0 0 0 4 GLU H 5.373 4.852 6.069 0 0 0 0 1 0 5 LEU H 5.423 5.164 6.197 0 0 0 0 2 0 """ tensorflow_tensor = convert_string_to_tensorflow_object(data_string) print(tensorflow_tensor) print("Tensor shape:", tensorflow_tensor.shape)
关键修改说明
- 修复类型匹配问题:移除了错误的
TF_DATA_TYPES[type(CellType)]逻辑,改为根据实际转换后的元素类型处理,或直接指定CNN常用的tf.float32类型。 - 正确分割文本:根据数据实际分隔符选择分割方式,确保每行数据被正确拆分为列。
- 实际类型转换:添加字符串转数值类型的逻辑,将文本数据转为int/float,保证最终生成的Tensor是数值型,符合CNN输入要求。
- 处理混合类型:针对CNN需要数值输入的特点,提取数据中的数值列;若需保留字符串列,可通过one-hot编码、词嵌入等方式转换为数值后再合并到张量中。
内容的提问来源于stack exchange,提问作者user366312
相关产品推荐
相关产品推荐

