我是机器学习的新手,现在我正在学习k均值聚类,我想使用pickle来转储和加载训练有素的模型。
我的代码是:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle
from sklearn.cluster import KMeans
from sklearn.externals import joblib
# importing our dataset
dataset = pd.read_csv("Mall_Customers.csv")
X = dataset.iloc[:, [3,4]].values
# Applying k-means to the mall dataset
kmeans = KMeans(n_clusters=5, init='k-means++',random_state=0)
y_kmeans = kmeans.fit_predict(X)
# Visualising the clusters
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')
plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids')
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()
我的问题:
答案 0 :(得分:3)
在所有机器学习模型中,无论是哪种类型(即聚类,回归等),使用pickle都相同
要将模型保存在转储中,其中'wb'表示写入二进制文件。
pickle.dump(model, open(filename, 'wb')) #Saving the model
要在任何需要使用 load 的地方加载保存的模型,其中'rb'表示读取二进制文件。
model = pickle.load(open(filename, 'rb')) #To load saved model from local directory
这里的模型是kmeans,文件名是任何本地文件,因此请相应使用。
答案 1 :(得分:2)
一个人也可以使用joblib
from joblib import dump, load
dump(model, model_save_path)
答案 2 :(得分:1)
保存:
pickle.dump(kmeans, open("save.pkl", "wb"))
加载:
kmeans = pickle.load(open("save.pkl", "rb"))