訓練模型的儲存與載入

ckxllf發表於2019-12-19

  1.目的:

  將訓練好的模型儲存下來,已備下次使用,節省訓練時間,提高效率

  2.API:

  from sklearn.externals import joblib

  儲存:

  joblib.dump(rf,"test.pkl")

  載入:

  estimator = joblib.load("test.pkl")

  3.Python程式碼實現:

  # -*- coding: UTF-8 -*-

  '''

  @Author :Jason

  波士頓房價預測,將模型儲存到

  '''

  from sklearn.datasets import load_boston

  from sklearn.model_selection import train_test_split

  from sklearn.preprocessing import StandardScaler

  from sklearn.linear_model import Ridge

  from sklearn.metrics import mean_squared_error

  from sklearn.externals import joblib

  def model_save_fetch():

  """

  嶺迴歸對波士頓房價進行預測

  :return:

  """

  # 1)獲取資料

  boston = load_boston()

  print("特徵數量:\n", boston.data.shape)

  # 2)劃分資料集 鄭州婦科醫院哪家好

  x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22)

  # 3)標準化

  transfer = StandardScaler()

  x_train = transfer.fit_transform(x_train)

  x_test = transfer.transform(x_test)

  # # 4)預估器

  # estimator = Ridge(alpha=0.5, max_iter=10000)

  # estimator.fit(x_train, y_train)

  #

  # # 儲存模型

  # joblib.dump(estimator, "./files/test.pkl")

  # 載入模型

  estimator = joblib.load("./files/test.pkl")

  # 5)得出模型

  print("嶺迴歸-權重係數為:\n", estimator.coef_)

  print("嶺迴歸-偏置為:\n", estimator.intercept_)

  # 6)模型評估

  y_predict = estimator.predict(x_test)

  print("預測房價:\n", y_predict)

  error = mean_squared_error(y_test, y_predict)

  print("嶺迴歸-均方誤差為:\n", error)

  return None

  if __name__ == "__main__":

  model_save_fetch()


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69945560/viewspace-2669430/,如需轉載,請註明出處,否則將追究法律責任。

相關文章