Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
sess = tf.Session()
# the training set
x_train = np.linspace(0, 10, 100)
y_train = x_train + np.random.normal(0,1,100)
# Creating X
x_vals_column = np.transpose(np.matrix(x_train))
ones_column = np.transpose(np.matrix(np.repeat(1, 100)))
X = np.column_stack((x_vals_column, ones_column))
# Create y matrix
y = np.transpose(np.matrix(y_train))
# Create tensors
X_tensor = tf.constant(X)
y_tensor = tf.constant(y)
# Find Cholesky Decomposition of X*XT
tX_X = tf.matmul(tf.transpose(X_tensor), X_tensor)
L = tf.cholesky(tX_X)
# Solve L*Z = y*XT for Z
tX_y = tf.matmul(tf.transpose(X_tensor), y)
Z = tf.matrix_solve(L, tX_y)
# Solve LT*WT = Z for WT
WT= tf.matrix_solve(tf.transpose(L), Z)
solution_eval = sess.run(WT)
# Extract coefficients
w1= solution_eval[0][0]
w0 = solution_eval[1][0]
# Get best fit line
best_fit = []
for i in x_train:
best_fit.append(w1*i+w0)
# Plot the results
plt.plot(x_train, y_train, 'o', label='Data')
plt.plot(x_train,best_fit, 'r-', label='Best fit line', linewidth=3)
plt.legend(loc='upper left')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.