1、First of All: Read The Fucking Source Code
import autokeras as ak
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error# 生成數據集
np.random.seed(42)
x = np.random.rand(1000, 10) # 生成1000個樣本,每個樣本有10個特征
y = x.dot([0.5, -1.5, 2.0, -0.8, 1.2, -0.3, 0.7, -1.1, 0.4, -0.6]) + 3.0 # 生成目標變量# 劃分訓練集和測試集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)input_node = ak.Input()
output_node = ak.DenseBlock()(input_node) # 數值特征處理層
output_node = ak.RegressionHead()(output_node)# 初始化AutoModel,指定為回歸任務
regressor = ak.AutoModel(inputs=input_node, # 指定輸入節點outputs=output_node, # 指定輸出節點overwrite=True, # 覆蓋之前的搜索結果max_trials=2 # 最大嘗試次數
)# 訓練模型
regressor.fit(x_train, y_train, epochs=10)# 評估模型
predictions = regressor.predict(x_test)
mse = mean_squared_error(y_test, predictions)
print('Mean Squared Error: {:.2f}'.format(mse))# 顯示最佳模型信息
model = regressor.export_model()
model.summary()
?注:以上基于AutoKeras 2.0版本回歸測試的例子,特別使用了通用的AutoModel的寫法,其1.1版本不支持。
2、代碼結構簡介
AutoKeras是一個基于Keras的自動機器學習庫,它能夠自動搜索最優的神經網絡架構。上述為一個簡單的回歸任務示例代碼,主要包含以下部分:
- 生成模擬數據集并進行訓練/測試集劃分
- 定義AutoKeras的輸入輸出節點
- ?配置并訓練AutoModel
- ?預測并計算均方誤差
- ?查看最佳模型結構
3、AutoModel輸入輸出說明
input_node = ak.Input()
output_node = ak.DenseBlock()(input_node) ?# 數值特征處理層
output_node = ak.RegressionHead()(output_node)
輸入部分:
input_node = ak.Input()
?創建輸入節點- 無需指定輸入形狀,AutoKeras會自動推斷
處理層部分:
DenseBlock()
?處理數值特征- 通過函數式API連接:
output_node = ak.DenseBlock()(input_node)
輸出部分:
RegressionHead()
?指定回歸任務- 同樣使用函數式API連接
AutoModel配置:
inputs
參數接收輸入節點outputs
參數接收輸出節點
?