我有一个非常简单的输入:点,并且我试图对它们是否在某个区域中进行分类。所以我的训练数据的形状为(1000000, 2)
,它是以下形式的数组:
[ [x1,y1], [x2,y2],... ]
我的标签格式类似((10000, 2)
形):
[ [1,0], [0,1], [0,1],... ]
({[0,1]
表示该点在该区域中,[1,0]
表示该点不在该区域中)
我的模型是这样建立的:
import tensorflow as tf
from tensorflow import keras
import numpy as np
# Reads the points and labels from .csv format files
train_data = np.genfromtxt('data/train_data.csv', delimiter=',')
train_labels = np.genfromtxt('data/train_labels.csv', delimiter=',')
model = keras.models.Sequential()
model.add(keras.layers.Dense(128, activation='relu', input_shape=(2,)))
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dense(2, activation='softmax'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(train_data, train_labels, epochs=1, batch_size=100, verbose=1) # ERROR
请注意,输入形状为(2,)
,这意味着(根据reference),模型将期望使用(*, 2)
形式的数组。
我遇到了错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 2
我不知道为什么。有什么建议吗?
堆栈跟踪:
Traceback (most recent call last):
File "C:/Users/omer/Desktop/Dots/train.py", line 25, in <module>
model.fit(train_data, train_labels, epochs=1, batch_size=100, verbose=1)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 880, in fit
validation_steps=validation_steps)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py", line 329, in model_iteration
batch_outs = f(ins_batch)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\backend.py", line 3076, in __call__
run_metadata=self.run_metadata)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 1439, in __call__
run_metadata_ptr)
File "C:\Users\omer\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 528, in __exit__
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 2
[[{{node metrics/acc/Squeeze}}]]
答案 0 :(得分:1)
您的标签形状错误。参见the documentation:
使用
sparse_categorical_crossentropy
损失时,您的目标应为整数目标。如果您有分类目标,则应使用categorical_crossentropy
因此您需要将标签转换为整数:
train_labels = np.argmax(train_labels, axis=1)
答案 1 :(得分:0)
根据您对问题的描述,这似乎是一个二进制分类任务(即,内部区域还是外部区域)。因此,您可以执行以下操作:
'sigmoid'
作为最后一层的激活功能。'binary_crossentropy'
作为损失函数。您还需要将当前标签[1,0]
和[0,1]
映射到0和1。