tensorflow基础例子(基础01)

例子1

# -*-coding:utf-8 -*-


import tensorflow as tf

# 定义a,b
a = tf.constant([1.0, 2.0], name='a')
b = tf.constant([2.0, 3.0], name='b')
result = a + b

# 定义会话
with tf.Session() as sess:
    print('运行结果:')
    print(sess.run(result))
    print('默认计算图:')
    print(a.graph is tf.get_default_graph())

运行结果:

运行结果:
[3. 5.]
默认计算图:
True

例子2

# -*- coding:utf-8 -*-


import tensorflow as tf

a = tf.constant([1, 2], dtype=tf.float32)
b = tf.constant([3, 4], dtype=tf.float32)

result = tf.add(a, b)

sess = tf.Session()

# 没有默认会话, 指定会话
print(result.eval(session=sess))

# 设置默认会话
with sess.as_default():
    # 以下两条语句功能相同
    print(sess.run(result))
    print(result.eval())

运行结果: 

[4. 6.]
[4. 6.]
[4. 6.]

例子3 

# -*- coding:utf-8 -*-


import tensorflow as tf

# 不同的初始化方式
print(tf.zeros(shape=[1, 2]))
print(tf.random_normal(shape=(1, 2), stddev=2))
print(tf.fill([3, 2], 9))
# 区分shape
x = tf.constant([0.7, 0.9])
print(x.shape)
y = tf.constant([[1, 2]])
print(y.shape)
z = tf.constant([[1], [2]])
print(z.shape)
k = tf.constant([[], []])
print(k.shape)

运行结果:  

Tensor("zeros:0", shape=(1, 2), dtype=float32)
Tensor("random_normal:0", shape=(1, 2), dtype=float32)
Tensor("Fill:0", shape=(3, 2), dtype=int32)
(2,)
(1, 2)
(2, 1)
(2, 0)

例子4

 

# coding=utf-8


import tensorflow as tf

w1 = tf.Variable(initial_value=tf.random_normal(shape=(2, 3), stddev=1, seed=1))
w2 = tf.Variable(initial_value=tf.random_normal(shape=(3, 1), stddev=1, seed=1))

x = tf.constant([[0.7, 0.9]])

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

with tf.Session() as sess:
    # 初始化w1
    # sess.run(w1.initializer)
    # 初始化w2
    # sess.run(w2.initializer)

    # 全部初始化
    init_op = tf.global_variables_initializer()
    sess.run(init_op)

    print(sess.run(y))
print(y.shape)
print(x.shape)

运行结果:  

[[3.957578]]
(1, 1)
(1, 2)

例子5

# -*- coding:utf-8 -*-

import tensorflow as tf

w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1), dtype=tf.float32)
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1), dtype=tf.float32)

# 定义placeholder
x = tf.placeholder(dtype=tf.float32, shape=[1, 2], name='x')

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print(sess.run(y, feed_dict={x: [[0.7, 0.9]]}))

 运行结果:

[[3.957578]]

例子6

 

# -*-coding:utf-8 -*-

from numpy.random import RandomState
import tensorflow as tf

BATCH_SIZE = 8
LEARNING_RATE = 0.001

# 生成训练数据
rdm = RandomState(seed=1)

DATASET_SIZE = 128

X = rdm.rand(DATASET_SIZE, 2)
# x1+x2 < 1 为真,y为1
# x1+x2 >= 1 为假,y为0
Y = [[int(x1 + x2 < 1)] for (x1, x2) in X]

# 定义神经网络
w1 = tf.Variable(initial_value=tf.random_normal([2, 3], stddev=1, seed=1), dtype=tf.float32)
w2 = tf.Variable(initial_value=tf.random_normal([3, 1], stddev=1, seed=1), dtype=tf.float32)

x = tf.placeholder(dtype=tf.float32, shape=[None, 2], name='x')
y_ = tf.placeholder(dtype=tf.float32, shape=[None, 1], name='y_')

# 定义前向传播
a = tf.matmul(x, w1)
y = tf.sigmoid(tf.matmul(a, w2))

# 定义交叉熵
cross_entropy = - tf.reduce_mean(
    y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)) + (1 - y_)
    * tf.log(tf.clip_by_value(1 - y, 1e-10, 1.0)))

# 选择优化算法
train_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy)

# 定义会话
with tf.Session() as sess:
    # 初始化变量
    init_op = tf.global_variables_initializer()
    sess.run(init_op)

    print(sess.run(w1))
    print(sess.run(w2))

    STEPS = 5000
    for i in range(STEPS):
        start = (i * BATCH_SIZE) % DATASET_SIZE
        end = min(start + BATCH_SIZE, DATASET_SIZE)

        sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]})

        if i % 1000 == 0:
            tc = sess.run(cross_entropy, feed_dict={x: X, y_: Y})
            print('当前step={},交叉熵为:{}'.format(i, tc))

    print(sess.run(w1))
    print(sess.run(w2))

 运行结果:

[[-0.8113182   1.4845988   0.06532937]
 [-2.4427042   0.0992484   0.5912243 ]]
[[-0.8113182 ]
 [ 1.4845988 ]
 [ 0.06532937]]
当前step=0,交叉熵为:1.8980486392974854
当前step=1000,交叉熵为:0.655075192451477
当前step=2000,交叉熵为:0.6261718273162842
当前step=3000,交叉熵为:0.615096390247345
当前step=4000,交叉熵为:0.6103087663650513
[[ 0.02476974  0.56948686  1.6921943 ]
 [-2.1977353  -0.23668927  1.1143897 ]]
[[-0.45544702]
 [ 0.49110925]
 [-0.98110336]]

例子7

# -*- coding:utf-8 -*-

import tensorflow as tf

v1 = tf.Variable(initial_value=tf.constant(1.0, shape=[1]), name='v1')
v2 = tf.Variable(initial_value=tf.constant(1.0, shape=[1]), name='v2')

result = v1 + v2

init_op = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(init_op)
    saver.save(sess, './model.ckpt')

例子8

# -*- coding:utf-8 -*-

import tensorflow as tf

v1 = tf.Variable(initial_value=tf.constant(1.0, shape=[1]), name='v1')
v2 = tf.Variable(initial_value=tf.constant(1.0, shape=[1]), name='v2')

result = v1 + v2

init_op = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
    saver.restore(sess, './model.ckpt')
    print(sess.run(result))

例子9

# -*- coding:utf-8 -*-

import tensorflow as tf

saver = tf.train.import_meta_graph('./model.ckpt.meta')

with tf.Session() as sess:
    saver.restore(sess, './model.ckpt')
    g = tf.get_default_graph()
    result = g.get_tensor_by_name('add:0')
    print(sess.run(result))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值