我想要创建30个20维数据作为x,然后让其与一个20维权重相乘,最后得出30个1维数据作为y,但是报错说我x,y must be the same size,为何?
x_data=np.random.randint(0,10,size=[30,20])
print('x_shape:',x_data.shape)
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
z_data = np.random.randint(0,10,size=[20,1])
print('z_shape:',z_data.shape)
y_data = np.matmul(x_data,z_data)
print('y_shape:',y_data.shape)
xs = tf.placeholder(tf.float32, [None, 20])
ys = tf.placeholder(tf.float32, [None, 1])
Weights1 = tf.Variable(tf.random_normal([20, 5]))
biases1 = tf.Variable(tf.zeros([1, 5]) + 0.1)
Wx_plus_b1 = tf.matmul(xs, Weights1) + biases1
l1 = tf.nn.relu(Wx_plus_b1)
隐层2
Weights2 = tf.Variable(tf.random_normal([5, 10]))
biases2 = tf.Variable(tf.zeros([1, 10]) + 0.1)
Wx_plus_b2 = tf.matmul(l1, Weights2) + biases2
l2 = tf.nn.relu(Wx_plus_b2)
输出层
Weights3 = tf.Variable(tf.random_normal([10, 1]))
biases3 = tf.Variable(tf.zeros([1, 1]) + 0.1)
prediction = tf.matmul(l2, Weights3) + biases3
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(0.1).minimize(loss)
init = tf.global_variables_initializer()
激活会话
with tf.Session() as sess:
sess.run(init)
# 绘制原始x-y散点图。
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show()
# 迭代次数 = 10000
for i in range(10000):
# 训练
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
# 每50步绘图并打印输出。
if i % 50 == 0:
# 可视化模型输出的结果。
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value = sess.run(prediction, feed_dict={xs: x_data})
# 绘制模型预测值。
lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
plt.pause(1)
# 打印损失
print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
这段代码运行的结果是没有二维图上没有点,还报了题目中说的那个错