import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
Os dados
x=np.array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5])
y=np.array([-53.9, -28.5, -20.7, -3.6, -9.8, 5.0, 4.2, 5.1, 11.4, 27.4, 44.0])
xmat=np.vstack((x**3,x**2,x,np.ones(len(x)))).T
# preciso da transposta pois vou usar o tf.multiply e nao o np.dot das outras questoes.
Place holders do TF
tfx= tf.placeholder("float")
tfy= tf.placeholder("float")
tfxmat=tf.placeholder("float")
w = tf.Variable([0.0,0.0,0.0,0.0], name="w")
previsao e erro veja que o erro é para dodos os dados e nao um dado por vez
pred=tf.reduce_sum(tf.multiply(w,tfxmat),axis=1)
#pred é um vetor de predicoes (para cada x)
erro = tf.reduce_sum(tf.pow(pred-tfy, 2))
define o otimizador
optimizer = tf.train.AdamOptimizer(0.01).minimize(erro)
init = tf.global_variables_initializer()
eu estou usando uma solucao em batch
with tf.Session() as sess:
sess.run(init)
for epoch in range(200):
sess.run(optimizer, feed_dict={tfxmat: xmat, tfy: y})
if (epoch+1) % 10 == 0:
c = sess.run(erro, feed_dict={tfxmat: xmat, tfy:y})
print("erro: "+str(c))
c = sess.run(erro, feed_dict={tfxmat: xmat, tfy:y})
print("erro: "+str(c))
wend=sess.run(w)
print("w: "+str(wend))
ypred= wend[0]*x**3+wend[1]*x**2+wend[2]*x+wend[3]
plt.plot(x, y, 'ro', label='Original data')
plt.plot(x, ypred, label='Fitted line')
plt.show()