• [技术干货] TensorFlow 张量操作的实现【转载】
    TensorFlow 张量操作基础张量是TensorFlow中的核心数据结构,可以理解为多维数组。张量的秩表示其维度数量,例如标量是0维张量,向量是1维张量,矩阵是2维张量。12345678910import tensorflow as tf # 创建标量scalar = tf.constant(5)# 创建向量vector = tf.constant([1, 2, 3])# 创建矩阵matrix = tf.constant([[1, 2], [3, 4]])# 创建3维张量tensor = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])张量创建方法TensorFlow提供了多种创建张量的方式,包括从Python列表、Numpy数组创建,以及生成特定模式的张量。12345678910111213141516171819# 从Python列表创建tensor_from_list = tf.convert_to_tensor([1, 2, 3]) # 从Numpy数组创建import numpy as nparray = np.array([[1, 2], [3, 4]])tensor_from_np = tf.convert_to_tensor(array) # 生成全零张量zeros = tf.zeros([2, 3]) # 生成全一张量ones = tf.ones([3, 2]) # 生成随机正态分布张量randn = tf.random.normal([2, 2], mean=0.0, stddev=1.0) # 生成均匀分布张量randu = tf.random.uniform([3, 3], minval=0, maxval=1)张量数学运算张量支持各种数学运算,包括逐元素运算和矩阵运算。12345678910111213141516171819202122a = tf.constant([[1, 2], [3, 4]])b = tf.constant([[5, 6], [7, 8]]) # 逐元素加法add = tf.add(a, b) # 逐元素乘法mul = tf.multiply(a, b) # 矩阵乘法matmul = tf.matmul(a, b) # 张量求和sum_all = tf.reduce_sum(a)sum_axis0 = tf.reduce_sum(a, axis=0)sum_axis1 = tf.reduce_sum(a, axis=1) # 张量平均值mean = tf.reduce_mean(a) # 张量最大值max_val = tf.reduce_max(a)张量形状操作改变张量形状是常见的操作,TensorFlow提供了多种形状操作方法。12345678910111213141516tensor = tf.constant([[1, 2], [3, 4], [5, 6]]) # 获取张量形状shape = tensor.shape # 改变张量形状reshaped = tf.reshape(tensor, [2, 3]) # 转置张量transposed = tf.transpose(tensor) # 扩展维度expanded = tf.expand_dims(tensor, axis=0) # 压缩维度squeezed = tf.squeeze(expanded)张量索引和切片TensorFlow支持类似Numpy的索引和切片操作。12345678910111213tensor = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # 获取单个元素elem = tensor[1, 2]  # 获取第2行第3列的元素 # 获取行切片row_slice = tensor[1:, :]  # 获取第2行及以后的所有行 # 获取列切片col_slice = tensor[:, 1]  # 获取第2列 # 使用步长切片strided_slice = tensor[::2, ::2]  # 每隔2个元素取一个张量广播机制TensorFlow支持广播机制,允许不同形状的张量进行运算。12345a = tf.constant([[1, 2, 3]])  # 形状(1,3)b = tf.constant([[4], [5], [6]])  # 形状(3,1) # 广播加法c = a + b  # 结果形状(3,3)张量聚合操作TensorFlow提供了多种聚合操作函数。12345678910111213tensor = tf.constant([[1, 2, 3], [4, 5, 6]]) # 沿轴0求和sum0 = tf.reduce_sum(tensor, axis=0)  # [5,7,9] # 沿轴1求最大值max1 = tf.reduce_max(tensor, axis=1)  # [3,6] # 计算逻辑与logical = tf.reduce_all(tensor > 3)  # False # 计算均值mean = tf.reduce_mean(tensor)  # 3.5张量拼接与分割TensorFlow支持张量的拼接和分割操作。123456789101112a = tf.constant([[1, 2], [3, 4]])b = tf.constant([[5, 6], [7, 8]]) # 沿轴0拼接concat0 = tf.concat([a, b], axis=0) # 沿轴1拼接concat1 = tf.concat([a, b], axis=1) # 张量分割split0 = tf.split(a, num_or_size_splits=2, axis=0)split1 = tf.split(a, num_or_size_splits=[1, 1], axis=1)张量排序操作TensorFlow提供了排序和top-k操作。12345678910tensor = tf.constant([[3, 1, 4], [1, 5, 9]]) # 排序sorted_values, sorted_indices = tf.sort(tensor, direction='DESCENDING') # argsortargsort = tf.argsort(tensor) # top-ktop_k_values, top_k_indices = tf.math.top_k(tensor, k=2)张量高级操作TensorFlow还提供了一些高级张量操作。1234567891011# 张量收集tensor = tf.constant([[0, 1, 2], [3, 4, 5]])indices = tf.constant([0, 1])gathered = tf.gather(tensor, indices)  # 收集第0行和第1行 # 张量分散updates = tf.constant([10, 20])scattered = tf.tensor_scatter_nd_update(tensor, [[0, 0], [1, 1]], updates) # 张量条件操作cond = tf.where(tensor > 3, tensor, tf.zeros_like(tensor))  # 大于3保留原值,否则设为0张量梯度计算TensorFlow支持自动微分,可以计算张量操作的梯度。1234x = tf.Variable(3.0)with tf.GradientTape() as tape:    y = x ** 2 + 2 * x + 1dy_dx = tape.gradient(y, x)  # 2x + 2 = 8 张量与Numpy互操作TensorFlow张量和Numpy数组可以方便地相互转换。123456# 张量转Numpy数组tensor = tf.constant([[1, 2], [3, 4]])numpy_array = tensor.numpy() # Numpy数组转张量new_tensor = tf.convert_to_tensor(numpy_array)
  • [认证交流] 【华为云开发者认证E级云架构学习分享】
    非常荣幸参加此次HCCDE 云架构的培训学习,E级的云架构的知识点比P提升了很多,如果说IE是重视理论知识,对华为云产品,最佳实践有个深入的了解的话,那么E覆盖的知识点从需求对接,开发前中后的注意事项,敏捷的流程,华为云高阶服务(CCE,CCI,EI,EG,FG,ROMA,CSE等),由浅入深,让学员学习到比IE更完整,更立体的知识体系,同时注重实操,利用RFS自动化购买云服务,搭建集群,考核了学员对json,对华为云各个产品考核的很深,需要同时注意微观的产品细节,宏观的架构及安全,掌握后,对目前正在交付的项目有非常大的帮助
  • [技术干货] 【TensorFlow】TensorFlow入门简介及代码实践
    介绍TensorFlow是一个开源的机器学习框架,是由Google开发的,用于构建和训练机器学习模型的工具库。它提供了丰富的功能和易于使用的接口,可用于各种机器学习任务,如图像识别、自然语言处理、推荐系统等。TensorFlow的基本概念包括:Tensor:是TensorFlow中的基本数据结构,可以理解为多维数组。它可以是一个标量(0维)、向量(1维)、矩阵(2维)或更高维的数组。计算图:TensorFlow使用计算图来描述计算过程,即将操作和数据组成的节点连接起来形成一个有向无环图。计算图定义了操作的顺序和依赖关系。变量:变量是在模型训练过程中需要被优化的参数。在TensorFlow中,通过tf.Variable()来定义变量。模型:模型是机器学习任务的核心部分,它由一系列操作和变量组成。在TensorFlow中,我们可以通过定义计算图来创建模型。一、TF使用场景TensorFlow的使用场景非常丰富,适用于各种机器学习任务。以下是一些常见的使用场景:图像识别:TensorFlow提供了一些预训练好的模型,如Inception、ResNet等,可以用于图像分类、目标检测和图像生成等任务。自然语言处理:TensorFlow提供了一些预训练好的模型,如BERT、GPT等,可以用于文本分类、情感分析和机器翻译等任务。推荐系统:TensorFlow可以用于构建推荐系统,通过分析用户的历史行为来预测用户可能喜欢的物品。强化学习:TensorFlow提供了一些强化学习的工具和算法,可以用于训练智能体从环境中学习并做出决策。二、与PyTorch对比TensorFlow和PyTorch是两个流行的深度学习框架。它们在设计哲学、编程模型和部分功能方面有一些差异。设计哲学:TensorFlow:TensorFlow是一个符号式编程框架,它使用静态计算图来定义和运行计算。用户首先定义计算图,然后在会话中执行计算。这种设计可以优化计算图,并提供高度的可移植性和分布式计算支持。PyTorch:PyTorch是一个动态图框架,它使用动态计算图来定义和运行计算。用户可以按照需要随时修改计算图,这使得调试和编写代码更加直观和灵活。编程模型:TensorFlow:TensorFlow使用基于声明式编程的API。用户需要显式地定义计算图,并通过会话执行计算,可以在训练和推理阶段使用不同的会话配置。PyTorch:PyTorch使用一种类似于Python的命令式编程风格,让用户可以直观地编写代码,调试和测试模型更加方便。用户可以直接在Python中使用标准的控制流程和变量操作。功能和生态系统:TensorFlow:TensorFlow具有较为完整的生态系统,提供了许多高级功能和工具,如TensorBoard可视化、分布式训练、模型部署等。它还有一个丰富的模型仓库(TensorFlow Hub)和模型优化工具(TensorFlow Lite)。PyTorch:PyTorch相对于TensorFlow而言功能相对简单,它更注重提供灵活性和易用性。PyTorch的生态系统也在不断扩大,但相对TensorFlow而言较为小众。TensorFlow在分布式训练和生产环境部署方面具有优势,适用于大规模的深度学习应用;而PyTorch在研究和实验中更受欢迎,更灵活易用。在选择使用哪个框架时,可以考虑项目需求和个人喜好。三、示例TensorFlow是一个用于机器学习和深度学习的开源框架,下面是TensorFlow的安装和使用教程:安装TensorFlow1)在Python环境中安装TensorFlow前,先确保已安装了Python和pip包管理工具。2)打开终端或命令提示符,运行以下命令安装TensorFlow:pip install tensorflow3)如果你使用的是GPU版本的TensorFlow,可以运行以下命令安装:pip install tensorflow-gpu导入TensorFlow 在Python脚本中,可以使用以下语句导入TensorFlow:import tensorflow as tf使用TensorFlow1)定义计算图 TensorFlow使用计算图来表示计算过程,首先需要定义一个计算图。例如,下面的代码定义了一个简单的计算图来加法运算:import tensorflow as tf # 定义计算图 a = tf.constant(2) b = tf.constant(3) c = tf.add(a, b)2)运行计算图 在TensorFlow中,需要创建一个会话(Session)来运行计算图。会话负责分配资源和执行计算。import tensorflow as tf # 定义计算图 a = tf.constant(2) b = tf.constant(3) c = tf.add(a, b) # 创建会话并运行计算图 with tf.Session() as sess: result = sess.run(c) print(result)3)TensorFlow中的变量和占位符 变量(Variable)用于存储模型的参数,占位符(Placeholder)用于接收外部输入数据。例如,下面的代码定义了一个变量和一个占位符:import tensorflow as tf # 定义变量和占位符 W = tf.Variable(tf.random_normal([2, 3])) X = tf.placeholder(tf.float32, [None, 2]) # 运行计算图 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) result = sess.run(W, feed_dict={X: [[1, 2], [3, 4]]}) print(result)4)TensorFlow中的模型训练 TensorFlow提供了各种优化算法和损失函数来训练模型。例如,下面的代码定义了一个简单的线性回归模型,并使用梯度下降算法进行训练:import tensorflow as tf # 定义模型 X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) W = tf.Variable(tf.random_normal([1])) b = tf.Variable(tf.random_normal([1])) pred = tf.add(tf.multiply(X, W), b) # 定义损失函数和优化算法 loss = tf.reduce_mean(tf.square(pred - Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss) # 训练模型 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(100): _, l = sess.run([optimizer, loss], feed_dict={X: [1, 2, 3, 4], Y: [2, 4, 6, 8]}) print(f'Epoch {epoch + 1}: loss = {l}') # 使用训练好的模型进行预测 result = sess.run(pred, feed_dict={X: [5, 6, 7, 8]}) print(result)
  • [技术干货] 【TensorFlow】TensorFlow入门介绍
    介绍TensorFlow是一个开源的机器学习框架,是由Google开发的,用于构建和训练机器学习模型的工具库。它提供了丰富的功能和易于使用的接口,可用于各种机器学习任务,如图像识别、自然语言处理、推荐系统等。TensorFlow的基本概念包括:Tensor:是TensorFlow中的基本数据结构,可以理解为多维数组。它可以是一个标量(0维)、向量(1维)、矩阵(2维)或更高维的数组。计算图:TensorFlow使用计算图来描述计算过程,即将操作和数据组成的节点连接起来形成一个有向无环图。计算图定义了操作的顺序和依赖关系。变量:变量是在模型训练过程中需要被优化的参数。在TensorFlow中,通过tf.Variable()来定义变量。模型:模型是机器学习任务的核心部分,它由一系列操作和变量组成。在TensorFlow中,我们可以通过定义计算图来创建模型。一、TF使用场景TensorFlow的使用场景非常丰富,适用于各种机器学习任务。以下是一些常见的使用场景:图像识别:TensorFlow提供了一些预训练好的模型,如Inception、ResNet等,可以用于图像分类、目标检测和图像生成等任务。自然语言处理:TensorFlow提供了一些预训练好的模型,如BERT、GPT等,可以用于文本分类、情感分析和机器翻译等任务。推荐系统:TensorFlow可以用于构建推荐系统,通过分析用户的历史行为来预测用户可能喜欢的物品。强化学习:TensorFlow提供了一些强化学习的工具和算法,可以用于训练智能体从环境中学习并做出决策。二、与PyTorch对比TensorFlow和PyTorch是两个流行的深度学习框架。它们在设计哲学、编程模型和部分功能方面有一些差异。设计哲学:TensorFlow:TensorFlow是一个符号式编程框架,它使用静态计算图来定义和运行计算。用户首先定义计算图,然后在会话中执行计算。这种设计可以优化计算图,并提供高度的可移植性和分布式计算支持。PyTorch:PyTorch是一个动态图框架,它使用动态计算图来定义和运行计算。用户可以按照需要随时修改计算图,这使得调试和编写代码更加直观和灵活。编程模型:TensorFlow:TensorFlow使用基于声明式编程的API。用户需要显式地定义计算图,并通过会话执行计算,可以在训练和推理阶段使用不同的会话配置。PyTorch:PyTorch使用一种类似于Python的命令式编程风格,让用户可以直观地编写代码,调试和测试模型更加方便。用户可以直接在Python中使用标准的控制流程和变量操作。功能和生态系统:TensorFlow:TensorFlow具有较为完整的生态系统,提供了许多高级功能和工具,如TensorBoard可视化、分布式训练、模型部署等。它还有一个丰富的模型仓库(TensorFlow Hub)和模型优化工具(TensorFlow Lite)。PyTorch:PyTorch相对于TensorFlow而言功能相对简单,它更注重提供灵活性和易用性。PyTorch的生态系统也在不断扩大,但相对TensorFlow而言较为小众。TensorFlow在分布式训练和生产环境部署方面具有优势,适用于大规模的深度学习应用;而PyTorch在研究和实验中更受欢迎,更灵活易用。在选择使用哪个框架时,可以考虑项目需求和个人喜好。三、示例TensorFlow是一个用于机器学习和深度学习的开源框架,下面是TensorFlow的安装和使用教程:安装TensorFlow1)在Python环境中安装TensorFlow前,先确保已安装了Python和pip包管理工具。2)打开终端或命令提示符,运行以下命令安装TensorFlow:pip install tensorflow3)如果你使用的是GPU版本的TensorFlow,可以运行以下命令安装:pip install tensorflow-gpu导入TensorFlow 在Python脚本中,可以使用以下语句导入TensorFlow:import tensorflow as tf使用TensorFlow1)定义计算图 TensorFlow使用计算图来表示计算过程,首先需要定义一个计算图。例如,下面的代码定义了一个简单的计算图来加法运算:import tensorflow as tf # 定义计算图 a = tf.constant(2) b = tf.constant(3) c = tf.add(a, b)2)运行计算图 在TensorFlow中,需要创建一个会话(Session)来运行计算图。会话负责分配资源和执行计算。import tensorflow as tf # 定义计算图 a = tf.constant(2) b = tf.constant(3) c = tf.add(a, b) # 创建会话并运行计算图 with tf.Session() as sess: result = sess.run(c) print(result)3)TensorFlow中的变量和占位符 变量(Variable)用于存储模型的参数,占位符(Placeholder)用于接收外部输入数据。例如,下面的代码定义了一个变量和一个占位符:import tensorflow as tf # 定义变量和占位符 W = tf.Variable(tf.random_normal([2, 3])) X = tf.placeholder(tf.float32, [None, 2]) # 运行计算图 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) result = sess.run(W, feed_dict={X: [[1, 2], [3, 4]]}) print(result)4)TensorFlow中的模型训练 TensorFlow提供了各种优化算法和损失函数来训练模型。例如,下面的代码定义了一个简单的线性回归模型,并使用梯度下降算法进行训练:import tensorflow as tf # 定义模型 X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) W = tf.Variable(tf.random_normal([1])) b = tf.Variable(tf.random_normal([1])) pred = tf.add(tf.multiply(X, W), b) # 定义损失函数和优化算法 loss = tf.reduce_mean(tf.square(pred - Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss) # 训练模型 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(100): _, l = sess.run([optimizer, loss], feed_dict={X: [1, 2, 3, 4], Y: [2, 4, 6, 8]}) print(f'Epoch {epoch + 1}: loss = {l}') # 使用训练好的模型进行预测 result = sess.run(pred, feed_dict={X: [5, 6, 7, 8]}) print(result)
  • [课程学习] Tensor学习总结
    Generator的使用:直接读取图像数据:train_generator=ImageDataGenerator(rescale=1./255)test_generator=ImageDataGenerator(rescale=1./255)train_data=train_generator.flow_from_directory(    "./cats_and_dogs_filtered/train",batch_size=20,target_size=(64,64),shuffle=True,class_mode='binary')test_data=test_generator.flow_from_directory(    "./cats_and_dogs_filtered/validation",batch_size=1000,target_size=(64,64),shuffle=False,class_mode='binary')创建模型:model=tf.keras.models.Sequential([    tf.keras.layers.Conv2D(64,3,activation='relu',input_shape=(64,64,3)),    tf.keras.layers.MaxPooling2D(3,3),    tf.keras.layers.Conv2D(128,3,activation='relu'),    tf.keras.layers.MaxPooling2D(3,3),    tf.keras.layers.Flatten(),    tf.keras.layers.Dense(512,activation='relu',kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.01)),    tf.keras.layers.Dense(256,activation='relu',kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.01)),    tf.keras.layers.Dense(1,activation='sigmoid',kernel_initializer='random_normal',kernel_regularizer=tf.keras.regularizers.l2(0.01))])model.summary()model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-5),              loss=tf.keras.losses.BinaryCrossentropy(),              metrics=["Accuracy"])model.fit_generator(train_data,steps_per_epoch=100,epochs=200,validation_data=test_data,validation_steps=1,)读取mnist数据:x_test , y_test = loadlocal_mnist(                images_path='D:\\Python\\MNIST_data\\t10k-images.idx3-ubyte',                 labels_path='D:\\Python\\MNIST_data\\t10k-labels.idx1-ubyte')x_train, y_train = loadlocal_mnist(                images_path='D:\\Python\\MNIST_data\\train-images.idx3-ubyte',                 labels_path='D:\\Python\\MNIST_data\\train-labels.idx1-ubyte')
  • atc转换错误
    按照流程装了运行环境,报错如图
  • [技术干货] 详解TensorFlow训练网络两种方式(转载)
    TensorFlow训练网络有两种方式,一种是基于tensor(array),另外一种是迭代器两种方式区别是:第一种是要加载全部数据形成一个tensor,然后调用model.fit()然后指定参数batch_size进行将所有数据进行分批训练第二种是自己先将数据分批形成一个迭代器,然后遍历这个迭代器,分别训练每个批次的数据方式一:通过迭代器1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283IMAGE_SIZE = 1000 # step1:加载数据集(train_images, train_labels), (val_images, val_labels) = tf.keras.datasets.mnist.load_data() # step2:将图像归一化train_images, val_images = train_images / 255.0, val_images / 255.0 # step3:设置训练集大小train_images = train_images[:IMAGE_SIZE]val_images = val_images[:IMAGE_SIZE]train_labels = train_labels[:IMAGE_SIZE]val_labels = val_labels[:IMAGE_SIZE] # step4:将图像的维度变为(IMAGE_SIZE,28,28,1)train_images = tf.expand_dims(train_images, axis=3)val_images = tf.expand_dims(val_images, axis=3) # step5:将图像的尺寸变为(32,32)train_images = tf.image.resize(train_images, [32, 32])val_images = tf.image.resize(val_images, [32, 32]) # step6:将数据变为迭代器train_loader = tf.data.Dataset.from_tensor_slices((train_images, train_labels)).batch(32)val_loader = tf.data.Dataset.from_tensor_slices((val_images, val_labels)).batch(IMAGE_SIZE) # step5:导入模型model = LeNet5() # 让模型知道输入数据的形式model.build(input_shape=(1, 32, 32, 1)) # 结局Output Shape为 multiplemodel.call(Input(shape=(32, 32, 1))) # step6:编译模型model.compile(optimizer='adam',              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),              metrics=['accuracy']) # 权重保存路径checkpoint_path = "./weight/cp.ckpt" # 回调函数,用户保存权重save_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,                                                   save_best_only=True,                                                   save_weights_only=True,                                                   monitor='val_loss',                                                   verbose=0) EPOCHS = 11 for epoch in range(1, EPOCHS):    # 每个批次训练集误差    train_epoch_loss_avg = tf.keras.metrics.Mean()    # 每个批次训练集精度    train_epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()    # 每个批次验证集误差    val_epoch_loss_avg = tf.keras.metrics.Mean()    # 每个批次验证集精度    val_epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()     for x, y in train_loader:        history = model.fit(x,                            y,                            validation_data=val_loader,                            callbacks=[save_callback],                            verbose=0)         # 更新误差,保留上次        train_epoch_loss_avg.update_state(history.history['loss'][0])        # 更新精度,保留上次        train_epoch_accuracy.update_state(y, model(x, training=True))         val_epoch_loss_avg.update_state(history.history['val_loss'][0])        val_epoch_accuracy.update_state(next(iter(val_loader))[1], model(next(iter(val_loader))[0], training=True))     # 使用.result()计算每个批次的误差和精度结果    print("Epoch {:d}: trainLoss: {:.3f}, trainAccuracy: {:.3%} valLoss: {:.3f}, valAccuracy: {:.3%}".format(epoch,                                                                                                             train_epoch_loss_avg.result(),                                                                                                             train_epoch_accuracy.result(),                                                                                                             val_epoch_loss_avg.result(),                                                                                                             val_epoch_accuracy.result()))方式二:适用model.fit()进行分批训练123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import model_sequential (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() # step2:将图像归一化train_images, test_images = train_images / 255.0, test_images / 255.0 # step3:将图像的维度变为(60000,28,28,1)train_images = tf.expand_dims(train_images, axis=3)test_images = tf.expand_dims(test_images, axis=3) # step4:将图像尺寸改为(60000,32,32,1)train_images = tf.image.resize(train_images, [32, 32])test_images = tf.image.resize(test_images, [32, 32]) # step5:导入模型# history = LeNet5()history = model_sequential.LeNet() # 让模型知道输入数据的形式history.build(input_shape=(1, 32, 32, 1))# history(tf.zeros([1, 32, 32, 1])) # 结局Output Shape为 multiplehistory.call(Input(shape=(32, 32, 1)))history.summary() # step6:编译模型history.compile(optimizer='adam',                loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),                metrics=['accuracy']) # 权重保存路径checkpoint_path = "./weight/cp.ckpt" # 回调函数,用户保存权重save_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,                                                   save_best_only=True,                                                   save_weights_only=True,                                                   monitor='val_loss',                                                   verbose=1)# step7:训练模型history = history.fit(train_images,                      train_labels,                      epochs=10,                      batch_size=32,                      validation_data=(test_images, test_labels),                      callbacks=[save_callback])
  • [资产园地] 图像分类—Res2Net50
    描述适用的案例图像分类—ResNeSt理论与实践适用的数据集flowers-5-manifest(图像分类)flowers-5-raw-split(图像分类)10类常见美食生活垃圾分类花卉分类猫狗分类23类美食4类美食OBS原始数据集格式仅支持切分的情况your_local_path/flowers |- train --------------- 训练集 |- classA ------------- 类别A |- A_0.jpg |- A_1.jpg |- ... |- A_n.jpg |- classB ------------ 类别B |- B_0.jpg |- B_1.jpg |- ... |- B_n.jpg |- classC --------------- 类别C |- C_0.jpg |- C_1.jpg |- ... |- C_n.jpg 以此类推 ... |- eval --------------- 测试集 |- classA ------------- 类别A |- A_0.jpg |- A_1.jpg |- ... |- A_n.jpg |- classB ------------ 类别B |- B_0.jpg |- B_1.jpg |- ... |- B_n.jpg |- classC --------------- 类别C |- C_0.jpg |- C_1.jpg |- ... |- C_n.jpg 以此类推 ...概述MobileNetsV2是基于一个流线型的架构,它使用深度可分离的卷积来构建轻量级的深层神经网,此模型基于 MobileNetV2: Inverted Residuals and Linear Bottlenecks 中提出的模型结构实现。可以用图像分类任务,比如猫狗分类、花卉分类等等。用户提供一系列带有标注的数据集,该算法会载入在ImageNet-1000上的预训练模型,在用户数据集上做迁移学习。训练后生成的模型可直接在ModelArts平台部署为在线服务或批量服务,同时支持使用CPU、GPU或Ascend 310进行推理。训练算法基本信息适用场景:图像分类支持的框架引擎:Tensorflow-1.13.1-python3.6-horovod算法输入:ModelArts数据管理平台发布的数据集(数据集必须设置“训练验证比例”),建议用户以8:2或9:1的比例进行切分,即“训练验证比例”设置为0.8或0.9。在ImageNet上的预训练模型;训练参数说明名称默认值类型是否必填是否可修改描述task_typeimage_classification_v2string是否适用场景。model_namemobilenet_v2string是否模型名称。do_trainTruebool是否是否做训练,默认训练。do_eval_along_trainTruebool是否是否边训练边验证,默认值为True,表示边训练边验证。variable_updatehorovodstring是否参数更新方式,默认horovod。learning_rate_strategy0.002string是是训练的学习率策略。"10:0.001,20:0.0001"代表0-10个epoch学习率0.001,10-20epoch学习率0.0001。如果不指定epoch, 会根据验证精度情况自动调整学习率,并当精度没有明显提升时,训练停止。batch_size64int是是每步训练的图片数量(单卡)。eval_batch_size64int是是每步验证的图片数量(单卡)。evaluate_every_n_epochs1.0float是是每训练n个epoch做一次验证。save_model_secs60int是是保存模型的频率(单位:s)。save_summary_steps10int是是保存summary的频率(单位:步)。log_every_n_steps10int是是打印日志的频率(单位:步)。do_data_cleaningTruebool否是是否做数据清洗,数据格式异常会导致训练失败,建议开启,保证训练稳定性。数据量过大时,数据清洗可能耗时较久,可自行线下清洗(支持BMP、JPEG、PNG格式,RGB三通道)。建议用JPEG格式数据。默认开启,设置为False表示关闭。use_fp16Falsebool否否是否使用混合精度, 混合精度可以加速训练,但是可能会造成一点精度损失,默认关闭。xla_compileTruebool否是是否开启xla编译,加速训练,默认启用,设置为False表示关闭。data_formatNHWCstring否是输入数据类型,NHWC表示channel在最后,NCHW表示channel在最前,默认值NHWC,暂不支持NCHW。best_modelTruebool否是是否在训练过程中保存并使用精度最高的模型,而不是最新的模型。默认值True,保存最优模型。在一定误差范围内,最优模型会保存最新的高精度模型。设置为False表示关闭。训练输出文件训练完成后的输出文件如下: |- om |- model |- index |- customize_service_d310.py |- model |- variables |- variables.data-00000-of-00001 |- variables.index |- customize_service.py |- index |- config.json |- saved_model.pb |- frozen_graph |- insert_op_conf.cfg |- model.pb |- checkpoint |- model.ckpt-xxx |- ... |- best_checkpoint |- best_model.ckpt-xxx |- ... |- events... |- graph.pbtxtAscend 310推理模型转换转换模板:TF-FrozenGraph-To-Ascend-C32转换输入目录:选择“训练输出目录”中的frozen_graph转换输出目录:选择“训练输出目录”中的om/model输入张量形状:images:1,224,224,3输入数据格式:NHWC转换输出节点:logits:0其他参数均使用默认值。模型导入从模板中选择:ARM-Ascend模板模型目录:选择“训练输出目录”中的om/model输入输出模式:预置图像处理模式GPU/CPU推理推理配置文件“model/config.json”,默认使用CPU推理镜像(runtime:tf1.xx-python3.x-cpu)。若使用GPU推理,导入模型之前需修改“model/config.json”文件,将runtime字段修改为“tf1.xx-python3.x-gpu”。交付交付方式华为云ModelArts交付区域华北-北京一、华北-北京四、华东-上海一、华南-广州、中国-香港
  • [资产园地] 图像分类-MobileNet_v2
    描述适用的案例图像分类—ResNeSt理论与实践适用的数据集flowers-5-manifest(图像分类)flowers-5-raw-split(图像分类)10类常见美食生活垃圾分类花卉分类猫狗分类23类美食4类美食OBS原始数据集格式仅支持切分的情况your_local_path/flowers |- train --------------- 训练集 |- classA ------------- 类别A |- A_0.jpg |- A_1.jpg |- ... |- A_n.jpg |- classB ------------ 类别B |- B_0.jpg |- B_1.jpg |- ... |- B_n.jpg |- classC --------------- 类别C |- C_0.jpg |- C_1.jpg |- ... |- C_n.jpg 以此类推 ... |- eval --------------- 测试集 |- classA ------------- 类别A |- A_0.jpg |- A_1.jpg |- ... |- A_n.jpg |- classB ------------ 类别B |- B_0.jpg |- B_1.jpg |- ... |- B_n.jpg |- classC --------------- 类别C |- C_0.jpg |- C_1.jpg |- ... |- C_n.jpg 以此类推 ...概述MobileNetsV2是基于一个流线型的架构,它使用深度可分离的卷积来构建轻量级的深层神经网,此模型基于 MobileNetV2: Inverted Residuals and Linear Bottlenecks 中提出的模型结构实现。可以用图像分类任务,比如猫狗分类、花卉分类等等。用户提供一系列带有标注的数据集,该算法会载入在ImageNet-1000上的预训练模型,在用户数据集上做迁移学习。训练后生成的模型可直接在ModelArts平台部署为在线服务或批量服务,同时支持使用CPU、GPU或Ascend 310进行推理。训练算法基本信息适用场景:图像分类支持的框架引擎:Tensorflow-1.13.1-python3.6-horovod算法输入:ModelArts数据管理平台发布的数据集(数据集必须设置“训练验证比例”),建议用户以8:2或9:1的比例进行切分,即“训练验证比例”设置为0.8或0.9。在ImageNet上的预训练模型;训练参数说明名称默认值类型是否必填是否可修改描述task_typeimage_classification_v2string是否适用场景。model_namemobilenet_v2string是否模型名称。do_trainTruebool是否是否做训练,默认训练。do_eval_along_trainTruebool是否是否边训练边验证,默认值为True,表示边训练边验证。variable_updatehorovodstring是否参数更新方式,默认horovod。learning_rate_strategy0.002string是是训练的学习率策略。"10:0.001,20:0.0001"代表0-10个epoch学习率0.001,10-20epoch学习率0.0001。如果不指定epoch, 会根据验证精度情况自动调整学习率,并当精度没有明显提升时,训练停止。batch_size64int是是每步训练的图片数量(单卡)。eval_batch_size64int是是每步验证的图片数量(单卡)。evaluate_every_n_epochs1.0float是是每训练n个epoch做一次验证。save_model_secs60int是是保存模型的频率(单位:s)。save_summary_steps10int是是保存summary的频率(单位:步)。log_every_n_steps10int是是打印日志的频率(单位:步)。do_data_cleaningTruebool否是是否做数据清洗,数据格式异常会导致训练失败,建议开启,保证训练稳定性。数据量过大时,数据清洗可能耗时较久,可自行线下清洗(支持BMP、JPEG、PNG格式,RGB三通道)。建议用JPEG格式数据。默认开启,设置为False表示关闭。use_fp16Falsebool否否是否使用混合精度, 混合精度可以加速训练,但是可能会造成一点精度损失,默认关闭。xla_compileTruebool否是是否开启xla编译,加速训练,默认启用,设置为False表示关闭。data_formatNHWCstring否是输入数据类型,NHWC表示channel在最后,NCHW表示channel在最前,默认值NHWC,暂不支持NCHW。best_modelTruebool否是是否在训练过程中保存并使用精度最高的模型,而不是最新的模型。默认值True,保存最优模型。在一定误差范围内,最优模型会保存最新的高精度模型。设置为False表示关闭。训练输出文件训练完成后的输出文件如下: |- om |- model |- index |- customize_service_d310.py |- model |- variables |- variables.data-00000-of-00001 |- variables.index |- customize_service.py |- index |- config.json |- saved_model.pb |- frozen_graph |- insert_op_conf.cfg |- model.pb |- checkpoint |- model.ckpt-xxx |- ... |- best_checkpoint |- best_model.ckpt-xxx |- ... |- events... |- graph.pbtxtAscend 310推理模型转换转换模板:TF-FrozenGraph-To-Ascend-C32转换输入目录:选择“训练输出目录”中的frozen_graph转换输出目录:选择“训练输出目录”中的om/model输入张量形状:images:1,224,224,3输入数据格式:NHWC转换输出节点:logits:0其他参数均使用默认值。模型导入从模板中选择:ARM-Ascend模板模型目录:选择“训练输出目录”中的om/model输入输出模式:预置图像处理模式GPU/CPU推理推理配置文件“model/config.json”,默认使用CPU推理镜像(runtime:tf1.xx-python3.x-cpu)。若使用GPU推理,导入模型之前需修改“model/config.json”文件,将runtime字段修改为“tf1.xx-python3.x-gpu”。交付交付方式华为云ModelArts交付区域华北-北京一、华北-北京四、华东-上海一、华南-广州、中国-香港
  • [其他] Tensorflow多节点作业下载数据到/cache显示No space left解决办法
    问题现象创建训练作业,Tensorflow多节点作业下载数据到/cache显示:“No space left”。原因分析TensorFlow多节点任务会启动parameter server(简称ps)和worker两种角色,ps和worker会被调度到相同的机器上。由于训练数据对于ps没有用,因此在代码中ps相关的逻辑不需要下载训练数据。​如果ps也下载数据到“/cache”实际下载的数据会翻倍。​例如只下载了2.5TB的数据,程序就显示空间不够而失败,因为/cache只有4TB的可用空间。处理方法在使用Tensorflow多节点作业下载数据时,正确的下载逻辑如下:import argparse parser = argparse.ArgumentParser() parser.add_argument("--job_name", type=str, default="") args = parser.parse_known_args() if args[0].job_name != "ps": copy..............................
  • [其他] 使用TensorFlow2对识别验证码
    验证码是根据随机字符生成一幅图片,然后在图片中加入干扰象素,用户必须手动填入,防止有人利用机器人自动批量注册、灌水、发垃圾广告等等 。数据集来源:https://www.kaggle.com/fournierp/captcha-version-2-images图片是5个字母的单词,可以包含数字。这些图像应用了噪声(模糊和一条线)。它们是200 x 50 PNG。我们的任务是尝试制作光学字符识别算法的模型。在数据集中存在的验证码png图片,对应的标签就是图片的名字import os import numpy as np import pandas as pd import cv2 import matplotlib.pyplot as plt import seaborn as sns # imgaug 图片数据增强 import imgaug.augmenters as iaa import tensorflow as tf # Conv2D MaxPooling2D Dropout Flatten Dense BN GAP from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Layer, BatchNormalization, GlobalAveragePooling2D from tensorflow.keras.optimizers import Adam from tensorflow.keras import Model, Input from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau # 图片处理器 from tensorflow.keras.preprocessing.image import ImageDataGenerator import plotly.express as px import plotly.graph_objects as go import plotly.offline as pyo pyo.init_notebook_mode()对数据进行一个简单的分析,统计图像中大约出现了什么样的符号。# 数据路径 DIR = '../input/captcha-version-2-images/samples/samples' # 存储验证码的标签 captcha_list = [] characters = {} for captcha in os.listdir(DIR): captcha_list.append(captcha) # 每张验证码的captcha_code captcha_code = captcha.split(".")[0] for i in captcha_code: # 遍历captcha_code characters[i] = characters.get(i, 0) +1 symbols = list(characters.keys()) len_symbols = len(symbols) print(f'图像中只使用了{len_symbols}符号') plt.bar(*zip(*characters.items())) plt.title('Frequency of symbols') plt.show()如何提取图像的数据建立X,y??# 如何提取图像 建立 model X 的shape 1070 * 50 * 200 * 1 # y的shape 5 * 1070 * 19 for i, captcha in enumerate(captcha_list): captcha_code = captcha.split('.')[0] # cv2.IMREAD_GRAYSCALE 灰度图 captcha_cv2 = cv2.imread(os.path.join(DIR, captcha),cv2.IMREAD_GRAYSCALE) # 缩放 captcha_cv2 = captcha_cv2 / 255.0 # print(captcha_cv2.shape) (50, 200) # 将captcha_cv2的(50, 200) 切换成(50, 200, 1) captcha_cv2 = np.reshape(captcha_cv2, img_shape) # (5,19) targs = np.zeros((len_captcha, len_symbols)) for a, b in enumerate(captcha_code): targs[a, symbols.index(b)] = 1 X[i] = captcha_cv2 y[:, i] = targs print("shape of X:", X.shape) print("shape of y:", y.shape)输出如下print("shape of X:", X.shape) print("shape of y:", y.shape)通过Numpy中random 随机选择数据,划分训练集和测试集# 生成随机数 from numpy.random import default_rng rng = default_rng(seed=1) test_numbers = rng.choice(1070, size=int(1070*0.3), replace=False) X_test = X[test_numbers] X_full = np.delete(X, test_numbers,0) y_test = y[:,test_numbers] y_full = np.delete(y, test_numbers,1) val_numbers = rng.choice(int(1070*0.7), size=int(1070*0.3), replace=False) X_val = X_full[val_numbers] X_train = np.delete(X_full, val_numbers,0) y_val = y_full[:,val_numbers] y_train = np.delete(y_full, val_numbers,1)在此验证码数据中,容易出现过拟合的现象,你可能会想到添加更多的新数据、 添加正则项等, 但这里使用数据增强的方法,特别是对于机器视觉的任务,数据增强技术尤为重要。常用的数据增强操作:imgaug库。imgaug是提供了各种图像增强操作的python库 https://github.com/aleju/imgaug。imgaug几乎包含了所有主流的数据增强的图像处理操作, 增强方法详见github# Sequential(C, R) 尺寸增加了5倍, # 选取一系列子增强器C作用于每张图片的位置,第二个参数表示是否对每个batch的图片应用不同顺序的Augmenter list # rotate=(-8, 8) 旋转 # iaa.CropAndPad 截取(crop)或者填充(pad),填充时,被填充区域为黑色。 # px: 想要crop(negative values)的或者pad(positive values)的像素点。 # (top, right, bottom, left) # 当pad_mode=constant的时候选择填充的值 aug =iaa.Sequential([iaa.CropAndPad( px=((0, 10), (0, 35), (0, 10), (0, 35)), pad_mode=['edge'], pad_cval=1 ),iaa.Rotate(rotate=(-8,8))]) X_aug_train = None y_aug_train = y_train for i in range(40): X_aug = aug(images = X_train) if X_aug_train is not None: X_aug_train = np.concatenate([X_aug_train, X_aug], axis = 0) y_aug_train = np.concatenate([y_aug_train, y_train], axis = 1) else: X_aug_train = X_aug让我们看看一些数据增强的训练图像。fig, ax = plt.subplots(nrows=2, ncols =5, figsize = (16,16)) for i in range(10): index = np.random.randint(X_aug_train.shape[0]) ax[i//5][i%5].imshow(X_aug_train[index],cmap='gray')这次使用函数式API创建模型,函数式API是创建模型的另一种方式,它具有更多的灵活性,包括创建更为复杂的模型。需要定义inputs和outputs#函数式API模型创建 captcha = Input(shape=(50,200,channels)) x = Conv2D(32, (5,5),padding='valid',activation='relu')(captcha) x = MaxPooling2D((2,2),padding='same')(x) x = Conv2D(64, (3,3),padding='same',activation='relu')(x) x = MaxPooling2D((2,2),padding='same')(x) x = Conv2D(128, (3,3),padding='same',activation='relu')(x) maxpool = MaxPooling2D((2,2),padding='same')(x) outputs = [] for i in range(5): x = Conv2D(256, (3,3),padding='same',activation='relu')(maxpool) x = MaxPooling2D((2,2),padding='same')(x) x = Flatten()(x) x = Dropout(0.5)(x) x = BatchNormalization()(x) x = Dense(64, activation='relu')(x) x = Dropout(0.5)(x) x = BatchNormalization()(x) x = Dense(len_symbols , activation='softmax' , name=f'char_{i+1}')(x) outputs.append(x) model = Model(inputs = captcha , outputs=outputs) # ReduceLROnPlateau更新学习率 reduce_lr = ReduceLROnPlateau(patience =3, factor = 0.5,verbose = 1) model.compile(loss='categorical_crossentropy', optimizer=Adam(learning_rate=0.0005), metrics=["accuracy"]) # EarlyStopping用于提前停止训练的callbacks。具体地,可以达到当训练集上的loss不在减小 earlystopping = EarlyStopping(monitor ="val_loss", mode ="min", patience = 10, min_delta = 1e-4, restore_best_weights = True) history = model.fit(X_train, [y_train[i] for i in range(5)], batch_size=32, epochs=30, verbose=1, validation_data = (X_val, [y_val[i] for i in range(5)]), callbacks =[earlystopping,reduce_lr])下面对model进行一个测试和评估。score = model.evaluate(X_test,[y_test[0], y_test[1], y_test[2], y_test[3], y_test[4]],verbose=1) metrics = ['loss','char_1_loss', 'char_2_loss', 'char_3_loss', 'char_4_loss', 'char_5_loss', 'char_1_acc', 'char_2_acc', 'char_3_acc', 'char_4_acc', 'char_5_acc'] for i,j in zip(metrics, score): print(f'{i}: {j}')具体输出如下:11/11 [==============================] - 0s 11ms/step - loss: 0.7246 - char_1_loss: 0.0682 - char_2_loss: 0.1066 - char_3_loss: 0.2730 - char_4_loss: 0.2636 - char_5_loss: 0.0132 - char_1_accuracy: 0.9844 - char_2_accuracy: 0.9657 - char_3_accuracy: 0.9408 - char_4_accuracy: 0.9626 - char_5_accuracy: 0.9938 loss: 0.7246273756027222 char_1_loss: 0.06818050146102905 char_2_loss: 0.10664034634828568 char_3_loss: 0.27299806475639343 char_4_loss: 0.26359987258911133 char_5_loss: 0.013208594173192978 char_1_acc: 0.9844236969947815 char_2_acc: 0.9657320976257324 char_3_acc: 0.940809965133667 char_4_acc: 0.9626168012619019 char_5_acc: 0.9937694668769836字母1到字母5的精确值都大于绘制loss和scoremetrics_df = pd.DataFrame(history.history) columns = [col for col in metrics_df.columns if 'loss' in col and len(col)>8] fig = px.line(metrics_df, y = columns) fig.show()plt.figure(figsize=(15,8)) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'val'], loc='upper right',prop={'size': 10}) plt.show()# 预测数据 def predict(captcha): captcha = np.reshape(captcha , (1, 50,200,channels)) result = model.predict(captcha) result = np.reshape(result ,(5,len_symbols)) # 取出最大预测中的输出 label = ''.join([symbols[np.argmax(i)] for i in result]) return label predict(X_test[2]) # 25277下面预测所有的数据actual_pred = [] for i in range(X_test.shape[0]): actual = ''.join([symbols[i] for i in (np.argmax(y_test[:, i],axis=1))]) pred = predict(X_test[i]) actual_pred.append((actual, pred)) print(actal_pred[:10])输出如下[('n4b4m', 'n4b4m'), ('42nxy', '42nxy'), ('25257', '25277'), ('cewnm', 'cewnm'), ('w46ep', 'w46ep'), ('cdcb3', 'edcb3'), ('8gf7n', '8gf7n'), ('nny5e', 'nny5e'), ('gm2c2', 'gm2c2'), ('g7fmc', 'g7fmc')]sameCount = 0 diffCount = 0 letterDiff = {i:0 for i in range(5)} incorrectness = {i:0 for i in range(1,6)} for real, pred in actual_pred: # 预测和输出相同 if real == pred: sameCount += 1 else: # 失败 diffCount += 1 # 遍历 incorrectnessPoint = 0 for i in range(5): if real[i] != pred[i]: letterDiff[i] += 1 incorrectnessPoint += 1 incorrectness[incorrectnessPoint] += 1 x = ['True predicted', 'False predicted'] y = [sameCount, diffCount] fig = go.Figure(data=[go.Bar(x = x, y = y)]) fig.show()在预测数据中,一共有287个数据预测正确。在这里,我们可以看到出现错误到底是哪一个index。x1 = ["Character " + str(x) for x in range(1, 6)] fig = go.Figure(data=[go.Bar(x = x1, y = list(letterDiff.values()))]) fig.show()为了计算每个单词的错误数,绘制相关的条形图。x2 = [str(x) + " incorrect" for x in incorrectness.keys()] y2 = list(incorrectness.values()) fig = go.Figure(data=[go.Bar(x = x2, y = y2)]) fig.show()下面绘制错误的验证码图像,并标准正确和错误的区别。fig, ax = plt.subplots(nrows = 8, ncols=4,figsize = (16,20)) count = 0 for i, (actual , pred) in enumerate(actual_pred): if actual != pred: img = X_test[i] try: ax[count//4][count%4].imshow(img, cmap = 'gray') ax[count//4][count%4].title.set_text(pred + ' - ' + actual) count += 1 except: pass
  • [其他] 使用TensorFlow2对阿拉伯语手写字符数据集进行识别
    使用 TensorFlow (Keras API) 实现一个用于多分类任务的深度学习模型,该任务需要对阿拉伯语手写字符数据集进行识别。数据集下载地址:https://www.kaggle.com/mloey1/ahcd1数据集介绍该数据集由 60 名参与者书写的16,800 个字符组成,年龄范围在 19 至 40 岁之间,90% 的参与者是右手。每个参与者在两种形式上写下每个字符(从“alef”到“yeh”)十次,如图 7(a)和 7(b)所示。表格以 300 dpi 的分辨率扫描。使用 Matlab 2016a 自动分割每个块以确定每个块的坐标。该数据库分为两组:训练集(每类 13,440 个字符到 480 个图像)和测试集(每类 3,360 个字符到 120 个图像)。数据标签为1到28个类别。在这里,所有数据集都是CSV文件,表示图像像素值及其相应标签,并没有提供对应的图片数据。导入模块import numpy as np import pandas as pd #允许对dataframe使用display() from IPython.display import display # 导入读取和处理图像所需的库 import csv from PIL import Image from scipy.ndimage import rotate读取数据# 训练数据images letters_training_images_file_path = "../input/ahcd1/csvTrainImages 13440x1024.csv" # 训练数据labels letters_training_labels_file_path = "../input/ahcd1/csvTrainLabel 13440x1.csv" # 测试数据images和labels letters_testing_images_file_path = "../input/ahcd1/csvTestImages 3360x1024.csv" letters_testing_labels_file_path = "../input/ahcd1/csvTestLabel 3360x1.csv" # 加载数据 training_letters_images = pd.read_csv(letters_training_images_file_path, header=None) training_letters_labels = pd.read_csv(letters_training_labels_file_path, header=None) testing_letters_images = pd.read_csv(letters_testing_images_file_path, header=None) testing_letters_labels = pd.read_csv(letters_testing_labels_file_path, header=None) print("%d个32x32像素的训练阿拉伯字母图像。" %training_letters_images.shape[0]) print("%d个32x32像素的测试阿拉伯字母图像。" %testing_letters_images.shape[0]) training_letters_images.head()13440个32x32像素的训练阿拉伯字母图像。3360个32x32像素的测试阿拉伯字母图像。查看训练数据的headnp.unique(training_letters_labels) array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28], dtype=int32)下面需要将csv值转换为图像,我们希望展示对应图像的像素值图像。def convert_values_to_image(image_values, display=False): image_array = np.asarray(image_values) image_array = image_array.reshape(32,32).astype('uint8') # 原始数据集被反射,因此我们将使用np.flip翻转它,然后通过rotate旋转,以获得更好的图像。 image_array = np.flip(image_array, 0) image_array = rotate(image_array, -90) new_image = Image.fromarray(image_array) if display == True: new_image.show() return new_image convert_values_to_image(training_letters_images.loc[0], True)这是一个字母f。下面,我们将进行数据预处理,主要进行图像标准化,我们通过将图像中的每个像素除以255来重新缩放图像,标准化到[0,1]training_letters_images_scaled = training_letters_images.values.astype('float32')/255 training_letters_labels = training_letters_labels.values.astype('int32') testing_letters_images_scaled = testing_letters_images.values.astype('float32')/255 testing_letters_labels = testing_letters_labels.values.astype('int32') print("Training images of letters after scaling") print(training_letters_images_scaled.shape) training_letters_images_scaled[0:5]输出如下Training images of letters after scaling (13440, 1024)从标签csv文件我们可以看到,这是一个多类分类问题。下一步需要进行分类标签编码,建议将类别向量转换为矩阵类型。输出形式如下:将1到28,变成0到27类别。从“alef”到“yeh”的字母有0到27的分类号。to_categorical就是将类别向量转换为二进制(只有0和1)的矩阵类型表示在这里,我们将使用keras的一个热编码对这些类别值进行编码。一个热编码将整数转换为二进制矩阵,其中数组仅包含一个“1”,其余元素为“0”。from keras.utils import to_categorical # one hot encoding number_of_classes = 28 training_letters_labels_encoded = to_categorical(training_letters_labels-1, num_classes=number_of_classes) testing_letters_labels_encoded = to_categorical(testing_letters_labels-1, num_classes=number_of_classes)下面将输入图像重塑为32x32x1,因为当使用TensorFlow作为后端时,Keras CNN需要一个4D数组作为输入,并带有形状(nb_samples、行、列、通道)其中 nb_samples对应于图像(或样本)的总数,而行、列和通道分别对应于每个图像的行、列和通道的数量。# reshape input letter images to 32x32x1 training_letters_images_scaled = training_letters_images_scaled.reshape([-1, 32, 32, 1]) testing_letters_images_scaled = testing_letters_images_scaled.reshape([-1, 32, 32, 1]) print(training_letters_images_scaled.shape, training_letters_labels_encoded.shape, testing_letters_images_scaled.shape, testing_letters_labels_encoded.shape) # (13440, 32, 32, 1) (13440, 28) (3360, 32, 32, 1) (3360, 28)因此,我们将把输入图像重塑成4D张量形状(nb_samples,32,32,1),因为我们图像是32x32像素的灰度图像。#将输入字母图像重塑为32x32x1 training_letters_images_scaled = training_letters_images_scaled.reshape([-1, 32, 32, 1]) testing_letters_images_scaled = testing_letters_images_scaled.reshape([-1, 32, 32, 1]) print(training_letters_images_scaled.shape, training_letters_labels_encoded.shape, testing_letters_images_scaled.shape, testing_letters_labels_encoded.shape)设计模型结构from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, BatchNormalization, Dropout, Dense def create_model(optimizer='adam', kernel_initializer='he_normal', activation='relu'): # create model model = Sequential() model.add(Conv2D(filters=16, kernel_size=3, padding='same', input_shape=(32, 32, 1), kernel_initializer=kernel_initializer, activation=activation)) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.2)) model.add(Conv2D(filters=32, kernel_size=3, padding='same', kernel_initializer=kernel_initializer, activation=activation)) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.2)) model.add(Conv2D(filters=64, kernel_size=3, padding='same', kernel_initializer=kernel_initializer, activation=activation)) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.2)) model.add(Conv2D(filters=128, kernel_size=3, padding='same', kernel_initializer=kernel_initializer, activation=activation)) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.2)) model.add(GlobalAveragePooling2D()) #Fully connected final layer model.add(Dense(28, activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer=optimizer) return model「模型结构」第一隐藏层是卷积层。该层有16个特征图,大小为3×3和一个激活函数,它是relu。这是输入层,需要具有上述结构的图像。第二层是批量标准化层,它解决了特征分布在训练和测试数据中的变化,BN层添加在激活函数前,对输入激活函数的输入进行归一化。这样解决了输入数据发生偏移和增大的影响。第三层是MaxPooling层。最大池层用于对输入进行下采样,使模型能够对特征进行假设,从而减少过拟合。它还减少了参数的学习次数,减少了训练时间。下一层是使用dropout的正则化层。它被配置为随机排除层中20%的神经元,以减少过度拟合。另一个隐藏层包含32个要素,大小为3×3和relu激活功能,从图像中捕捉更多特征。其他隐藏层包含64和128个要素,大小为3×3和一个relu激活功能,重复三次卷积层、MaxPooling、批处理规范化、正则化和* GlobalAveragePooling2D层。最后一层是具有(输出类数)的输出层,它使用softmax激活函数,因为我们有多个类。每个神经元将给出该类的概率。使用分类交叉熵作为损失函数,因为它是一个多类分类问题。使用精确度作为衡量标准来提高神经网络的性能。model = create_model(optimizer='Adam', kernel_initializer='uniform', activation='relu') model.summary()「Keras支持在Keras.utils.vis_utils模块中绘制模型,该模块提供了使用graphviz绘制Keras模型的实用函数」import pydot from keras.utils import plot_model plot_model(model, to_file="model.png", show_shapes=True) from IPython.display import Image as IPythonImage display(IPythonImage('model.png'))训练模型,使用batch_size=20来训练模型,对模型进行15个epochs阶段的训练。训练结果如下所示:最后Epochs绘制损耗和精度曲线。import matplotlib.pyplot as plt def plot_loss_accuracy(history): # Loss plt.figure(figsize=[8,6]) plt.plot(history.history['loss'],'r',linewidth=3.0) plt.plot(history.history['val_loss'],'b',linewidth=3.0) plt.legend(['Training loss', 'Validation Loss'],fontsize=18) plt.xlabel('Epochs ',fontsize=16) plt.ylabel('Loss',fontsize=16) plt.title('Loss Curves',fontsize=16) # Accuracy plt.figure(figsize=[8,6]) plt.plot(history.history['accuracy'],'r',linewidth=3.0) plt.plot(history.history['val_accuracy'],'b',linewidth=3.0) plt.legend(['Training Accuracy', 'Validation Accuracy'],fontsize=18) plt.xlabel('Epochs ',fontsize=16) plt.ylabel('Accuracy',fontsize=16) plt.title('Accuracy Curves',fontsize=16) plot_loss_accuracy(history)「加载具有最佳验证损失的模型」# 加载具有最佳验证损失的模型 model.load_weights('weights.hdf5') metrics = model.evaluate(testing_letters_images_scaled, testing_letters_labels_encoded, verbose=1) print("Test Accuracy: {}".format(metrics[1])) print("Test Loss: {}".format(metrics[0]))输出如下:3360/3360 [==============================] - 0s 87us/step Test Accuracy: 0.9678571224212646 Test Loss: 0.11759862171020359打印混淆矩阵。from sklearn.metrics import classification_report def get_predicted_classes(model, data, labels=None): image_predictions = model.predict(data) predicted_classes = np.argmax(image_predictions, axis=1) true_classes = np.argmax(labels, axis=1) return predicted_classes, true_classes, image_predictions def get_classification_report(y_true, y_pred): print(classification_report(y_true, y_pred)) y_pred, y_true, image_predictions = get_predicted_classes(model, testing_letters_images_scaled, testing_letters_labels_encoded) get_classification_report(y_true, y_pred)输出如下: precision recall f1-score support 0 1.00 0.98 0.99 120 1 1.00 0.98 0.99 120 2 0.80 0.98 0.88 120 3 0.98 0.88 0.93 120 4 0.99 0.97 0.98 120 5 0.92 0.99 0.96 120 6 0.94 0.97 0.95 120 7 0.94 0.95 0.95 120 8 0.96 0.88 0.92 120 9 0.90 1.00 0.94 120 10 0.94 0.90 0.92 120 11 0.98 1.00 0.99 120 12 0.99 0.98 0.99 120 13 0.96 0.97 0.97 120 14 1.00 0.93 0.97 120 15 0.94 0.99 0.97 120 16 1.00 0.93 0.96 120 17 0.97 0.97 0.97 120 18 1.00 0.93 0.96 120 19 0.92 0.95 0.93 120 20 0.97 0.93 0.94 120 21 0.99 0.96 0.97 120 22 0.99 0.98 0.99 120 23 0.98 0.99 0.99 120 24 0.95 0.88 0.91 120 25 0.94 0.98 0.96 120 26 0.95 0.97 0.96 120 27 0.98 0.99 0.99 120 accuracy 0.96 3360 macro avg 0.96 0.96 0.96 3360 weighted avg 0.96 0.96 0.96 3360最后绘制随机几个相关预测的图片indices = np.random.randint(0, testing_letters_labels.shape[0], size=49) y_pred = np.argmax(model.predict(training_letters_images_scaled), axis=1) for i, idx in enumerate(indices): plt.subplot(7,7,i+1) image_array = training_letters_images_scaled[idx][:,:,0] image_array = np.flip(image_array, 0) image_array = rotate(image_array, -90) plt.imshow(image_array, cmap='gray') plt.title("Pred: {} - Label: {}".format(y_pred[idx], (training_letters_labels[idx] -1))) plt.xticks([]) plt.yticks([]) plt.show()
  • [其他] 使用TensorFlow2判断细胞图像是否感染
    使用 TensorFlow (Keras API) 实现一个用于二进制分类任务的深度学习模型,该任务包括将细胞的图像标记为感染或未感染疟疾。数据集来源:https://www.kaggle.com/iarunava/cell-images-for-detecting-malaria数据集包含2个文件夹感染::13780张图片未感染:13780张图片总共27558张图片。此数据集取自NIH官方网站:https://ceb.nlm.nih.gov/repositories/malaria-datasets/环境:kaggle,天池实验室或者gogole colab都可以。导入相关模块import cv2 import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Activation from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt import glob import os对于图片数据存在形状不一样的情况,因此需要使用 OpenCV 进行图像预处理。将图片变成 numpy 数组(数字格式)的形式转换为灰度,并将其调整为一个(70x70)形状。img_dir="../input/cell-images-for-detecting-malaria/cell_images" img_size=70 def load_img_data(path): # 打乱数据 image_files = glob.glob(os.path.join(path, "Parasitized/*.png")) + \ glob.glob(os.path.join(path, "Uninfected/*.png")) X, y = [], [] for image_file in image_files: # 命名标签 0 for uninfected and 1 for infected label = 0 if "Uninfected" in image_file else 1 # load the image in gray scale 变成灰度图片 img_arr = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE) # resize the image to (70x70) 调整图片大小 img_resized = cv2.resize(img_arr, (img_size, img_size)) X.append(img_resized) y.append(label) return X, y X, y = load_img_data(img_dir)查看X的shape。print(X.shape)X的shape为(27558, 70, 70, 1),27558表示图片的数据,70*70表示图片的长和宽像素。另外,为了帮助网络更快收敛,我们应该进行数据归一化。在sklearn 中有一些缩放方法,例如:在这里我们将除以255,因为像素可以达到的最大值是255,这将导致应用缩放后像素范围在 0 和 1 之间。X, y = load_img_data(img_dir) # reshape to (n_samples, 70, 70, 1) (to fit the NN) X = np.array(X).reshape(-1, img_size, img_size, 1) #从[0,255]到[0,1]缩放像素 帮助神经网络更快地训练 X = X / 255 # shuffle & split the dataset X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, stratify=y) print("Total training samples:", X_train.shape) print("Total validation samples:", X_test.shape[0])使用sklearn的train_test_split()方法将数据集划分为训练集和测试集,我们使用总数据的 10% 稍后对其进行验证。在建立的模型中,我们将添加 3 个卷积层,然后Flatten是由层组成的全连接Dense层。model = Sequential() model.add(Conv2D(64, (3, 3), input_shape=X_train.shape[1:])) model.add(Activation("relu")) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation("relu")) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation("relu")) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation("relu")) model.add(Dense(64)) model.add(Activation("relu")) model.add(Dense(1)) model.add(Activation("sigmoid")) model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) print(model.summary())由于输出是二进制的(感染或未感染),我们使用Sigmoid 函数作为输出层的激活函数。# train the model with 10 epochs, 64 batch size model.fit(X_train, np.array(y_train), batch_size=64, epochs=10, validation_split=0.2)在训练数据集及其验证拆分上实现了94%的准确率。现在使用evaluate()  来评估测试数据集上的模型loss, accuracy = model.evaluate(X_test, np.array(y_test), verbose=0) print(f"Testing on {len(X_test)} images, the results are\n Accuracy: {accuracy} | Loss: {loss}")输出如下Testing on 2756 images, the results are Accuracy: 0.9404934644699097 | Loss: 0.1666732281446457该模型在测试数据中也表现OK,准确率达到94%最后,我们将通过保存我们的模型来结束所有这个过程。model.save("model.h5")
  • [其他] 深度学习框架TensorFlow
        TensorFlow是一个基于数据流编程(dataflow programming)的符号数学系统,被广泛应用于各类机器学习(machine learning)算法的编程实现,其前身是谷歌的神经网络算法库DistBelief   。Tensorflow拥有多层级结构,可部署于各类服务器、PC终端和网页并支持GPU和TPU高性能数值计算,被广泛应用于谷歌内部的产品开发和各领域的科学研究  。TensorFlow由谷歌人工智能团队谷歌大脑(Google Brain)开发和维护,拥有包括TensorFlow Hub、TensorFlow Lite、TensorFlow Research Cloud在内的多个项目以及各类应用程序接口(Application Programming Interface, API)  。自2015年11月9日起,TensorFlow依据阿帕奇授权协议(Apache 2.0 open source license)开放源代码   。    语言与系统支持TensorFlow支持多种客户端语言下的安装和运行。截至版本1.12.0,绑定完成并支持版本兼容运行的语言为C和Python,其它(试验性)绑定完成的语言为JavaScript、C++、Java、Go和Swift,依然处于开发阶段的包括C#、Haskell、Julia、Ruby、Rust和Scala
  • [其他] TensorFlow - 基本使用
    使用 TensorFlow, 你必须明白 TensorFlow:使用图 (graph) 来表示计算任务.在被称之为 会话 (Session) 的上下文 (context) 中执行图.使用 tensor 表示数据.通过 变量 (Variable) 维护状态.使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据.综述 TensorFlow 是一个编程系统, 使用图来表示计算任务. 图中的节点被称之为 op (operation 的缩写). 一个 op 获得 0 个或多个 Tensor, 执行计算, 产生 0 个或多个 Tensor. 每个 Tensor 是一个类型化的多维数组. 例如, 你可以将一小组图像集表示为一个四维浮点数数组, 这四个维度分别是 [batch, height, width, channels].一个 TensorFlow 图描述了计算的过程. 为了进行计算, 图必须在 会话 里被启动. 会话 将图的 op 分发到诸如 CPU 或 GPU 之类的 设备 上, 同时提供执行 op 的方法. 这些方法执行后, 将产生的 tensor 返回. 在 Python 语言中, 返回的 tensor 是 numpy ndarray 对象; 在 C 和 C++ 语言中, 返回的 tensor 是 tensorflow::Tensor 实例.计算图 TensorFlow 程序通常被组织成一个构建阶段和一个执行阶段. 在构建阶段, op 的执行步骤 被描述成一个图. 在执行阶段, 使用会话执行执行图中的 op.例如, 通常在构建阶段创建一个图来表示和训练神经网络, 然后在执行阶段反复执行图中的训练 op.TensorFlow 支持 C, C++, Python 编程语言. 目前, TensorFlow 的 Python 库更加易用, 它提供了大量的辅助函数来简化构建图的工作, 这些函数尚未被 C 和 C++ 库支持.三种语言的会话库 (session libraries) 是一致的.构建图 构建图的第一步, 是创建源 op (source op). 源 op 不需要任何输入, 例如 常量 (Constant). 源 op 的输出被传递给其它 op 做运算.Python 库中, op 构造器的返回值代表被构造出的 op 的输出, 这些返回值可以传递给其它 op 构造器作为输入.TensorFlow Python 库有一个默认图 (default graph), op 构造器可以为其增加节点. 这个默认图对 许多程序来说已经足够用了. 阅读 Graph 类 文档 来了解如何管理多个图.import tensorflow as tf //导入tensorflow并简命名为tf tf.compat.v1.disable_eager_execution()//使用tf 1.0 Session()函数     demo=tf.constant("欢迎来到Tensorflow")//创建字符常量     window=tf.compat.v1.Session()//显示会话     print(window.run(Hello))通过上面的例子,将会输出b"欢迎来到Tensorflow"  PS:(在代码中直接使用中文名可能会出现\x十六进制值,可以将第三行替换成想要的内容)也可以创建简单的矩阵运算import tensorflow as tf tf.compat.v1.disable_eager_execution     matrix1=tf.constant([[2.,2.]])     matrix2=tf.constant([[3.],[3.]])     result=tf.matmul(matrix1,matrix2)     show=tf.compat.v1.Session()     print(show.run(result))上面将会输出12,第一行的值2计算下面一行的值3,相当于2x3+2x3=12