我正在尝试在Tensorflow中实现1d卷积神经网络。这是用于创建占位符,卷积层和最大池层的代码:
import tensorflow as tf
import math
try:
from tqdm import tqdm
except ImportError:
def tqdm(x, *args, **kwargs):
return x
sess = tf.InteractiveSession()
# These will be inputs
## Input pixels, image with one channel (gray)
length=458
x = tf.placeholder("float", [None, length])
# Note that -1 is for reshaping
x_im = tf.reshape(x, [-1,length,1])
## Known labels
# None works during variable creation to be
# unspecified size
y_ = tf.placeholder("float", [None,2])
# Conv layer 1
num_filters1 = 2
winx1 = 3
W1 = tf.Variable(tf.truncated_normal(
[winx1, 1 , num_filters1],
stddev=1./math.sqrt(winx1)))
b1 = tf.Variable(tf.constant(0.1,
shape=[num_filters1]))
# 5 convolution, pad with zeros on edges
xw = tf.nn.conv1d(x_im, W1,
stride=5,
padding='SAME')
h1 = tf.nn.relu(xw + b1)
# 2 Max pooling, no padding on edges
p1 = tf.layers.max_pooling1d(h1, pool_size=2,
strides=1, padding='VALID')
# Conv layer 2
num_filters2 = 2
winx2 = 3
W2 = tf.Variable(tf.truncated_normal(
[winx2, num_filters1, num_filters2],
stddev=1./math.sqrt(winx2)))
b2 = tf.Variable(tf.constant(0.1,
shape=[num_filters2]))
# 3 convolution, pad with zeros on edges
p1w2 = tf.nn.conv1d(p1, W2,
stride=3, padding='SAME')
h1 = tf.nn.relu(p1w2 + b2)
# 2 Max pooling, no padding on edges
p2 = tf.layers.max_pooling1d(h1, pool_size=2,
strides=1, padding='VALID')
# Need to flatten convolutional output
p2_size = np.product(
[s.value for s in p2.get_shape()[1:]])
p2f = tf.reshape(p2, [-1, p2_size ])
# Dense layer
num_hidden = 2
W3 = tf.Variable(tf.truncated_normal(
[p2_size, num_hidden],
stddev=2./math.sqrt(p2_size)))
b3 = tf.Variable(tf.constant(0.2,
shape=[num_hidden]))
h3 = tf.nn.relu(tf.matmul(p2f,W3) + b3)
# Drop out training
keep_prob = tf.placeholder("float")
h3_drop = tf.nn.dropout(h3, keep_prob)
# Output Layer
W4 = tf.Variable(tf.truncated_normal(
[num_hidden, 2],
stddev=1./math.sqrt(num_hidden)))
b4 = tf.Variable(tf.constant(0.1,shape=[2]))
# Just initialize
sess.run(tf.global_variables_initializer())
# Define model
y = tf.nn.softmax(tf.matmul(h3_drop,W4) + b4)
### End model specification, begin training code
在构建模型之后,是时候定义损失函数,如下所示:
# Climb on cross-entropy
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits_v2(
logits=y + 1e-50, labels=y_))
# How we train
train_step = tf.train.GradientDescentOptimizer(
0.01).minimize(cross_entropy)
# Define accuracy
correct_prediction = tf.equal(tf.argmax(y,1),
tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(
correct_prediction, "float"))
但是当我尝试使用以下代码训练模型时:
# Actually train
epochs = 10
train_acc = np.zeros(epochs//10)
test_acc = np.zeros(epochs//10)
for i in tqdm(range(epochs), ascii=True):
# Record summary data, and the accuracy
if i % 10 == 0:
# Check accuracy on train set
A = accuracy.eval(feed_dict={x: train,
y_: onehot_train, keep_prob: 1.0})
train_acc[i//10] = A
# And now the validation set
A = accuracy.eval(feed_dict={x: test,
y_: onehot_test, keep_prob: 1.0})
test_acc[i//10] = A
train_step.run(feed_dict={x: train,\
y_: onehot_train, keep_prob: 0.5})
它返回错误:
ValueError:无法为Tensor提供形状值(7487,458) 'placeholder_8:0',其形状为'(?,1,458)'
我有7478(1D)信号,长度为458。有人可以帮帮我吗?!
答案 0 :(得分:3)
你只需要重塑你的输入
Use Internal JRE
你很高兴去!