Keras的loss_weights和class_weight

loss_weights

是model.compile的参数,对应于模型的每个输出的损失的权重。loss_weights是一个列表,对应于每个输出的权重,默认1.

Model.compile(
    optimizer="rmsprop",
    loss=None,
    metrics=None,
    loss_weights=None,
    weighted_metrics=None,
    run_eagerly=None,
    steps_per_execution=None,
    **kwargs
)
  • loss_weights: Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the weighted sum of all individual losses, weighted by the loss_weights coefficients. If a list, it is expected to have a 1:1 mapping to the model's outputs. If a dict, it is expected to map output names (strings) to scalar coefficients.

class_weight

是model.fit的参数,对应于样本类别的权重,可以更加关注数量少得样本。

当数据集不平衡时,可以为每个类设置类权重。假设有 5000 个类狗样本和 45000 个类非狗样本,class_weight= [0:5,1:0.5],这给类"狗"10倍的权重作用在损失函数。

Model.fit(
    x=None,
    y=None,
    batch_size=None,
    epochs=1,
    verbose="auto",
    callbacks=None,
    validation_split=0.0,
    validation_data=None,
    shuffle=True,
    class_weight=None,
    sample_weight=None,
    initial_epoch=0,
    steps_per_epoch=None,
    validation_steps=None,
    validation_batch_size=None,
    validation_freq=1,
    max_queue_size=10,
    workers=1,
    use_multiprocessing=False,
)
  • class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Dense, Conv1D, MaxPooling1D, Flatten from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix, classification_report from sklearn.metrics import roc_auc_score from sklearn.utils.class_weight import compute_class_weight # 读取数据 data = pd.read_csv('database.csv') # 数据预处理 X = data.iloc[:, :-1].values y = data.iloc[:, -1].values scaler = StandardScaler() X = scaler.fit_transform(X) # 特征选择 pca = PCA(n_components=10) X = pca.fit_transform(X) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) class_weights = compute_class_weight(class_weight='balanced', classes=np.unique(y_train), y=y_train) # 构建CNN模型 model = Sequential() model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(10, 1))) model.add(MaxPooling1D(pool_size=2)) model.add(Flatten()) model.add(Dense(10, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1)) X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1)) model.fit(X_train, y_train,class_weight=class_weights,epochs=100, batch_size=64, validation_data=(X_test, y_test)) # 预测结果 y_pred = model.predict(X_test) #检验值 accuracy = accuracy_score(y_test, y_pred) auc = roc_auc_score(y_test, y_pred) print(auc) print("Accuracy:", accuracy) print('Confusion Matrix:\n', confusion_matrix(y_test, y_pred)) print('Classification Report:\n', classification_report(y_test, y_pred))
最新发布
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值