【Tensorflow】Practice

2019-04-11  本文已影响0人  唯师默蓝
import tensorflow as tf

m1 = tf.constant([[2, 2]])
m2 = tf.constant([[3],
                  [3]])
# matmul():乘法
dot_operation = tf.matmul(m1, m2)

# method 1
sess = tf.Session()
result = sess.run(dot_operation)
print(result)
sess.close()
# method 2
with tf.Session() as sess:
    result_ = sess.run(dot_operation)
    print(result_)

import tensorflow as tf

x1 = tf.placeholder(dtype=tf.float32, shape=None)
y1 = tf.placeholder(dtype=tf.float32, shape=None)
z1 = x1 + y1

x2 = tf.placeholder(dtype=tf.float32, shape=[2, 1])
y2 = tf.placeholder(dtype=tf.float32, shape=[1, 2])
z2 = tf.matmul(x2, y2)
with tf.Session() as sess:
    # when only one operation to run
    z1_value = sess.run(z1, feed_dict={x1: 1, y1: 2})

    # when run multiple operations
    z1_value, z2_value = sess.run(
        [z1, z2],       # run them together
        feed_dict={
            x1: 1, y1: 2,
            x2: [[2], [2]], y2: [[3, 3]]
        })
    print(z1_value)
    print(z2_value)
import tensorflow as tf
# 循环加法
var = tf.Variable(0)    # our first variable in the "global_variable" set
# add:加法
add_operation = tf.add(var, 1)
# assign(a,b):把b赋值给a
update_operation = tf.assign(var, add_operation)

with tf.Session() as sess:
    # once define variables, you have to initialize them by doing this
    sess.run(tf.global_variables_initializer())
    for _ in range(6):
        sess.run(update_operation)
        print(sess.run(var))
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 200)     # x data, shape=(100, 1)

# 下面是流行的激活函数

y_relu = tf.nn.relu(x)
y_sigmoid = tf.nn.sigmoid(x)
y_tanh = tf.nn.tanh(x)
y_softplus = tf.nn.softplus(x)
#y_softmax = tf.nn.softmax(x) softmax是一种特殊的激活函数,它是关于概率的

# 创建回话
sess = tf.Session()
y_relu, y_sigmoid, y_tanh, y_softplus = sess.run([y_relu, y_sigmoid, y_tanh, y_softplus])

# 可视化这些激活函数
plt.figure(1, figsize=(8, 6))
plt.subplot(221)
plt.plot(x, y_relu, c='red', label='relu')
plt.ylim((-1, 5))
# legend:显示图例
#         'best'         : 0, (only implemented for axes legends)(自适应方式)
#         'upper right'  : 1,
#         'upper left'   : 2,
#         'lower left'   : 3,
#         'lower right'  : 4,
#         'right'        : 5,
#         'center left'  : 6,
#         'center right' : 7,
#         'lower center' : 8,
#         'upper center' : 9,
#         'center'       : 10,
plt.legend(loc='best')

plt.subplot(222)
plt.plot(x, y_sigmoid, c='red', label='sigmoid')
plt.ylim((-0.2, 1.2))
plt.legend(loc='best')

plt.subplot(223)
plt.plot(x, y_tanh, c='red', label='tanh')
plt.ylim((-1.2, 1.2))
plt.legend(loc='best')

plt.subplot(224)
plt.plot(x, y_softplus, c='red', label='softplus')
plt.ylim((-0.2, 6))
plt.legend(loc='best')

plt.show()
上一篇 下一篇

猜你喜欢

热点阅读