我有非常简单的输入:点,并且我试图对它们是否在某个区域中进行分类。因此,我的训练数据是形状的(1000000, 2),这是一种形式的数组: [ [x1,y1], [x2,y2],... ] 我的标签是一类似的形式的(异型(10000, 2)): [ [1,0], [0,1], [0,1],... ] ([0,1]装置的点处于区域中,[1,0]装置是不)
(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,),意味着(根据参考)该模型将期望使用形式的数组(*, 2)。
(2,)
(*, 2)
我收到错误消息: tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 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}}]]
您的标签形状错误。请参阅文档:
使用sparse_categorical_crossentropy损失时,您的目标应该是 整数 目标。如果您有明确的目标,则应使用categorical_crossentropy
sparse_categorical_crossentropy
categorical_crossentropy
因此,您需要将标签转换为整数:
train_labels = np.argmax(train_labels, axis=1)