python - 如何保存模态并再次加载以使用?
问题描述
我对python没有更多的了解。这是我在 python 中的 ANN 模态代码。此代码包含预测二进制输出中的客户情况。客户离开与否。
代码:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Part 2 - Now let's make the ANN!
# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Initialising the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
# Adding the second hidden layer
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
# Adding the output layer
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting the ANN to the Training set
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
# Part 3 - Making predictions and evaluating the model
# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
我想知道如何使用 keras 将此模态保存为 h5。保存后如何在另一个项目中再次加载以预测数据。
解决方案
为了保存模型,您可以执行以下操作:
model.save('model_file.h5')
并加载模型回来使用:
from keras.models import load_model
my_model = load_model('model_file.h5')
推荐阅读
- html - Bootstrap 4 网格 - .col-breakpoint vs .col-number
- r - 生成重复随机抽样
- datatable - 从其他表中的值的总和创建表
- html - 父元素有填充时错误的最大高度
- dart - 如果没有可用的网络连接,flutter firestore setData 没有错误
- node.js - 测试 Nodejs 共享实例的最佳实践
- python - 返回时可以留下文件而不关闭吗?
- angular - Angular - 使用 + 符号查询参数 - 以编码的 %2B 形式发送
- android - 无法使用 Android 手机检测到 Digital Persona 5100 设备
- java - 测试 MySQL DB 连接,当打开同一服务器中不同 DB 的 2 个端口时,同时给出连接正确的端口