本文将介绍如下内容:
- 自定义损失函数
- 自定义DenseLayer
一,自定义损失函数
1,在TF中实现自定义损失函数
在TF中实现的demo如下:
import tensorflow as tf
import numpy as np
y_pred = np.array([1,4,3,2,6,5,9])
y_true = np.array([1,4,3,2,1,4,9])
print(tf.reduce_mean(tf.square(y_pred - y_true)))
# ---output------
tf.Tensor(3, shape=(), dtype=int64)
结合之前的实例如下:
def customized_mse(y_true, y_pred):
return tf.reduce_mean(tf.square(y_pred - y_true))
model = keras.models.Sequential([
keras.layers.Dense(30, activation='relu',
input_shape=x_train.shape[1:]),
keras.layers.Dense(1),
])
model.summary()
model.compile(loss=customized_mse, optimizer="sgd",
metrics=["mean_squared_error"])
callbacks = [keras.callbacks.EarlyStopping(
patience=5, min_delta=1e-2)]
2,总结代码如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras
# 1,打印使用的python库的版本信息
print(tf.__version__)
print(sys.version_info)
for module in mpl, np, pd, sklearn, tf, keras:
print(module.__name__, module.__version__)
# 2,下载并使用sklearn中的“fetch_california_housing”数据集
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing()
print(housing.DESCR)
print(housing.data.shape)
print(housing.target.shape)
# 3,拆分数据集中的数据为 训练数据、验证数据、测试数据
from sklearn.model_selection import train_test_split
x_train_all, x_test, y_train_all, y_test = train_test_split(
housing.data, housing.target, random_state = 7)
x_train, x_valid, y_train, y_valid = train_test_split

本文聚焦于在TF中进行自定义操作,主要介绍了自定义损失函数和自定义DenseLayer两方面内容。详细阐述了在TF里实现自定义损失函数的方法,还对tf.keras.layers.Dense的属性、计算公式等进行讲解,并给出了在TF中实现自定义DenseLayer的方式,最后都给出了总结代码。
最低0.47元/天 解锁文章
1145

被折叠的 条评论
为什么被折叠?



