Sco*_*tie 2 python machine-learning keras tensorflow
我正在尝试通过 TensorFlow 2.0 + Keras 构建二元分类模型。每个目标都有5特征,我希望这个模型可以预测输入数据是否属于a。
fit()然而,和之间的准确度完全不同predict()。最奇怪的是,我把训练数据交给模型进行预测,模型却没有返回1。
构建训练数据:(a的特征标记为1,其他特征标记为0)
num_train = 50
data = { # the content is fake, just for understanding the format
'a': [(1, 2, 3, 4, 5), (2, 3, 4, 5, 6), ...],
'b': [(10, 20, 30, 40, 50), (20, 30, 40, 50, 60), ...],
...
}
train_x = []
train_y = []
for name, features in data.items():
for f in features[:num_train]:
train_x.append(f)
train_y.append(1 if name == 'a' else 0)
train_x = np.array(train_x)
train_y = np.array(train_y)
Run Code Online (Sandbox Code Playgroud)
模型如下:
model = Sequential()
model.add(Dense(1, activation='sigmoid', input_dim=5))
model.compile(optimizer='sgd', loss='mse', metrics=['accuracy'])
Run Code Online (Sandbox Code Playgroud)
并致电model.fit():
model.fit(x=train_x, y=train_y, validation_split=0.2, batch_size=10, epochs=50)
Run Code Online (Sandbox Code Playgroud)
纪元 50 之后:
Epoch 50/50
653/653 [==============================] - 0s 80us/sample - loss: 0.0745 - accuracy: 0.9234 - val_loss: 0.0192 - val_accuracy: 1.0000
Run Code Online (Sandbox Code Playgroud)
最后我用大家的前3个样本来预测:
for name, features in data.items():
test_x = features[:3]
print(name, np.around(model.predict(test_x), decimals=2))
Run Code Online (Sandbox Code Playgroud)
输出:
a [[0.14] [0.14] [0.14]]
b [[0.14] [0.13] [0.13]]
c [[0.14] [0.14] [0.13]]
...
Run Code Online (Sandbox Code Playgroud)
完整的数据和源代码已上传至Google Drive,请查看链接。
小智 5
检查源代码后,存在一些实现问题:
- 训练数据和验证数据由 Keras 随机化
在训练期间,20% 的数据被采样为验证数据,但您不知道采样的数据是否平衡(即训练数据和验证数据中类的比例相同)。在你的例子中,由于不平衡,采样的训练数据很可能大部分来自 0 类,因此你的模型没有学到任何有用的东西(因此输出都是相同的)0.13样本的输出都是相同的)。
更好、更可控的方法是在训练之前以分层方式分割数据:
from sklearn.model_selection import train_test_split
num_train = 50
train_x = []
train_y = []
for name, features in data.items():
for f in features[:num_train]:
train_x.append(f)
train_y.append(1 if name == 'a' else 0)
train_x = np.array(train_x)
train_y = np.array(train_y)
# Split your data, and stratify according to the target label `train_y`
# Set a random_state, so that the train-test split is reproducible
x_train, x_test, y_train, y_test = train_test_split(train_x, train_y, test_size=0.2, stratify=train_y, random_state=123)
Run Code Online (Sandbox Code Playgroud)
在训练期间,您指定而validation_data不是使用validation_split:
model = Sequential()
model.add(Dense(1, activation='sigmoid', input_dim=5))
model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x=x_train, y=y_train,
validation_data=(x_test, y_test), # Use this instead
class_weight={0:1,1:17}, # See explanation in 2. Imbalanced class
batch_size=10, epochs=500)
Run Code Online (Sandbox Code Playgroud)
- 高度不平衡的类别 - 1 类的频率比 0 类低 17 倍
您的 1 级a比 0 级小 17 倍(由其余部分组成)。如果您不调整类别权重,您的模型会平等对待所有样本,并且通过简单地将所有样本分类为 0 类,您的模型的准确度将为 94.4%(其余 5.6% 全部来自 1 类,并且全部被错误地分类为这个天真的模型)。
为了解决类别不平衡的问题,一种方法是为少数类别设置更高的损失。在此示例中,我将类别 1 的类别权重设置为类别 0 的 17 倍:
class_weight={0:1,1:17}
Run Code Online (Sandbox Code Playgroud)
通过这样做,您可以告诉模型,错误预测的第 1 类中的每个样本都会导致比错误分类的第 0 类多 17 倍的惩罚。因此,模型被迫更多地关注第 1 类,尽管它是少数民族阶层。
- 获得原始预测后不应用阈值。
训练后(请注意,我将 增加到epochs500,并且模型在大约 200 个 epoch 后收敛),对您之前获得的测试集进行预测:
preds = model.predict(x_test)
Run Code Online (Sandbox Code Playgroud)
你会得到这样的结果:
[[0.33624142]
[0.58196825]
[0.5549609 ]
[0.38138568]
[0.45235538]
[0.32419187]
[0.37660158]
[0.37013668]
[0.5794893 ]
[0.5611163 ]
......]
Run Code Online (Sandbox Code Playgroud)
这是神经网络的原始输出,其范围为[0,1],因为最后一个激活层将sigmoid其压缩到该范围。为了将其转换为您需要的类预测(类 0 或 1),需要应用阈值。通常,该阈值设置为 0.5,其中输出大于 0.5 的预测意味着样本可能来自类别 1,否则输出小于 0.5。
因此,您需要使用阈值输出
threshold_output = np.where(preds > 0.5, 1, 0)
Run Code Online (Sandbox Code Playgroud)
你将得到实际的班级预测:
[[0]
[1]
[1]
[0]
[0]
[0]
[0]
[0]
[1]
[1]
...]
Run Code Online (Sandbox Code Playgroud)
获得训练和测试的准确性
现在,要检查训练和测试的准确性,您可以sklearn.metric直接使用,这省去了手动计算它们的麻烦:
from sklearn.metrics import accuracy_score
train_preds = np.where(model.predict(x_train) > 0.5, 1, 0)
test_preds = np.where(model.predict(x_test) > 0.5, 1, 0)
train_accuracy = accuracy_score(y_train, train_preds)
test_accuracy = accuracy_score(y_test, test_preds)
print(f'Train Accuracy : {train_accuracy:.4f}')
print(f'Test Accuracy : {test_accuracy:.4f}')
Run Code Online (Sandbox Code Playgroud)
它为您提供:
Train Accuracy : 0.7443
Test Accuracy : 0.7073
Run Code Online (Sandbox Code Playgroud)
希望这能回答您的问题!