tensorflow 基礎中的基礎

2021-10-23 12:02:20 字數 3152 閱讀 8682

import tensorflow as tf
m_1 = tf.constant([[

3,2]

])m_2 = tf.constant([[

3],[

2]])

pr = tf.matmul(m_1,m_2)

with tf.session(

)as s_1:

result = s_1.run(pr)

print

(result)

[[13]]
第二種開啟方式
s_2 = tf.session(

)result_2 = s_2.run(pr)

print

(result_2)

s_2.close(

)

[[13]]
v_1 = tf.variable(

0,name=

'counter'

)# 設定變數

c_1 = tf.constant(1)

# 設定常量

v_1.name # 檢視v_1屬性

new_value = tf.add(v_1 ,c_1)

# 新的值:變數+常量

update = tf.assign(v_1,new_value)

# 講new_value傳遞至v_1

init = tf.global_variables_initializer(

)# 初始化所有變數

with tf.session(

)as sess:

sess.run(init)

for i in

range(3

):sess.run(update)

print

(sess.run(v_1)

)print

(v_1.name)

1

counter_6:0

2counter_6:0

3counter_6:0

在run時需要傳入的數值
holder_1 = tf.placeholder(tf.float32)

holder_2 = tf.placeholder(tf.float32)

result = tf.multiply(holder_1,holder_2)

with tf.session(

)as sess:

print

(sess.run(result,feed_dict =

))

[80.]
將線性轉為非線性
def

add_layer

(inputs,in_size,out_size,activation_function =

none):

weights = tf.variable(tf.random_normal(

[in_size,out_size]))

# 設定權重

biases = tf.variable(tf.zeros([1

,out_size])+

0.1)

# 常數項

wx_b = tf.matmul(inputs,weights)

+ biases # 用權重和biases計算輸入

if activation_function is

none

:# 如果存在啟用函式則對輸出進行啟用否則直接輸出

outputs = wx_b

else

: outputs = activation_function(wx_b)

return outputs

import numpy as np

# 建立乙個(400,1)的輸入和同格式的輸出

x_data = np.linspace(-1

,1,400

).reshape(-1

,1) noise = np.random.normal(1,

0.05

,x_data.shape)

.astype(np.float32)

y_data = np.square(x_data)

+ noise

xs = tf.placeholder(tf.float32,

[none,1

])# 設立 x和y的傳入

ys = tf.placeholder(tf.float32,

[none,1

])l1 = add_layer(xs,1,

10,activation_function=tf.nn.relu)

# 建立隱藏層 輸入為x_data,輸入為(400,10)的輸入 啟用函式為 relu

pre = add_layer(l1,10,

1)# 建立輸出層 輸入為隱藏層輸入 輸出為**值 沒有啟用函式

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-pre)

, reduction_indices=[1

]))# 設定偏差

train_step = tf.train.gradientdescentoptimizer(

0.1)

.minimize(loss)

# 設定訓練方式 為 梯度下降 目標為最小化loss

init = tf.global_variables_initializer(

)with tf.session(

)as sess:

sess.run(init)

for step in

range

(2000):

sess.run(train_step,feed_dict =

)if step%

50==0:

print

(sess.run(loss,feed_dict =

))

Tensorflow的基礎用法

tensorflow是乙個深度學習框架,它使用圖 graph 來表示計算任務,使用tensor 張量 表示資料,圖中的節點稱為op,在乙個會話 session 的上下文中執行運算,最終產生tensor。之所以用計算圖來表示計算任務,tensorflow的官網的一張就能很好的說明。tensor在數學中...

Tensorflow的基礎用法

tensorflow是乙個深度學習框架,它使用圖 graph 來表示計算任務,使用tensor 張量 表示資料,圖中的節點稱為op,在乙個會話 session 的上下文中執行運算,最終產生tensor。之所以用計算圖來表示計算任務,tensorflow的官網的一張就能很好的說明。tensor在數學中...

Tensorflow 基礎概念

g v,e v operation 圖的節點 e tensor 圖的邊 g graph 圖 tensorflow tensor 多維陣列 flow graph 圖 op session回話上下文管理 variable tensor 多維資料變數 placeholder 外部傳入的引數變數 seesi...