Python Keras - Windows和Linux之间的兼容性

时间:2017-08-10 22:32:53

标签: python keras

我已经在Windows 10,Python 3.5,Keras 2.0.6中训练并保存了Keras模型。

在Windows中,我可以加载模型并重复使用它。但是,当我尝试在Linux(Ubuntu),Keras 2.0.5中加载模型时,我收到以下错误:

  

ValueError:优化器重量形状(90,)与提供的重量形状(31,90)不兼容

我尝试卸载Keras并使用Pip重新安装,然后对Conda执行相同的操作。这是Windows和Linux的兼容性问题,还是其他什么?

非常感谢

训练和保存模型的代码:

from keras.models import Sequential
from keras.layers import Dense

import keras.backend as K
def inRange(y_true, y_pred):
    return K.sum(K.cast(K.less_equal(K.abs(y_true-y_pred), 8), "int32")) / K.shape(y_true)[0]

# create model
model = Sequential()
model.add(Dense(n1, input_dim=X_train.shape[1], activation='relu'))
model.add(Dense(n2, activation='relu'))
model.add(Dense(1, activation='linear'))


# Compile model
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', inRange])

# Fit the model
history = model.fit(X_train, y_train, epochs=maxEpoch, batch_size=10)

# evaluate the model
scores = model.evaluate(X_train, y_train)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# save the model
model.save('length_predict.h5', overwrite=True, include_optimizer=True)

加载已保存模型的代码:

import keras.backend as K
from keras.models import load_model

# Custom metric for use in the keras ANN models, needs to be loaded as a custom object
def inRange(y_true, y_pred):
    '''
    Function for determining the percentage of points that fall within the +-8% error
    '''
    return K.sum(K.cast(K.less_equal(K.abs(y_true-y_pred), 8), "int32")) / K.shape(y_true)[0]

# Load the ANN
model_length = load_model('length_predict.h5', custom_objects={'inRange':inRange})

1 个答案:

答案 0 :(得分:0)

谢谢,它实际上是版本不兼容问题。

出于某种原因,Anaconda在Windows中安装了2.0.6版,但在Linux中只安装了2.0.5版。我在我的Linux机器上手动下载并安装了2.0.6(来自Keras github页面),然后代码工作了:)