網(wǎng)站上線 郵件群發(fā)模板網(wǎng)站搭建需要多少錢?
一、使用tensorflow框架實(shí)現(xiàn)邏輯回歸
1. 數(shù)據(jù)部分:
- 首先自定義了一個(gè)簡(jiǎn)單的數(shù)據(jù)集,特征?
X
?是 100 個(gè)隨機(jī)樣本,每個(gè)樣本一個(gè)特征,目標(biāo)值?y
?基于線性關(guān)系并添加了噪聲。 - tensorflow框架不需要
numpy
?數(shù)組轉(zhuǎn)換為相應(yīng)的張量,可以直接在模型中使用數(shù)據(jù)集。
2. 模型定義部分:
方案 1:model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
解釋:
- 此方案使用?
tf.keras.Sequential
?構(gòu)建模型,在列表中直接定義了一個(gè)?Dense
?層,input_shape=(1,)
?表明輸入數(shù)據(jù)的形狀。 - 編譯模型時(shí),選擇隨機(jī)梯度下降(SGD)優(yōu)化器和均方誤差損失函數(shù)。
- 訓(xùn)練完成后,使用?
sklearn
?的指標(biāo)評(píng)估模型,并輸出模型的系數(shù)和截距。
import tensorflow as tf
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score# 自定義數(shù)據(jù)集
X = np.random.rand(100, 1).astype(np.float32)
y = 2 * X + 1 + 0.3 * np.random.randn(100, 1).astype(np.float32)# 構(gòu)建模型
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))
])# 編譯模型
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),loss='mean_squared_error')# 訓(xùn)練模型
history = model.fit(X, y, epochs=1000, verbose=0)# 模型評(píng)估
y_pred = model.predict(X)
mse = mean_squared_error(y, y_pred)
r2 = r2_score(y, y_pred)
print(f"均方誤差 (MSE): {mse}")
print(f"決定系數(shù) (R2): {r2}")# 輸出模型的系數(shù)和截距
weights, biases = model.layers[0].get_weights()
print(f"模型系數(shù): {weights[0][0]}")
print(f"模型截距: {biases[0]}")
方案 2:model = tf.keras.Sequential()
解釋:
- 這種方式先創(chuàng)建一個(gè)空的?
Sequential
?模型,再使用?add
?方法添加?Dense
?層。 - 后續(xù)編譯、訓(xùn)練、評(píng)估和輸出模型參數(shù)的步驟與方案 1 類似。
import tensorflow as tf
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score# 自定義數(shù)據(jù)集
X = np.random.rand(100, 1).astype(np.float32)
y = 2 * X + 1 + 0.3 * np.random.randn(100, 1).astype(np.float32)# 構(gòu)建模型
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=(1,)))# 編譯模型
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),loss='mean_squared_error')# 訓(xùn)練模型
history = model.fit(X, y, epochs=1000, verbose=0)# 模型評(píng)估
y_pred = model.predict(X)
mse = mean_squared_error(y, y_pred)
r2 = r2_score(y, y_pred)
print(f"均方誤差 (MSE): {mse}")
print(f"決定系數(shù) (R2): {r2}")# 輸出模型的系數(shù)和截距
weights, biases = model.layers[0].get_weights()
print(f"模型系數(shù): {weights[0][0]}")
print(f"模型截距: {biases[0]}")
方案 3:自定義模型類
解釋:
- 繼承?
Model
?基類創(chuàng)建自定義模型類?Linear
,在?__init__
?方法中定義?Dense
?層。 call
?方法用于實(shí)現(xiàn)前向傳播邏輯,類似于 PyTorch 中的?forward
?方法。- 后續(xù)的編譯、訓(xùn)練、評(píng)估和參數(shù)輸出流程和前面方案一致。
import tensorflow as tf
from tensorflow.keras import Model
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score# 自定義數(shù)據(jù)集
X = np.random.rand(100, 1).astype(np.float32)
y = 2 * X + 1 + 0.3 * np.random.randn(100, 1).astype(np.float32)# 自定義模型類
class Linear(Model):def __init__(self):super(Linear, self).__init__()self.linear = tf.keras.layers.Dense(1)def call(self, x, **kwargs):x = self.linear(x)return x# 構(gòu)建模型
model = Linear()# 編譯模型
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),loss='mean_squared_error')# 訓(xùn)練模型
history = model.fit(X, y, epochs=1000, verbose=0)# 模型評(píng)估
y_pred = model.predict(X)
mse = mean_squared_error(y, y_pred)
r2 = r2_score(y, y_pred)
print(f"均方誤差 (MSE): {mse}")
print(f"決定系數(shù) (R2): {r2}")# 輸出模型的系數(shù)和截距
weights, biases = model.linear.get_weights()
print(f"模型系數(shù): {weights[0][0]}")
print(f"模型截距: {biases[0]}")
方案 4:函數(shù)式 API 構(gòu)建模型
解釋:
- 使用函數(shù)式 API 構(gòu)建模型,先定義輸入層,再定義?
Dense
?層,最后使用?Model
?類將輸入和輸出連接起來(lái)形成模型。 - 編譯、訓(xùn)練、評(píng)估和參數(shù)輸出的步驟和前面方案相同。注意這里通過(guò)?
model.layers[1]
?獲取?Dense
?層的權(quán)重和偏置,因?yàn)榈谝粚邮禽斎雽印?/li>
import tensorflow as tf
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score# 自定義數(shù)據(jù)集
X = np.random.rand(100, 1).astype(np.float32)
y = 2 * X + 1 + 0.3 * np.random.randn(100, 1).astype(np.float32)# 定義函數(shù)構(gòu)建模型
def linear():input = tf.keras.layers.Input(shape=(1,), dtype=tf.float32)y = tf.keras.layers.Dense(1)(input)model = tf.keras.models.Model(inputs=input, outputs=y)return model# 構(gòu)建模型
model = linear()# 編譯模型
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),loss='mean_squared_error')# 訓(xùn)練模型
history = model.fit(X, y, epochs=1000, verbose=0)# 模型評(píng)估
y_pred = model.predict(X)
mse = mean_squared_error(y, y_pred)
r2 = r2_score(y, y_pred)
print(f"均方誤差 (MSE): {mse}")
print(f"決定系數(shù) (R2): {r2}")# 輸出模型的系數(shù)和截距
weights, biases = model.layers[1].get_weights()
print(f"模型系數(shù): {weights[0][0]}")
print(f"模型截距: {biases[0]}")
3. 訓(xùn)練和評(píng)估部分:
- 使用?
fit
?方法對(duì)模型進(jìn)行訓(xùn)練,verbose=0
?表示不顯示訓(xùn)練過(guò)程中的詳細(xì)信息,訓(xùn)練過(guò)程中的損失信息會(huì)存儲(chǔ)在?history
?對(duì)象中。 - 通過(guò)多個(gè) epoch 進(jìn)行訓(xùn)練,每個(gè) epoch 包含前向傳播、損失計(jì)算、反向傳播和參數(shù)更新。
- 使用?
predict
?方法進(jìn)行預(yù)測(cè),計(jì)算均方誤差和決定系數(shù)評(píng)估模型性能,通過(guò)?model.linear.get_weights()
?獲取模型的系數(shù)和截距。
二、保存tensorflow框架邏輯回模型
方式 1:保存為 HDF5 文件(后綴名?.h5
)
這種方式會(huì)保存模型的結(jié)構(gòu)、權(quán)重以及訓(xùn)練配置(如優(yōu)化器、損失函數(shù)等),加載時(shí)可以直接得到一個(gè)完整可用的模型。
import tensorflow as tf
import numpy as np# 自定義數(shù)據(jù)集
# 生成 1000 個(gè)樣本,每個(gè)樣本有 2 個(gè)特征
X = np.random.randn(1000, 2).astype(np.float32)
# 根據(jù)特征生成標(biāo)簽
y = (2 * X[:, 0] + 3 * X[:, 1] > 0).astype(np.float32).reshape(-1, 1)# 構(gòu)建邏輯回歸模型
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(2,), activation='sigmoid')
])# 編譯模型
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])# 訓(xùn)練模型
model.fit(X, y, epochs=100, batch_size=32, verbose=1)# 保存模型為 HDF5 文件
model.save('logistic_regression_model.h5')# 加載 HDF5 文件模型
loaded_model = tf.keras.models.load_model('logistic_regression_model.h5')# 生成新的測(cè)試數(shù)據(jù)
X_test = np.random.randn(100, 2).astype(np.float32)
y_test = (2 * X_test[:, 0] + 3 * X_test[:, 1] > 0).astype(np.float32).reshape(-1, 1)# 進(jìn)行預(yù)測(cè)
y_pred_probs = loaded_model.predict(X_test)
y_pred = (y_pred_probs > 0.5).astype(np.float32)# 計(jì)算準(zhǔn)確率
accuracy = tf.keras.metrics.BinaryAccuracy()
accuracy.update_state(y_test, y_pred)
print(f"預(yù)測(cè)準(zhǔn)確率: {accuracy.result().numpy()}")
代碼解釋
- 數(shù)據(jù)生成與模型構(gòu)建:生成自定義數(shù)據(jù)集,構(gòu)建并編譯邏輯回歸模型,然后進(jìn)行訓(xùn)練。
- 保存模型:使用?
model.save('logistic_regression_model.h5')
?將模型保存為 HDF5 文件。 - 加載模型:使用?
tf.keras.models.load_model('logistic_regression_model.h5')
?加載保存的模型。 - 預(yù)測(cè)與評(píng)估:生成新的測(cè)試數(shù)據(jù),使用加載的模型進(jìn)行預(yù)測(cè),并計(jì)算預(yù)測(cè)準(zhǔn)確率。
方式 2:只保存參數(shù)
這種方式只保存模型的權(quán)重參數(shù),不保存模型的結(jié)構(gòu)和訓(xùn)練配置。加載時(shí)需要先定義與原模型相同結(jié)構(gòu)的模型,再將保存的參數(shù)加載到新模型中。
import tensorflow as tf
import numpy as np# 自定義數(shù)據(jù)集
# 生成 1000 個(gè)樣本,每個(gè)樣本有 2 個(gè)特征
X = np.random.randn(1000, 2).astype(np.float32)
# 根據(jù)特征生成標(biāo)簽
y = (2 * X[:, 0] + 3 * X[:, 1] > 0).astype(np.float32).reshape(-1, 1)# 構(gòu)建邏輯回歸模型
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(2,), activation='sigmoid')
])# 編譯模型
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])# 訓(xùn)練模型
model.fit(X, y, epochs=100, batch_size=32, verbose=1)# 只保存模型參數(shù)
model.save_weights('logistic_regression_weights.h5')# 重新定義相同結(jié)構(gòu)的模型
new_model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(2,), activation='sigmoid')
])# 編譯新模型
new_model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])# 加載保存的參數(shù)到新模型
new_model.load_weights('logistic_regression_weights.h5')# 生成新的測(cè)試數(shù)據(jù)
X_test = np.random.randn(100, 2).astype(np.float32)
y_test = (2 * X_test[:, 0] + 3 * X_test[:, 1] > 0).astype(np.float32).reshape(-1, 1)# 進(jìn)行預(yù)測(cè)
y_pred_probs = new_model.predict(X_test)
y_pred = (y_pred_probs > 0.5).astype(np.float32)# 計(jì)算準(zhǔn)確率
accuracy = tf.keras.metrics.BinaryAccuracy()
accuracy.update_state(y_test, y_pred)
print(f"預(yù)測(cè)準(zhǔn)確率: {accuracy.result().numpy()}")
代碼解釋
- 數(shù)據(jù)生成與模型構(gòu)建:同樣生成自定義數(shù)據(jù)集,構(gòu)建并編譯邏輯回歸模型,進(jìn)行訓(xùn)練。
- 保存參數(shù):使用?
model.save_weights('logistic_regression_weights.h5')
?只保存模型的權(quán)重參數(shù)。 - 重新定義模型:重新定義一個(gè)與原模型結(jié)構(gòu)相同的新模型,并進(jìn)行編譯。
- 加載參數(shù):使用?
new_model.load_weights('logistic_regression_weights.h5')
?將保存的參數(shù)加載到新模型中。 - 預(yù)測(cè)與評(píng)估:生成新的測(cè)試數(shù)據(jù),使用加載參數(shù)后的新模型進(jìn)行預(yù)測(cè),并計(jì)算預(yù)測(cè)準(zhǔn)確率。
通過(guò)以上兩種方式,可以根據(jù)實(shí)際需求選擇合適的模型保存方法。
三、加載tensorflow框架邏輯回歸模型
方案 1:加載保存為 HDF5 文件的模型
當(dāng)用戶將模型保存為 HDF5 文件(后綴名?.h5
)時(shí),使用?tf.keras.models.load_model
?函數(shù)可以直接加載整個(gè)模型,包括模型的結(jié)構(gòu)、權(quán)重以及訓(xùn)練配置。
import tensorflow as tf
import numpy as np# 生成一些示例數(shù)據(jù)用于預(yù)測(cè)
X_test = np.random.randn(100, 2).astype(np.float32)
y_test = (2 * X_test[:, 0] + 3 * X_test[:, 1] > 0).astype(np.float32).reshape(-1, 1)# 加載保存為 HDF5 文件的模型
loaded_model = tf.keras.models.load_model('logistic_regression_model.h5')# 進(jìn)行預(yù)測(cè)
y_pred_probs = loaded_model.predict(X_test)
y_pred = (y_pred_probs > 0.5).astype(np.float32)# 計(jì)算準(zhǔn)確率
accuracy = tf.keras.metrics.BinaryAccuracy()
accuracy.update_state(y_test, y_pred)
print(f"預(yù)測(cè)準(zhǔn)確率: {accuracy.result().numpy()}")
代碼解釋
- 數(shù)據(jù)準(zhǔn)備:生成一些示例數(shù)據(jù)?
X_test
?和對(duì)應(yīng)的標(biāo)簽?y_test
,用于后續(xù)的預(yù)測(cè)和評(píng)估。 - 模型加載:使用?
tf.keras.models.load_model('logistic_regression_model.h5')
?加載之前保存為 HDF5 文件的模型。 - 預(yù)測(cè)與評(píng)估:使用加載的模型對(duì)測(cè)試數(shù)據(jù)進(jìn)行預(yù)測(cè),將預(yù)測(cè)概率轉(zhuǎn)換為標(biāo)簽,然后計(jì)算預(yù)測(cè)準(zhǔn)確率。
方案 2:加載只保存的參數(shù)(權(quán)重和偏置)
當(dāng)用戶只保存了模型的參數(shù)(權(quán)重和偏置)時(shí),需要先定義一個(gè)與原模型結(jié)構(gòu)相同的新模型,然后使用?load_weights
?方法將保存的參數(shù)加載到新模型中。
import tensorflow as tf
import numpy as np# 生成一些示例數(shù)據(jù)用于預(yù)測(cè)
X_test = np.random.randn(100, 2).astype(np.float32)
y_test = (2 * X_test[:, 0] + 3 * X_test[:, 1] > 0).astype(np.float32).reshape(-1, 1)# 重新定義相同結(jié)構(gòu)的模型
new_model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(2,), activation='sigmoid')
])# 編譯新模型
new_model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])# 加載保存的參數(shù)
new_model.load_weights('logistic_regression_weights.h5')# 進(jìn)行預(yù)測(cè)
y_pred_probs = new_model.predict(X_test)
y_pred = (y_pred_probs > 0.5).astype(np.float32)# 計(jì)算準(zhǔn)確率
accuracy = tf.keras.metrics.BinaryAccuracy()
accuracy.update_state(y_test, y_pred)
print(f"預(yù)測(cè)準(zhǔn)確率: {accuracy.result().numpy()}")
代碼解釋
- 數(shù)據(jù)準(zhǔn)備:同樣生成示例數(shù)據(jù)?
X_test
?和?y_test
?用于預(yù)測(cè)和評(píng)估。 - 模型定義與編譯:重新定義一個(gè)與原模型結(jié)構(gòu)相同的新模型?
new_model
,并進(jìn)行編譯,設(shè)置優(yōu)化器、損失函數(shù)和評(píng)估指標(biāo)。 - 參數(shù)加載:使用?
new_model.load_weights('logistic_regression_weights.h5')
?將之前保存的參數(shù)加載到新模型中。 - 預(yù)測(cè)與評(píng)估:使用加載參數(shù)后的新模型對(duì)測(cè)試數(shù)據(jù)進(jìn)行預(yù)測(cè),將預(yù)測(cè)概率轉(zhuǎn)換為標(biāo)簽,最后計(jì)算預(yù)測(cè)準(zhǔn)確率。
通過(guò)以上兩種方案,可以根據(jù)不同的保存方式正確加載 TensorFlow 模型。
四、完整流程
1. 實(shí)現(xiàn)思路
①?導(dǎo)入必要的庫(kù)
在開始之前,需要導(dǎo)入 TensorFlow 用于構(gòu)建和訓(xùn)練模型,NumPy 用于數(shù)據(jù)處理,以及一些評(píng)估指標(biāo)相關(guān)的庫(kù)。
②?生成自定義數(shù)據(jù)集
自定義數(shù)據(jù)集可以根據(jù)具體需求生成,這里以一個(gè)簡(jiǎn)單的二維數(shù)據(jù)集為例,每個(gè)樣本有兩個(gè)特征,標(biāo)簽為 0 或 1。
③?構(gòu)建邏輯回歸模型
一共有4種方式,案例使用其中的TensorFlow的tf.keras.Sequential
?構(gòu)建模型,在列表中直接定義了一個(gè)?Dense
?層,input_shape=(1,)
?表明輸入數(shù)據(jù)的形狀。
④?訓(xùn)練模型
使用生成的數(shù)據(jù)集對(duì)模型進(jìn)行訓(xùn)練。
⑤?保存模型
可以選擇將模型保存為 HDF5 文件或只保存模型的參數(shù),案例為保存為 HDF5 文件。
⑥ 加載模型并進(jìn)行預(yù)測(cè)
此案例為加載 HDF5 文件模型
2. 代碼示例
import tensorflow as tf
import numpy as np
from sklearn.metrics import accuracy_score# 生成 1000 個(gè)樣本,每個(gè)樣本有 2 個(gè)特征
X = np.random.randn(1000, 2).astype(np.float32)
# 根據(jù)特征生成標(biāo)簽
y = (2 * X[:, 0] + 3 * X[:, 1] > 0).astype(np.float32).reshape(-1, 1)# 構(gòu)建邏輯回歸模型
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(2,), activation='sigmoid')
])# 編譯模型
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])# 訓(xùn)練模型
model.fit(X, y, epochs=100, batch_size=32, verbose=1)# 保存模型
model.save('logistic_regression_model')# 加載模型
loaded_model = tf.keras.models.load_model('logistic_regression_model')# 生成新的測(cè)試數(shù)據(jù)
X_test = np.random.randn(100, 2).astype(np.float32)
y_test = (2 * X_test[:, 0] + 3 * X_test[:, 1] > 0).astype(np.float32).reshape(-1, 1)# 進(jìn)行預(yù)測(cè)
y_pred_probs = loaded_model.predict(X_test)
y_pred = (y_pred_probs > 0.5).astype(np.float32)# 計(jì)算準(zhǔn)確率
accuracy = accuracy_score(y_test, y_pred)
print(f"預(yù)測(cè)準(zhǔn)確率: {accuracy}")
3. 代碼解釋
① 數(shù)據(jù)集生成:
使用?np.random.randn
?生成具有兩個(gè)特征的隨機(jī)樣本,根據(jù)特征的線性組合生成標(biāo)簽。
② 模型構(gòu)建:
使用?tf.keras.Sequential
?構(gòu)建一個(gè)簡(jiǎn)單的邏輯回歸模型,包含一個(gè)具有?sigmoid
?激活函數(shù)的全連接層。
③ 模型編譯:
使用?adam
?優(yōu)化器和?binary_crossentropy
?損失函數(shù)進(jìn)行編譯,并監(jiān)控準(zhǔn)確率指標(biāo)。
④ 模型訓(xùn)練:
使用?fit
?方法對(duì)模型進(jìn)行訓(xùn)練,指定訓(xùn)練輪數(shù)和批次大小。
⑤ 模型保存:
使用?model.save
?方法將模型保存到指定目錄。
⑥ 模型加載與預(yù)測(cè):
使用?tf.keras.models.load_model
?加載保存的模型,生成新的測(cè)試數(shù)據(jù)進(jìn)行預(yù)測(cè),并計(jì)算預(yù)測(cè)準(zhǔn)確率。