python - Numpy 数组的 feed_dict 形状问题
问题描述
我正在尝试使用本教程为多个变量实现线性回归模型。我尝试使用train_test_split()
sklearn 的方法将其替换为我自己的数据集。
import numpy as np
import tensorflow as tf
import pandas as pd
df = pd.read_csv('airfoil_self_noise.csv',sep=',')
from sklearn.model_selection import train_test_split
X_true, X_test, y_true, y_test = train_test_split(df.iloc[:,:-1].values,df.iloc[:,-1].values,test_size = 0.2, random_state=0)
n_features = np.shape(X_true)[1]
m_examples = np.shape(X_true)[0]
# Placeholder that is fed input data.
X_in = tf.placeholder(tf.float32, [None, n_features], "X_in")
# The model: we assume y = X_in * w + b
w = tf.Variable(tf.random_normal((n_features, 1)), name="w")
b = tf.Variable(tf.constant(0.1, shape=[]), name="b")
h = tf.add(tf.matmul(X_in, w), b, name="h")
# Placeholder that is fed observed results.
y_in = tf.placeholder(tf.float32,[1,None], "y_in")
# The loss function: we are minimizing square root of mean
loss_op = tf.reduce_mean(tf.square(tf.subtract(y_in, h)), name="loss")
train_op = tf.train.GradientDescentOptimizer(0.3).minimize(loss_op)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(1000):
sess.run(train_op, feed_dict={
X_in: X_true,
y_in: y_true
})
w_computed = sess.run(w)
b_computed = sess.run(b)
print ("w computed [%s]" % ', '.join(['%.5f' % x for x in w_computed.flatten()]))
print ("w actual [%s]" % ', '.join(['%.5f' % x for x in w_true.flatten()]))
print ("b computed %.3f" % b_computed)
print ("b actual %.3f" % b_true[0])
我似乎遇到的问题是馈入 y_in 的 numpy 数组的形状。
Traceback (most recent call last):
File "Airfoil_Test_TF.py", line 32, in <module>
y_in: y_true
File ".../anaconda3/envs/py36/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
run_metadata_ptr)
File ".../anaconda3/envs/py36/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1128, in _run
str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1202,) for Tensor 'y_in:0', which has shape '(1, ?)'
我试图修改 y_in 占位符的尺寸,但它没有做任何事情。本教程最初使用尺寸[None,1]
而不是这种方式定义了占位符,但我找不到转置y_true
为形状 (,1202) 的方法,因为在 numpy.xml 中无法转置单维数组。
有什么建议么?
谢谢!
解决方案
你可以打电话
y_true = y_true.reshape((1,-1))
这应该可以解决问题。
简短说明:
在 numpy 中,形状(10,)
只是一个一维向量。
形状(10, 1)
表示一个明确的行向量。
形状(1, 10)
代表一个列向量。
推荐阅读
- c++ - C++ 中的 Qt Quick / QML 标志更改回 UI
- mongodb - Mongo Facet 聚合与 Sum
- javascript - 在哪里可以找到有关 JSON.stringify.replace() 方法的文档?
- heroku - Node js应用程序在没有日志的heroku上运行几秒钟后崩溃
- sql-server - 在 ubuntu 中安装 ms-sql 时出现包冲突。破损的包裹
- assembly - 汇编语言按钮功能
- onedrive - 根据 URL 获取 OneDrive 详细信息(https://1drv.ms/u/s!AtLQ0D1mu8SWcw7SxEL4olaQ3B8?e=NHs43v)
- html - 顺风背景不透明度
- quickbase - 有没有办法在 QuickBase 中跨行和列连接?
- c# - 应用程序无法编译 - 错误 CS5001