tensorflow實現線性迴歸

import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from sklearn import datasets from tensorflow.python.framework import ops ops.reset_default_graph() sess = tf.Session()python

iris = datasets.load_iris()app

x_vals = np.array([x[3] for x in iris.data]) y_vals = np.array([y[0] for y in iris.data])dom

learn_rate = 0.05 batch_size = 25 x_data = tf.placeholder(shape=[None,1],dtype=tf.float32) y_target = tf.placeholder(shape=[None,1],dtype=tf.float32)orm

A = tf.Variable(tf.random_normal(shape=[1,1])) b = tf.Variable(tf.random_normal(shape=[1,1]))get

model_output = tf.add(tf.matmul(x_data,A),b)it

loss = tf.reduce_mean(tf.square(y_target-model_output)) init = tf.global_variables_initializer() sess.run(init) my_opt = tf.train.GradientDescentOptimizer(learn_rate) train_step = my_opt.minimize(loss)io

loss_vec = []import

for i in range(200): rand_index = np.random.choice(len(x_vals),size=batch_size) rand_x = np.transpose([x_vals[rand_index]]) rand_y = np.transpose([y_vals[rand_index]]) sess.run(train_step,feed_dict={x_data:rand_x,y_target:rand_y}) temp_loss = sess.run(loss,feed_dict={x_data:rand_x,y_target:rand_y}) loss_vec.append(temp_loss)tensorflow

[slope] = sess.run(A) [intercept] = sess.run(b) best_fit =[] for i in x_vals: best_fit.append(i*slope+intercept) plt.plot(x_vals,y_vals,'x',label='data') plt.plot(x_vals,best_fit,'r--',label='best line') plt.legend(loc ='upper right') plt.show() plt.plot(loss_vec,'k-') plt.show()model

相關文章
相關標籤/搜索