tensorflow 1 新增層及搭建神經網路

2021-08-15 21:09:01 字數 4711 閱讀 7088

參考——莫煩python

包括:1.變數定義

2.session控制

3.佔位符

4.新增層

5.搭建神經網路

#!/usr/bin/env python

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

# @time : 18/2/27 下午5:11

# @author : cicada@hole

# @file : tf.py

# @desc : tensorflow測試檔案

# @link :

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

def func1():

# dx_data = np.random.rand(100).astype(np.float32)

y_data = x_data * 0.1 + 0.3

# mweights = tf.variable(tf.random_uniform([1], -1.0, 1.0))

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

y = weights * x_data + biases

loss = tf.reduce_mean(tf.square(y - y_data))

optimizer = tf.train.gradientdescentoptimizer(0.5)

train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

session = tf.session()

session.run(init)

for step in range(201):

session.run(train)

if step % 20 == 0:

print(step, session.run(weights), session.run(biases))

def sessioncontrol():

# 建立兩個矩陣

matrix1 = tf.constant([[3,3],[2,3]])

matrix2 = tf.constant([[2],[2]])

product = tf.matmul(matrix1, matrix2)

#用session來啟用product並得到計算結果

sess = tf.session()

# method1

result = sess.run(product)

print(result)

sess.close()

# method 2

with tf.session() as sess:

result2 = sess.run(product)

print(result2)

def tfvardefine():

# 定義變數 語法: state = tf.variable()

state = tf.variable(0, name='counter')

# 定義常量 one

one = tf.constant(1)

# 定義加法步驟(此步並沒有直接計算)

new_value = tf.add(state, one)

# 將state 更新為 new_value

update = tf.assign(state, new_value)

# 定義的變數需要啟用

init = tf.global_variables_initializer()

# 使用session

with tf.session() as sess:

sess.run(init)

for _ in range(3):

sess.run(update)

print('---------state ',sess.run(state)) # 需要把sess的指標指向state 再print

#-------佔位符placeholder----

def placeholdertest():

input1 = tf.placeholder(tf.float32) #大部分形式f32

input2 = tf.placeholder(tf.float32)

output = tf.multiply(input1, input2) #乘法運算

with tf.session() as sess:

print(sess.run(output, feed_dict=))

# feed_dict和placeholder進行繫結,能傳值

#----激勵函式-----如sigmod等

def activationfunctiontest():

pass

#----新增層 ----add_layer()----

def add_layer(inputs, in_size, out_size, activation_function=none):

weights = tf.variable(tf.random_normal([in_size, out_size])) #in_size行out_size列的隨機矩陣

biases = tf.variable(tf.zeros([1, out_size]) + 0.1) #biases推薦值不為零

wx_plus_b = tf.matmul(inputs, weights) + biases #神經網路未啟用的值

#activation_function = none時,輸出wx_plus_b,不為none時,輸出啟用後的wx_plus_b

if activation_function is none:

outputs = wx_plus_b

else:

outputs = activation_function(wx_plus_b)

return outputs

#----搭建網路-----

def buildnn():

#匯入資料

x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]

noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)

y_data = np.square(x_data) - 0.5 + noise

xs = tf.placeholder(tf.float32, [none, 1])

ys = tf.placeholder(tf.float32, [none, 1])

#輸入層1個、隱藏層10個、輸出層1個的神經網路

l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)#輸入層只有乙個屬性

#輸入就是隱藏層的輸出——l1,輸入有10層(隱藏層的輸出層),輸出有1層

prediction = add_layer(l1, 10, 1, activation_function=none)

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))#平均誤差

# reduction_indices表示函式的處理維度

# 讓機器學習提公升準確率 以0.1的效率來最小化誤差loss

train_step = tf.train.gradientdescentoptimizer(0.1).minimize(loss)

init = tf.global_variables_initializer()

sess = tf.session()

sess.run(init)

fig = plt.figure()

ax = fig.add_subplot(1, 1, 1)

ax.scatter(x_data, y_data)

plt.ion() # 連續顯示

plt.show()

for i in range(1000):

sess.run(train_step, feed_dict=)

if i % 50 == 0:

# to visualize the result and improvement

try:

ax.lines.remove(lines[0])

except exception:

pass

prediction_value = sess.run(prediction, feed_dict=)

# plot the prediction

lines = ax.plot(x_data, prediction_value, 'r-', lw=5) #顯示**的資料

tensorflow 1 共享變數

共享變數 reuse variables example1 with tf.variable scope try 先建立兩個變數w1,w2 w2 tf.get variable w1 shape 2,3,4 dtype tf.float32 w3 tf.get variable w2 shape 2...

tensorflow1 構建線性模型

x是給定的輸入資料 使用tensorflow構建乙個模型,開始的時候,w和b全部給成0,讓其訓練,使其接近預設的模型。即讓w接近0.1,b接近0.2 import tensorflow as tf import numpy as np x data np.random.rand 100 y data...

神經網路 tensorflow 1

import tensorflow as tf import numpy as np create data x data np.random.rand 100 astype np.float32 在tensorflow中大部分的資料的資料型別都是float32 y data x data 0.1 ...