Skip to main content
 首页 » 编程设计

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

2025年02月15日8freeliver54

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

然后在 Windows 中我可以加载模型并重新使用它。但是,当我尝试在 Linux (Ubuntu)、Keras 2.0.5 中加载模型时,出现以下错误:

ValueError: Optimizer weight shape (90,) not compatible with provided weight shape (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}) 

请您参考如下方法:

谢谢,原来是版本不兼容的问题。

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