贴吧问题: 题主最近刚接触神经网络的课题,目前想要用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
ipt_shape=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))
x1=np.expand_dims(x1, axis=-1)
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
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")
model.fit(x=[x1, x2], y=y)
pred=model.predict([x1, x2])
print(pred)
|