注意
点击 here 下载完整的示例代码
模型持久化
HiClass 完全兼容 Pickle。 Pickle 可以用于轻松地将机器学习模型存储在磁盘上。 在本示例中,我们演示了如何使用 pickle 来存储和加载训练好的分类器。
输出:
[['Animal' 'Reptile' 'Lizard']
['Animal' 'Reptile' 'Snake']
['Animal' 'Mammal' 'Cow']
['Animal' 'Mammal' 'Sheep']]
import pickle
from sklearn.linear_model import LogisticRegression
from hiclass import LocalClassifierPerLevel
# Define data
X_train = [[1, 2], [3, 4], [5, 6], [7, 8]]
X_test = [[7, 8], [5, 6], [3, 4], [1, 2]]
Y_train = [
["Animal", "Mammal", "Sheep"],
["Animal", "Mammal", "Cow"],
["Animal", "Reptile", "Snake"],
["Animal", "Reptile", "Lizard"],
]
# Use Logistic Regression classifiers for every level in the hierarchy
lr = LogisticRegression()
classifier = LocalClassifierPerLevel(local_classifier=lr)
# Train local classifier per level
classifier.fit(X_train, Y_train)
# Save the model to disk
filename = "trained_model.sav"
pickle.dump(classifier, open(filename, "wb"))
# Some time in the future...
# Load the model from disk
loaded_model = pickle.load(open(filename, "rb"))
# Predict
predictions = loaded_model.predict(X_test)
print(predictions)
脚本总运行时间: ( 0 分钟 0.022 秒)