In [20]:
import tensorflow as tf
import numpy as np
from sklearn.datasets import fetch_california_housing
In [2]:
print(tf.__version__)
In [3]:
x = tf.Variable(3, name="x")
y = tf.Variable(4, name="y")
f = x*x*y + y + 2
In [4]:
with tf.Session() as sess:
x.initializer.run()
y.initializer.run()
result = f.eval()
In [10]:
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
result = f.eval()
print(result)
In [8]:
sess = tf.InteractiveSession()
init.run()
result = f.eval()
print(result)
In [9]:
sess.close()
In [11]:
x1 = tf.Variable(1)
In [12]:
x1.graph is tf.get_default_graph()
Out[12]:
In [13]:
graph = tf.Graph()
with graph.as_default():
x2 = tf.Variable(2)
In [14]:
x2.graph is graph
Out[14]:
In [15]:
x2.graph is tf.get_default_graph()
Out[15]:
In [16]:
w = tf.constant(3)
x = w + 2
y = x + 5
z = x * 3
In [17]:
with tf.Session() as sess:
print(y.eval())
print(z.eval())
In [18]:
with tf.Session() as sess:
y_val, z_val = sess.run([y, z])
print(y_val)
print(z_val)
In [21]:
housing = fetch_california_housing()
m, n = housing.data.shape
housing_data_plus_bias = np.c_[np.ones((m,1)), housing.data]
In [23]:
X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")
XT = tf.transpose(X)
theta = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(XT,X)), XT), y)
In [25]:
with tf.Session() as sess:
theta_value = theta.eval()
print(theta_value)
In [26]:
A = tf.placeholder(tf.float32, shape=(None, 3))
B = A + 5
In [27]:
with tf.Session() as sess:
B_val_1 = B.eval(feed_dict={A: [[1,2,3]]})
B_val_2 = B.eval(feed_dict={A: [[4,5,6], [7,8,9]]})
In [29]:
print(B_val_1)
In [30]:
print(B_val_2)
In [ ]:
X = tf.placeholder(tf.float32, shape=(None, n+1), name="X")
y = tf.placeholder(tf.float32, shape(None, 1), name="y")
In [ ]:
save = tf.train.Saver()
In [ ]:
with tf.Session() as sess:
sess.run(init)
for epoch in range(n_epochs):
if epoch % 100 == 0:
save_path = saver.save(sess, "./tmp/my_model.ckpt")
sess.run(training_op)
best_theta = theta.eval()
save_path = saver.save(Sess, "./tmp/my_model_final.ckpt")
In [ ]:
with tf.Session() as sess:
saver.restore(sess, "./tmp/my_model_final.ckpt")
In [ ]:
saver = tf.train(saver({"weights": theta}))
In [ ]:
saver = tf.train.import_meta_graph("./tmp/my_model_final.ckpt.meta")
with tf.Session() as sess:
saver.restore(sess, "./tmp/my_model_final.ckpt")
In [ ]:
In [31]:
from datetime import datetime
In [34]:
now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
root_logdir = "tf_logs"
logdir = "{}/run-{}/".format(root_logdir, now)
In [36]:
mse_summary = tf.summary.scalar("MSE", mse)
file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph())
In [38]:
with tf.name_scope("loss") as scope:
error = y_pred - y
mse = tf.reduce_mean(tf.square(error), name="mse")
In [ ]: