2024年最全深度学习高级,Keras多输入和混合数据实现回归模型,阿里技术面试难吗

(1)Python所有方向的学习路线(新版)

这是我花了几天的时间去把Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

最近我才对这些路线做了一下新的更新,知识体系更全面了。

在这里插入图片描述

(2)Python学习视频

包含了Python入门、爬虫、数据分析和web开发的学习视频,总共100多个,虽然没有那么全面,但是对于入门来说是没问题的,学完这些之后,你可以按照我上面的学习路线去网上找其他的知识资源进行进阶。

在这里插入图片描述

(3)100多个练手项目

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了,只是里面的项目比较多,水平也是参差不齐,大家可以挑自己能做的项目去练练。

在这里插入图片描述

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

在使用多种数据模式时,您会在机器学习文献中看到术语“混合数据”。 开发能够处理混合数据的机器学习系统可能极具挑战性,因为每种数据类型可能需要单独的预处理步骤,包括缩放、归一化和特征工程。 处理混合数据仍然是一个非常开放的研究领域,并且通常严重依赖于特定的任务/最终目标。

我们将在今天的教程中处理混合数据,以帮助您了解与之相关的一些挑战。

Keras 如何接受多个输入?

==========================================================================

image-20211103131246814

图 2:与其 Sequential API 不同,Keras 的函数式 API 允许使用更复杂的模型。 在这篇博文中,我们使用函数式 API 来支持我们创建具有多个输入和混合数据的模型以进行房价预测的目标。

Keras 能够通过其功能 API 处理多个输入(甚至多个输出)。 与sequential API(您之前几乎肯定已经通过 Sequential 类使用过)相反,函数式 API 可用于定义更复杂的non-sequential 模型,包括:

  • 多输入型号

  • 多输出型号

  • 多输入多输出模型

  • 有向无环图

  • 具有共享层的模型

例如,我们可以将一个简单的序列神经网络定义为:

model = Sequential()

model.add(Dense(8, input_shape=(10,), activation=“relu”))

model.add(Dense(4, activation=“relu”))

model.add(Dense(1, activation=“linear”))

这个网络是一个简单的前馈神经网络,有 10 个输入,第一个隐藏层有 8 个节点,第二个隐藏层有 4 个节点,最后一个输出层用于回归。

我们可以使用函数式 API 定义示例神经网络:

inputs = Input(shape=(10,))

x = Dense(8, activation=“relu”)(inputs)

x = Dense(4, activation=“relu”)(x)

x = Dense(1, activation=“linear”)(x)

model = Model(inputs, x)

请注意我们如何不再依赖 Sequential 类。 要了解 Keras 函数 API 的强大功能,请考虑以下代码,其中我们创建了一个接受多个输入的模型:

define two sets of inputs

inputA = Input(shape=(32,))

inputB = Input(shape=(128,))

the first branch operates on the first input

x = Dense(8, activation=“relu”)(inputA)

x = Dense(4, activation=“relu”)(x)

x = Model(inputs=inputA, outputs=x)

the second branch opreates on the second input

y = Dense(64, activation=“relu”)(inputB)

y = Dense(32, activation=“relu”)(y)

y = Dense(4, activation=“relu”)(y)

y = Model(inputs=inputB, outputs=y)

combine the output of the two branches

combined = concatenate([x.output, y.output])

apply a FC layer and then a regression prediction on the

combined outputs

z = Dense(2, activation=“relu”)(combined)

z = Dense(1, activation=“linear”)(z)

our model will accept the inputs of the two branches and

then output a single value

model = Model(inputs=[x.input, y.input], outputs=z)

在这里,您可以看到我们为 Keras 神经网络定义了两个输入:

  • 输入A:32-dim

  • 输入B : 128-dim

使用 Keras 的函数式 API 定义了一个简单的 32-8-4 网络。

类似地,定义了一个 128-64-32-4 网络。

然后我们合并 x 和 y 的输出。 x 和 y 的输出都是 4-dim,所以一旦我们将它们连接起来,我们就有一个 8-dim 向量。 然后,我们应用另外两个完全连接的层。第一层有 2 个节点,然后是 ReLU 激活,而第二层只有一个具有线性激活的节点(即我们的回归预测)。 构建多输入模型的最后一步是定义一个模型对象,它:

  • 接受我们的两个输入

  • 将输出定义为最终的 FC 层集(即 z )。

如果您要使用 Keras 来可视化模型架构,它将如下所示:

在这里插入图片描述

图 3:该模型有两个输入分支,最终合并并产生一个输出。 Keras 函数式 API 支持这种类型的架构以及您可以想象的其他架构。

注意我们的模型有两个不同的分支。 第一个分支接受我们的 128-d 输入,而第二个分支接受 32-d 输入。 这些分支彼此独立运行,直到它们连接起来。 从那里从网络输出单个值。 在本教程的其余部分,您将学习如何使用 Keras 创建多个输入网络。

房价数据集

================================================================

image-20211103132539807

图 4:房价数据集由数字/分类数据和图像数据组成。 使用 Keras,我们将构建一个支持多输入和混合数据类型的模型。 结果将是预测房屋价格/价值的 Keras 回归模型。

数据集地址:emanhamed/Houses-dataset: This is the first benchmark dataset for houses prices that contains both images and textual information that was introduced in our paper. (github.com)

该数据集包括数字/分类数据以及数据集中 535 个示例房屋中的每一个的图像数据。 数字和分类属性包括:

  • 卧室数量

  • 浴室数量

  • 面积(即平方英尺)

  • 邮政编码

每个房子总共提供了四张图片:

  • 卧室

  • 浴室

  • 厨房

  • 房子的正面图

今天,我们将使用 Keras 处理多个输入和混合数据。 我们将接受数字/分类数据以及我们的图像数据到网络。 将定义网络的两个分支来处理每种类型的数据。 然后将在最后合并分支以获得我们最终的房价预测。

通过这种方式,我们将能够利用 Keras 处理多个输入和混合数据。

项目结构

===============================================================

$ tree --dirsfirst --filelimit 10

.

├── Housesdataset

│ ├── HousesDataset [2141 entries]

│ └── README.md

├── model

│ ├── init.py

│ ├── datasets.py

│ └── models.py

└── mixed_training.py

Houses-dataset 文件夹包含我们在本系列中使用的 House Prices 数据集。 当我们准备好运行 mix_training.py 脚本时,您只需要提供一个路径作为数据集的命令行参数(我将在结果部分向您展示这是如何完成的)。 今天我们将回顾三个 Python 脚本:

model/datasets.py :处理加载和预处理我们的数值/分类数据以及我们的图像数据。 我们之前在过去两周内审查了这个脚本,但今天我将再次引导您完成它。

model/models.py :包含我们的多层感知器(MLP)和卷积神经网络(CNN)。 这些组件是我们的多输入混合数据模型的输入分支。 我们上周审查了这个脚本,今天我们也将简要审查它。

mix_training.py :我们的训练脚本将使用 pyimagesearch 模块的便利功能来加载 + 拆分数据并将两个分支连接到我们的网络 + 添加头部。 然后它将训练和评估模型。

加载数值和分类数据

====================================================================

在这里插入图片描述

打开 datasets.py 文件并插入以下代码:

import the necessary packages

from sklearn.preprocessing import LabelBinarizer

from sklearn.preprocessing import MinMaxScaler

import pandas as pd

import numpy as np

import glob

import cv2

import os

def load_house_attributes(inputPath):

initialize the list of column names in the CSV file and then

load it using Pandas

cols = [“bedrooms”, “bathrooms”, “area”, “zipcode”, “price”]

df = pd.read_csv(inputPath, sep=" ", header=None, names=cols)

determine (1) the unique zip codes and (2) the number of data

points with each zip code

zipcodes = df[“zipcode”].value_counts().keys().tolist()

counts = df[“zipcode”].value_counts().tolist()

loop over each of the unique zip codes and their corresponding

count

for (zipcode, count) in zip(zipcodes, counts):

the zip code counts for our housing dataset is extremely

unbalanced (some only having 1 or 2 houses per zip code)

so let’s sanitize our data by removing any houses with less

than 25 houses per zip code

if count < 25:

idxs = df[df[“zipcode”] == zipcode].index

df.drop(idxs, inplace=True)

return the data frame

return df

导入项目需要的包。

定义了 load_house_attributes 函数。 该函数通过 Pandas 的 pd.read_csv 以 CSV 文件的形式从房价数据集中读取数字/分类数据。 数据被过滤以适应不平衡。 一些邮政编码仅由 1 或 2 个房屋表示,因此我们继续删除邮政编码中少于 25 个房屋的任何记录。 结果是稍后更准确的模型。 现在让我们定义 process_house_attributes 函数:

def process_house_attributes(df, train, test):

initialize the column names of the continuous data

continuous = [“bedrooms”, “bathrooms”, “area”]

performin min-max scaling each continuous feature column to

the range [0, 1]

cs = MinMaxScaler()

trainContinuous = cs.fit_transform(train[continuous])

testContinuous = cs.transform(test[continuous])

one-hot encode the zip code categorical data (by definition of

one-hot encoding, all output features are now in the range [0, 1])

zipBinarizer = LabelBinarizer().fit(df[“zipcode”])

trainCategorical = zipBinarizer.transform(train[“zipcode”])

testCategorical = zipBinarizer.transform(test[“zipcode”])

construct our training and testing data points by concatenating

the categorical features with the continuous features

trainX = np.hstack([trainCategorical, trainContinuous])

testX = np.hstack([testCategorical, testContinuous])

return the concatenated training and testing data

return (trainX, testX)

此函数通过 sklearn-learn 的 MinMaxScaler将最小-最大缩放应用于连续特征。

然后,计算分类特征的单热编码,这次是通过 sklearn-learn 的 LabelBinarizer。 然后连接并返回连续和分类特征。

加载图像数据集

==================================================================

在这里插入图片描述

图 6:我们模型的一个分支接受单个图像 - 来自家中的四张图像的蒙太奇。 使用蒙太奇与输入到另一个分支的数字/类别数据相结合,我们的模型然后使用回归来预测具有 Keras 框架的房屋的价值。

下一步是定义一个辅助函数来加载我们的输入图像。 再次打开 datasets.py 文件并插入以下代码:

def load_house_images(df, inputPath):

initialize our images array (i.e., the house images themselves)

images = []

loop over the indexes of the houses

for i in df.index.values:

find the four images for the house and sort the file paths,

ensuring the four are always in the same order

basePath = os.path.sep.join([inputPath, “{}_*”.format(i + 1)])

housePaths = sorted(list(glob.glob(basePath)))

initialize our list of input images along with the output image

after combining the four input images

inputImages = []

outputImage = np.zeros((64, 64, 3), dtype=“uint8”)

loop over the input house paths

for housePath in housePaths:

load the input image, resize it to be 32 32, and then

update the list of input images

image = cv2.imread(housePath)

image = cv2.resize(image, (32, 32))

inputImages.append(image)

tile the four input images in the output image such the first

image goes in the top-right corner, the second image in the

top-left corner, the third image in the bottom-right corner,

and the final image in the bottom-left corner

outputImage[0:32, 0:32] = inputImages[0]

outputImage[0:32, 32:64] = inputImages[1]

outputImage[32:64, 32:64] = inputImages[2]

outputImage[32:64, 0:32] = inputImages[3]

add the tiled image to our set of images the network will be

trained on

images.append(outputImage)

return our set of images

return np.array(images)

load_house_images 函数有三个目标:

  • 加载房价数据集中的所有照片。 回想一下,我们每个房子都有四张照片(图 6)。

  • 从四张照片生成单个蒙太奇图像。 蒙太奇将始终按照您在图中看到的方式排列。

  • 将所有这些家庭蒙太奇附加到列表/数组并返回到调用函数。

我们定义了接受 Pandas 数据框和数据集 inputPath 的函数。

初始化图像列表。 我们将使用我们构建的所有蒙太奇图像填充此列表。 在我们的数据框中循环房屋。 在循环内部, 获取当前房屋的四张照片的路径。

执行初始化。 我们的 inputImages 将以列表形式包含每条记录的四张照片。 我们的 outputImage 将是照片的蒙太奇(如图 6 所示)。 循环 4 张照片: 加载、调整大小并将每张照片附加到 inputImages。 使用以下命令为四个房屋图像、创建平铺(蒙太奇): 左上角的浴室图片。 右上角的卧室图片。 右下角的正面视图。 左下角的厨房。 将平铺/蒙太奇 outputImage 附加到图像。 跳出循环,我们以 NumPy 数组的形式返回所有图像。

定义模型

===============================================================

image-20211103135438793

使用 Keras 的功能 API 构建的多输入和混合数据网络。

为了构建多输入网络,我们需要两个分支: 第一个分支将是一个简单的多层感知器 (MLP),旨在处理分类/数字输入。 第二个分支将是一个卷积神经网络,用于对图像数据进行操作。 然后将这些分支连接在一起以形成最终的多输入 Keras 模型。 我们将在下一节中构建最终的串联多输入模型——我们当前的任务是定义两个分支。

打开models.py文件并插入以下代码:

import the necessary packages

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import BatchNormalization

from tensorflow.keras.layers import Conv2D

from tensorflow.keras.layers import MaxPooling2D

from tensorflow.keras.layers import Activation

from tensorflow.keras.layers import Dropout

from tensorflow.keras.layers import Dense

from tensorflow.keras.layers import Flatten

from tensorflow.keras.layers import Input

from tensorflow.keras.models import Model

def create_mlp(dim, regress=False):

define our MLP network

model = Sequential()

model.add(Dense(8, input_dim=dim, activation=“relu”))

model.add(Dense(4, activation=“relu”))

check to see if the regression node should be added

if regress:

model.add(Dense(1, activation=“linear”))

return our model

return model

导入。您将在此脚本中看到每个导入的函数/类。

分类/数值数据将由一个简单的多层感知器 (MLP) 处理。 MLP在create_mlp 定义。 在本系列的第一篇文章中详细讨论过,MLP 依赖于 Keras Sequential API。我们的 MLP 非常简单,具有:

  • 具有 ReLU 激活功能的全连接(密集)输入层。

  • 一个完全连接的隐藏层,也有 ReLU 激活。

  • 最后,带有线性激活的可选回归输出。

虽然我们在第一篇文章中使用了 MLP 的回归输出,但它不会在这个多输入、混合数据网络中使用。您很快就会看到,我们将明确设置 regress=False,即使它也是默认值。回归实际上稍后会在整个多输入、混合数据网络的头部执行(图 7 的底部)。 现在让我们定义网络的右上角分支,一个 CNN:

def create_cnn(width, height, depth, filters=(16, 32, 64), regress=False):

initialize the input shape and channel dimension, assuming

TensorFlow/channels-last ordering

inputShape = (height, width, depth)

chanDim = -1

define the model input

inputs = Input(shape=inputShape)

loop over the number of filters

for (i, f) in enumerate(filters):

if this is the first CONV layer then set the input

appropriately

if i == 0:

x = inputs

CONV => RELU => BN => POOL

x = Conv2D(f, (3, 3), padding=“same”)(x)

x = Activation(“relu”)(x)

x = BatchNormalization(axis=chanDim)(x)

x = MaxPooling2D(pool_size=(2, 2))(x)

create_cnn 函数处理图像数据并接受五个参数:

  • width :输入图像的宽度(以像素为单位)。

  • height :输入图像有多少像素高。

  • depth :输入图像中的通道数。 对于RGB彩色图像,它是三个。

  • 过滤器:逐渐变大的过滤器的元组,以便我们的网络可以学习更多可区分的特征。

  • regress :一个布尔值,指示是否将完全连接的线性激活层附加到 CNN 以用于回归目的。

模型的输入是通过 inputShape 定义的。 从那里我们开始循环过滤器并创建一组 CONV => RELU > BN => POOL 层。 循环的每次迭代都会附加这些层。 如果您不熟悉,请务必查看使用 Python 进行计算机视觉深度学习入门包中的第 11 章,以获取有关这些层类型的更多信息。

让我们完成构建我们网络的 CNN 分支:

flatten the volume, then FC => RELU => BN => DROPOUT

x = Flatten()(x)

x = Dense(16)(x)

x = Activation(“relu”)(x)

x = BatchNormalization(axis=chanDim)(x)

x = Dropout(0.5)(x)

apply another FC layer, this one to match the number of nodes

coming out of the MLP

x = Dense(4)(x)

x = Activation(“relu”)(x)

check to see if the regression node should be added

if regress:

x = Dense(1, activation=“linear”)(x)

construct the CNN

model = Model(inputs, x)

return the CNN

return model

我们展平下一层,然后添加一个带有 BatchNormalization 和 Dropout 的全连接层。

应用另一个全连接层来匹配来自多层感知器的四个节点。 匹配节点的数量不是必需的,但它确实有助于平衡分支。

检查是否应附加回归节点; 然后相应地添加它。 同样,我们也不会在这个分支的末尾进行回归。 回归将在多输入、混合数据网络的头部执行(图 7 的最底部)。

最后,模型是根据我们的输入和我们组装在一起的所有层构建的x

。 然后我们可以将 CNN 分支返回给调用函数。 现在我们已经定义了多输入 Keras 模型的两个分支,让我们学习如何组合它们!

使用 Keras 进行多输入

=========================================================================

我们现在准备构建能够处理多个输入和混合数据的最终 Keras 模型。 这是分支合并的地方,也是“魔法”最终发生的地方。训练也将在此脚本中进行。 创建一个名为 mix_training.py 的新文件,打开它,并插入以下代码:

import the necessary packages

from pyimagesearch import datasets

from pyimagesearch import models

from sklearn.model_selection import train_test_split

from tensorflow.keras.layers import Dense

from tensorflow.keras.models import Model

from tensorflow.keras.optimizers import Adam

from tensorflow.keras.layers import concatenate

import numpy as np

import argparse

import locale

import os

construct the argument parser and parse the arguments

ap = argparse.ArgumentParser()

ap.add_argument(“-d”, “–dataset”, type=str, required=True,

help=“path to input dataset of house images”)

最后

🍅 硬核资料:关注即可领取PPT模板、简历模板、行业经典书籍PDF。
🍅 技术互助:技术群大佬指点迷津,你的问题可能不是问题,求资源在群里喊一声。
🍅 面试题库:由技术群里的小伙伴们共同投稿,热乎的大厂面试真题,持续更新中。
🍅 知识体系:含编程语言、算法、大数据生态圈组件(Mysql、Hive、Spark、Flink)、数据仓库、Python、前端等等。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 26
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值