张 量 与 操 作 − − − 三 种 建 模 方 法 张量与操作---三种建模方法 张量与操作−−−三种建模方法
import tensorflow as tf
print(tf.__version__)
print(tf.test.is_gpu_available())
一 张量
# Rank 0
mammal=tf.Variable("Elephant",tf.string)
tf.print(tf.rank(mammal))
tf.print(tf.shape(mammal))
print(tf.rank(mammal))
#Rank 1
mystr=tf.Variable(["Hello"],tf.string)
tf.print(tf.rank(mystr))
tf.print(tf.shape(mystr))
#Rank 2
mymat=tf.Variable([[7],[11]],tf.int16)
tf.print(tf.rank(mymat))
tf.print(tf.shape(mymat))
创建张量
tf.constant([1,2,3],dtype=tf.int16)
tf.zeros((2,2),dtype=tf.int16)
reshape
rank_three_tensor=tf.ones([3,4,5])
tf.print("rank_three_tensor")
tf.print(rank_three_tensor)
matrix=tf.reshape(rank_three_tensor,[6,10])
tf.print("matrix")
tf.print(matrix)
yet_another=tf.reshape(rank_three_tensor,[8, 10])#报错 数量不一致
操作
- tf.strings
- tf.debugging
- tf.dtypes
- tf.math
- tf.random
- tf.feature_column 建议参考,常用于特征处理.
tf.strings
#字符切割
tf.strings.bytes_split('hello')
help(tf.strings.split)
#单词切割
tf.strings.split('hello world')
#string hash
tf.strings.to_hash_bucket(['hello','world'], num_buckets=10)
tf.debugging
#tf自带debug函数
a=tf.random.uniform((10,10))
tf.debugging.assert_equal(x=a.shape,y=(10,10))
#错误示范
tf.debugging.assert_equal(x=a.shape,y=(20,10))
tf.math
a = tf.constant([[1,2],[3,4]])
b = tf.constant([[5,6],[7,8]])
tf.print(tf.math.add(a,b))
tf.print(tf.math.subtract(a,b))
tf.print(tf.math.multiply(a,b))
tf.print(tf.math.divide(a,b))
print(tf.math.add(a,b))
tf.dtypes
x =tf.constant([1.8,2.2],dtype=tf.float32)
x1=tf.dtypes.cast(x,tf.int32)
x1
二 常用层
- tf.keras.layers:是封装后的高阶API
- tf.nn:底层函数库
在大多数据情况下,可以使用TensorFlow封装的tf.keras.layers构建的一些层建模,Keras层是非常有用的。
可以在文档中查看预先存在的层的完整列表。它包括Dense,Conv2D,LSTM,BatchNormalization,Dropout等。
#文本分类
a = tf.random.uniform(shape = (10,100,50),minval=-0.5,maxval=0.5) #张量
x = tf.keras.layers.LSTM(100)(a) #LSTM
x = tf.keras.layers.Dense(10)(x) #全连接层
x = tf.nn.softmax(x) #激活函数
增加层的参数配置
#层中增加激活函数
tf.keras.layers.Dense(64, activation='relu')
#or
tf.keras.layers.Dense(64, activation=tf.nn.relu)
#将L1正则化系数为0.01的线性层应用于内核矩阵
tf.keras.layers.Dense(64, kernel_regularizer=tf.keras.regularizers.l1(0.01))
# 将L2正则化系数为0.01的线性层应用于偏差向量:
tf.keras.layers.Dense(64, bias_regularizer=tf.keras.regularizers.l2(0.01))
# 内核初始化为随机正交矩阵的线性层:
tf.keras.layers.Dense(64, kernel_initializer='orthogonal')
# 偏差向量初始化为2.0的线性层:
tf.keras.layers.Dense(64, bias_initializer=tf.keras.initializers.Constant(2.0))
三 三种建模方式
- Sequential model(顺序模型):对于顺序结构的模型,优先使用Sequential方法构建。
- Functional model(函数模型):如果模型有多输入或者多输出,或者模型需要共享权重,或者模型具有残差连接等非顺序结构,推荐使用函数式APl进
- Subclassing model(子类化模型):需要自定义层之间的传输、复杂模型。
1.Sequential model(顺序模型)
第一种Sequential model
from tensorflow.keras import layers
import tensorflow as tf
model = tf.keras.Sequential()
model.add(layers.Dense(64, activation='relu'))#第一层
model.add(layers.Dense(64, activation='relu'))#第二层
model.add(layers.Dense(10))#第三层
# 。。。。。。。
第二种Sequential model
model = tf.keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(32,)),#第一层
layers.Dense(64, activation='relu'),#第二层
layers.Dense(10)#第三层
#。。。。。
])
model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
import numpy as np
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.fit(data, labels, epochs=10, batch_size=32)
tf.keras.Model.fit (用于模型训练)
- epochs:训练分为几个时期。每一个epoch是对整个输入数据的一次迭代(此操作以较小的批次完成)。
- batch_size:当传递NumPy数据时,模型将数据切成较小的批次,并在训练期间对这些批次进行迭代。该整数指定每个批次的大小。请注意,如果不能将样本总数除以批次大小,则最后一批可能会更小。
- validation_data:在模型训练时,监控在某些验证数据上监视其性能。传递此参数(输入和标签的元组)可以使模型在每个时期结束时以推断模式显示所传递数据的损失和度量。
2. Functional model
函数式模型是一种创建模型的方法,该模型比tf.keras.Sequential更灵活。函数式模型可以处理具有非线性拓扑的模型,具有共享层的模型以及具有多个输入或输出的模型等等
深度学习模型通常是层的有向无环图(DAG)的主要思想。因此,函数式模型是一种构建层图的方法。
举个例子:
“”"
(input: 32-dimensional vectors)
↧
[Dense (64 units, relu activation)]
↧
[Dense (64 units, relu activation)]
↧
[Dense (10 units, softmax activation)]
↧
(output: logits of a probability distribution over 10 classes)
“”"
inputs = tf.keras.Input(shape=(32,))
# inputs = tf.keras.Input(shape=(32,))
x = layers.Dense(64, activation='relu')(inputs) #第一层
x = layers.Dense(64, activation='relu')(x) #第二层
predictions = layers.Dense(10)(x) #第三层
model = tf.keras.Model(inputs=inputs, outputs=predictions)
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
import numpy as np
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.fit(data, labels, batch_size=32, epochs=5)
inputs1 = tf.keras.Input(shape=(32,)) #输入1
inputs2 = tf.keras.Input(shape=(32,)) #输入2
x1 = layers.Dense(64, activation='relu')(inputs1) #第一层
x2 = layers.Dense(64, activation='relu')(inputs2) #第一层
x = tf.concat([x1,x2],axis=-1)
x = layers.Dense(64, activation='relu')(x) #第二层
predictions = layers.Dense(10)(x) #第三层
model = tf.keras.Model(inputs=[inputs1,inputs2], outputs=predictions)
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
import numpy as np
data1 = np.random.random((1000, 32))
data2 = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.fit((data1,data2), labels, batch_size=32, epochs=5)
3.模型子类化 (重要!!!)
通过子类化tf.keras.Model和定义自己的前向传播模型来构建完全可定制的模型。
和eager execution模式相辅相成。
class MyModel(tf.keras.Model):
def __init__(self, num_classes=10):
super(MyModel, self).__init__(name='my_model')
self.num_classes = num_classes
# 定义自己需要的层
self.dense_1 = layers.Dense(32, activation='relu') #
self.dense_2 = layers.Dense(num_classes)
def call(self, inputs):
#定义前向传播
# 使用在 (in `__init__`)定义的层
x = self.dense_1(inputs)
x = self.dense_2(x)
return x
model = MyModel(num_classes=10)
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
import numpy as np
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
# Trains for 5 epochs.
model.fit(data, labels, batch_size=32, epochs=5)