Python Keras Prediction返回nan

时间:2019-02-17 11:15:47

标签: python tensorflow keras neural-network

我在理解Keras如何处理数据以及为什么我的模型无法正常工作方面遇到问题。我正在尝试建立一个小的模型,可以根据经度和纬度的输入来预测城市。

我想看到的是当我做出预测时,例如,城市阵列的第一个索引我希望看到输出阵列索引零为最大激活值。

我当前使用Keras和Tensorflow的模型

数据 纬度和经度数据在0/1之间归一化

cities = [];

cities.append([60.1695213,24.9354496]); #1
cities.append([60.2052002,24.6522007]); #2
cities.append([61.4991112,23.7871208]); #3
cities.append([64.222176,27.72785]);    #4
cities.append([60.4514809,22.2686901]); #5
cities.append([65.0123596,25.4681606]); #6
cities.append([60.9826698,25.6615105]); #7
cities.append([62.8923798,27.6770306]); #8
cities.append([62.2414703,25.7208805]); #9
cities.append([61.4833298,21.7833309]); #10
cities.append([61.0587082,28.1887093]); #11
cities.append([63.0960007,21.6157703]); #12
cities.append([60.4664001,26.9458199]); #13
cities.append([62.601181,29.7631607]); #14
cities.append([60.9959602,24.4643402]); #15
cities.append([60.3923302,25.6650696]); #16
cities.append([61.6885681,27.2722702]); #17
cities.append([65.579287,24.196943]); #18
cities.append([65.986503,28.692848]); #19
cities.append([61.1272392,21.5112705]); #20

train_cities = np.array(cities);

for i in train_cities:
    i[0] = normalize(i[0],65.986503,60.1695213,0.99,0.01)
    i[1] = normalize(i[1],29.7631607,21.5112705,0.99,0.01)

train_labels = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

归一化经度/纬度

[[0.01168472 0.41784541]
 [0.01769563 0.38420658]
 [0.23568373 0.28146911]
 [0.69444458 0.74947275]
 [0.05918709 0.10113927]
 [0.82756859 0.48111052]
 [0.14867768 0.50407289]
 [0.47041082 0.7434374 ]
 [0.36075063 0.51112371]
 [0.233025   0.04349768]
 [0.16148804 0.80420471]
 [0.50471529 0.02359807]
 [0.06170056 0.65659833]
 [0.42135191 0.99118761]
 [0.15091674 0.36189614]
 [0.04922184 0.50449557]
 [0.26760196 0.69536778]
 [0.92308013 0.33013987]
 [0.99168472 0.86407655]
 [0.17303361 0.01118761]]

模型

model = keras.Sequential([
    keras.layers.Dense(10, activation=tf.nn.relu, input_shape = (2,)),
    keras.layers.Dense(20, activation=tf.nn.softmax)
]);

model.compile(optimizer='adam', 
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(train_cities, train_labels, epochs=50)

预测

model.fit(train_cities, train_labels, epochs=50)

我想对这些数据进行处理,只是将城市索引数组之一输入到网络中,并为其获取相应的标签。

我正在得到一个nan索引的输出数组

array([[nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
        nan, nan, nan, nan, nan, nan, nan]], dtype=float32)

另外,由于我无法弄清原因,网络似乎并未真正学习。

Epoch 50/50
20/20 [==============================] - 0s 200us/step - loss: nan - acc: 0.0000e+00

任何帮助将不胜感激。

归一化功能

def normalize(value,maxValue,minValue,maxRange,minRange):
    return ((value - (minValue - 0.01)) * (maxRange - (minRange))) / ((maxValue - 0.01) - (minValue - 0.01)) + (minRange)

1 个答案:

答案 0 :(得分:1)

不清楚$for_user是什么。如果它与train_labels相同,那么您将需要使最后一层的输出为labels而不是21,因为在keras中,标签从20开始。或者,您可以将标签重新定义为从00。否则,您的代码就可以了,并且可以在我的电脑上运行。在19个时期之后,我的精度为100%