python - 自动 sklearn : How to load pickle file and run predict()

标签 python automl

我已经使用 auto-sklearn 安装了一个分类模型,并设法将其保存到带有 pickle 的文件中。

x = automl.show_models()
results = {"ensemble": x}
pickle.dump(results, open('file.pickle','wb'))

我还设法重新加载了模型。
automl = pickle.load(open('file.pickle','rb'))

但我无法使用重新加载的模型对新数据进行预测。
当我运行时:
y_hat = automl.predict(X_test)

我收到以下错误:
AttributeError: 'str' object has no attribute 'predict'

最佳答案

不正确:

x = automl.show_models()
results = {"ensemble": x} # <---
pickle.dump(results, open('file.pickle','wb'))
正确:
x = automl.show_models()
#results = {"ensemble": x}
results = autml # the classifier/regressor itself
pickle.dump(results, open('file.pickle','wb'))
鸢尾花的示例代码:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from autosklearn.classification import AutoSklearnClassifier
import pickle


# dataset:
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

# train model:
classifier = AutoSklearnClassifier(
    time_left_for_this_task=30, 
    per_run_time_limit=60,
    memory_limit=1024*12) # depends on your computer
classifier.fit(X_train, y_train)

# save model
with open('iris-classifier.pkl', 'wb') as f:
    pickle.dump(classifier, f)

# load model
with open('iris-classifier.pkl', 'rb') as f:
    loaded_classifier = pickle.load(f)

# predict
y_true = y_test
y_pred = loaded_classifier.predict(X_test)
print('iris classifier: accuracy:', accuracy_score(y_true, y_pred))
# iris classifier: accuracy: 0.9333333333333333

关于python - 自动 sklearn : How to load pickle file and run predict(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61703174/

相关文章:

python - 使用 numpy >= 1.13 将特定字段视为 ndarray

python - Pandas:如何重用数据中的索引信息?

go - 编码文件以发送到 Google AutoML

python3通过分隔符将大文件分割成小文件(不是大小,行)

python - Django为 "Fully Loaded"后如何运行任意代码

php - Python:preg_replace 函数模拟

google-cloud-platform - 无法获取 gcr.io/automl-vision-ondevice/gcloud-container-1.14.0 的 docker 镜像 :latest

python - 错误 : Setup iteration failed: Unidentified error, 检查门户/计算中的日志

google-cloud-platform - 如何使用 Google NLP 在单个注释中提取多个标签文本项

azure - 无法删除 Azure Synapse AutoML 需求预测错误 : An invalid value for argument [y] was provided