nb.py 762 B

123456789101112131415161718192021222324252627282930313233343536
  1. #%%
  2. import tensorflow as tf
  3. from tensorflow.keras import layers
  4. pip install -U scikit-learn
  5. #%%
  6. # 添加dropout操作
  7. x = tf.nn.dropout(x, rate=0.5)
  8. # 添加Dropout层
  9. model.add(layers.Dropout(rate=0.5))
  10. # 手动计算每个张量的范数
  11. loss_reg = lambda_ * tf.reduce_sum(tf.square(w))
  12. # 在层方式时添加范数函数
  13. Dense(256, activation='relu',
  14. kernel_regularizer=regularizers.l2(_lambda))
  15. #%%
  16. #
  17. # 创建网络参数w1,w2
  18. w1 = tf.random.normal([4,3])
  19. w2 = tf.random.normal([4,2])
  20. # 计算L1正则化项
  21. loss_reg = tf.reduce_sum(tf.math.abs(w1))\
  22. + tf.reduce_sum(tf.math.abs(w2))
  23. # 计算L2正则化项
  24. loss_reg = tf.reduce_sum(tf.square(w1))\
  25. + tf.reduce_sum(tf.square(w2))
  26. #%%
  27. loss_reg
  28. #%%