TensorFlow深度学习入门

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Tue Oct  2 15:49:08 2018
 4 
 5 @author: zhen
 6 """
 7 
 8 import tensorflow as tf
 9 import numpy as np
10 from sklearn.datasets import  fetch_california_housing
11 
12 x = tf.Variable(3, name='x')
13 y = tf.Variable(4, name='y')
14 
15 # 任何创建的节点会自动加入到默认的图中
16 print(x.graph is tf.get_default_graph())
17 
18 # 创建新的图
19 graph = tf.Graph()
20 
21 with graph.as_default():
22     # 只在with范围内有效
23     demo = tf.Variable(3)
24 
25 print(demo.graph is graph)
26     
27 demo2 = tf.Variable(3)
28 print(demo2.graph is graph)
29 
30 # 创建常量
31 constant = tf.constant(3)
32 
33 f = x * x * y + x * y + 1
34 f2 = f * constant
35 
36 # 可以不分别对每个变量去进行初始化,在run运行时初始化
37 init = tf.global_variables_initializer()
38 
39 with tf.Session() as sess:
40     init.run()
41     result = f.eval()
42     result2 = f2.eval()
43     print(result, result2)
44 
45     f_result, f2_result = sess.run([f, f2])
46     print(f_result, f2_result)
47 
48 # 获取数据集
49 housing = fetch_california_housing(data_home="C:/Users/zhen/.spyder-py3/data", download_if_missing=True)
50 # 获取x数据行数和列数
51 m, n = housing.data.shape
52 # 添加额外数据加入特征
53 housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
54 # 创建两个Tensorflow常量节点x和y,去持有数据和标签
55 x = tf.constant(housing_data_plus_bias, dtype=tf.float32, name='x')
56 y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')
57 # 矩阵操作
58 xt = tf.transpose(x)
59 # 计算最优解
60 theta = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(xt, x)), xt), y)
61 with tf.Session() as sess:
62     theta_value = theta.eval()
63     print(theta_value)

猜你喜欢

转载自www.cnblogs.com/yszd/p/9761758.html