贴吧问题: 一维序列的卷积神经网络 2021-10-27

贴吧问题:
题主最近刚接触神经网络的课题,目前想要用Python做一个一维序列的卷积神经网络,需求是将一维序列卷积池化后,再将卷积得到的特征数据序列与另外三个数值数据放入全连接层。
就是卷积和bp的结合,想问问该怎么做

答案:

from tensorflow.keras.layers import Conv1D, MaxPool1D, Flatten, Dense, Input
from tensorflow.keras.models import Model
import numpy as np
import tensorflow

ipt_size=100 #100个样本

ipt_shape=128 #一维128长度数据
ipt2_shape=3 # 三维数据

x1=np.random.randint(0,100,(ipt_size, ipt_shape))
y=np.random.randint(0,100,(ipt_size))
x2=np.random.randint(0,100,(ipt_size, ipt2_shape))


# x  扩维
x1=np.expand_dims(x1, axis=-1)
# 随机样本 x, y
print(x1.shape)
print(y.shape)
print(x2.shape)

ipt1=Input((ipt_shape, 1))
cov1=Conv1D(filters=32, kernel_size=3)(ipt1)
max1=MaxPool1D()(cov1)

cov2=Conv1D(filters=32, kernel_size=3)(max1)
max2=MaxPool1D()(cov2)


f=Flatten()(max2)

ipt2=Input((ipt2_shape))

# 连接层
class Combine_ipt(tensorflow.keras.layers.Layer):
    def __init__(self):
        super(Combine_ipt, self).__init__()

    def call(self, inputs):
        ipt1=inputs[0]
        ipt2=inputs[1]

        res=tensorflow.concat([ipt1, ipt2], -1)


        print("融合前维度为:%s 和 %s, 融合后变成:%s", ipt1.shape, ipt2.shape, res.shape)

        return res

#使用连接层连接 f 和 ipt2
ci=Combine_ipt()([f, ipt2])

d1=Dense(32, activation="relu")(f)

# 回归问题, 单神经元无激活函数
opt=Dense(1)(d1)

model=Model((ipt1, ipt2), opt)

model.summary()

model.compile(loss="mse")

# 训练, 参数自己调 (x=None, y=None, batch_size=None, epochs=1, verbose='auto', callbacks=None, validation_split=0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_batch_size=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False)
model.fit(x=[x1, x2], y=y)

# 推理
pred=model.predict([x1, x2])

print(pred)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值