学习视频和代码来源慕课
1. import
2. train, test
3. model = tf.keras.models.Sequential
Flatten 把数据转成一维数组 tf.keras.layers.Flatten()
全连接层 tf.keras.layers.Dense(神经元个数,activation='激活函数',kernel_regularizer=哪种正则化)
activation='relu','softmax','sigmoid','tanh'
kernel_regularizer可选:tf.keras.kernel_regularizers.l1(),tf.keras.kernel_regularizers.l2()
卷积层:tf.keras.layers.Conv2D(filters=卷积核个数,
kernel_size=卷积核尺寸,
strides=步长,
padding='vaild' or 'same',
activation='relu','softmax','sigmoid','tanh',
input_shape=(高,宽,通道数)可省略
)
LSTM层:tf.keras.layers.LSTM()
4. model.compile
model.compile(optimizer=优化器,loss=损失函数,metrics=['准确率'])
配置网络
optimizer可选:
'sgd' or tf.keras.optimizers.SGD (Ir=学习率,momentum=动量参数)
'adagrad' or tf.keras.optimizers.Adagrad (Ir=学习率)
'adadelta' or tf.keras.optimizers.Adadelta (Ir=学习率)
'adam' or tf.keras.optimizers.Adam (lr=学习率, beta_1=0.9, beta_2
loss可选:
'mse' or tf.keras.losses.MeanSquaredError()
'sparse_categorical_crossentropy' or tf.keraslosses.SparseCategoricalCrossentropy(from_logits=False)
from_logits是否是原始输出,也就是没有经过softmax的输出,没有经过则是True
Metrics可选:
'accuracy':y_和y都是数值 如y_=[1] y=[1]
'categorical_accuracy':y_和y都是独热码(概率分布),如y_=[0,1,0] y=[0.2145,0.6584,0.9991]
'sparse_categorical_crossentropy':y_是数值,y是独热编码(概率分布),如y_=[1],y=[0.2145,0.6584,0.9991]
5. model.fit
model.fit(训练集的输入特征,训练集的标签,batch_size=,epochs=,validation_data(测试集的输入特征,测试集的标签),validation_split=划分比例,validation_freq=多少次opoch测试一次)
6. model.summary
打印网络结构
示例:
# 鸢尾花分类
import tensorflow as tf
from sklearn import datasets
import numpy as np
x_train = datasets.load_iris().data
y_train = datasets.load_iris().target
np.random.seed(116)
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.L2())
])
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.1),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_crossentropy']
)
model.fit(x_train, y_train, batch_size=32, epochs=100,validation_split=0.2, validation_freq=20)
model.summary()
1. import
2. train, test
3. class MyModel(Model) model=Mymodel
class Mymodel(Model):
def __init__(self):
super(Mymodel,self).__init__()
# 定义网络结构块
self.d1 = Dense(3)
def call(self,x):
# 调用网络结构块,实现前向传播
y = self.d1(x)
return y
model = MyModel()
4. model.compile
model.compile(optimizer=优化器,loss=损失函数,metrics=['准确率'])
配置网络
optimizer可选:
'sgd' or tf.keras.optimizers.SGD (Ir=学习率,momentum=动量参数)
'adagrad' or tf.keras.optimizers.Adagrad (Ir=学习率)
'adadelta' or tf.keras.optimizers.Adadelta (Ir=学习率)
'adam' or tf.keras.optimizers.Adam (lr=学习率, beta_1=0.9, beta_2
loss可选:
'mse' or tf.keras.losses.MeanSquaredError()
'sparse_categorical_crossentropy' or tf.keraslosses.SparseCategoricalCrossentropy(from_logits=False)
from_logits是否是原始输出,也就是没有经过softmax的输出,没有经过则是True
Metrics可选:
'accuracy':y_和y都是数值 如y_=[1] y=[1]
'categorical_accuracy':y_和y都是独热码(概率分布),如y_=[0,1,0] y=[0.2145,0.6584,0.9991]
'sparse_categorical_crossentropy':y_是数值,y是独热编码(概率分布),如y_=[1],y=[0.2145,0.6584,0.9991]
5. model.fit
model.fit(训练集的输入特征,训练集的标签,batch_size=,epochs=,validation_data(测试集的输入特征,测试集的标签),validation_split=划分比例,validation_freq=多少次opoch测试一次)
6. model.summary
示例:
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
from sklearn import datasets
import numpy as np
x_train = datasets.load_iris().data
y_train = datasets.load_iris().target
np.random.seed(116)
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)
class IrisModel(Model):
def __init__(self):
super(IrisModel, self).__init__()
self.d1 = Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.L2())
def call(self, x):
y = self.d1(x)
return y
model = IrisModel()
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.1),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_crossentropy']
)
model.fit(x_train, y_train, batch_size=32, epochs=100, validation_split=0.2, validation_freq=20)
model.summary()