我在这里阅读了张量流的指南开始a link 在本指南中,使用模型y = W * x + b的一维示例。 之后,我尝试为x创建2维。遵循我的代码:
import tensorflow as tf
import numpy as np
import random as rd
rd.seed(2)
#model is 2*x1 + x2 - 3 = y
def create_data_train():
x_train = np.asarray([[2,3],[6,7],[1,5],[4,6],[10,-1],[0,0],[5,6],
[8,9],[4.5,6.2],[1,1],[0.3,0.2]])
w_train = np.asarray([[2,1]])
b = np.asarray([[-3]])
y_train = np.dot(x_train, w_train.T) + b
for i in range(y_train.shape[0]):
for j in range(y_train.shape[1]):
y_train[i][j] += 1-rd.randint(0,2)
return x_train,y_train
# step 1
x = tf.placeholder(tf.float32, [None, 2])
W = tf.Variable(tf.zeros([2, 1]))
b = tf.Variable(tf.zeros([1]))
y = tf.matmul(x, W) + b
y_ = tf.placeholder(tf.float32, [None, 1])
# step 2
loss = tf.reduce_sum(tf.pow(tf.subtract(y,y_),2))
optimizer = tf.train.GradientDescentOptimizer(0.05)
train = optimizer.minimize(loss)
#step 3
x1,y1 = create_data_train()
x_train = tf.convert_to_tensor(x1)
y_train = tf.convert_to_tensor(y1)
print(x_train)
print(y_train)
init = tf.global_variables_initializer()
sess = tf.Session()
print(sess.run(x_train))
sess.run(init)
for i in range(1000):
sess.run(train,feed_dict={x:x_train,y_:y_train})
endW ,endb = sess.run([W,b])
print(endW)
print(endb)
但是当我跑步时,我遇到一个错误是:
TypeError:Feed的值不能是tf.Tensor对象。可接受的Feed值包括Python标量,字符串,列表,numpy ndarrays或TensorHandles。
答案 0 :(得分:0)
此处出现错误,因为您无法将张量提供给 feed_dict 。
由于您有以下两行,
x_train = tf.convert_to_tensor(x1)
y_train = tf.convert_to_tensor(y1)
您正在将 x1 和 y1 转换为张量(即您的输入和输出)。直接输入 x1 和 y1 ,而不转换为张量。
希望这有帮助。