tensorflow基礎使用4

2021-08-08 08:44:48 字數 1423 閱讀 9445

非線性回歸

# coding: utf-8

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

#使用numpy生成200個隨機點

x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]

noise = np.random.normal(0,0.02,x_data.shape)

y_data = np.square(x_data) + noise

#定義兩個placeholder

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

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

#定義神經網路中間層

weights_l1 = tf.variable(tf.random_normal([1,10]))

biases_l1 = tf.variable(tf.zeros([1,10]))

wx_plus_b_l1 = tf.matmul(x,weights_l1) + biases_l1

l1 = tf.nn.tanh(wx_plus_b_l1)

#定義神經網路輸出層

weights_l2 = tf.variable(tf.random_normal([10,1]))

biases_l2 = tf.variable(tf.zeros([1,1]))

wx_plus_b_l2 = tf.matmul(l1,weights_l2) + biases_l2

prediction = tf.nn.tanh(wx_plus_b_l2)

#二次代價函式

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

#使用梯度下降法訓練

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

with tf.session() as sess:

#變數初始化

sess.run(tf.global_variables_initializer())

for _ in range(2000):

sess.run(train_step,feed_dict=)

#獲得**值

prediction_value = sess.run(prediction,feed_dict=)

#畫圖plt.figure()

plt.scatter(x_data,y_data)

plt.plot(x_data,prediction_value,'r-',lw=5)

plt.show()

第4章 TensorFlow基礎

基本資料型別,包含數值型 字串型和布林型。布林型別的張量只需要傳入 python 語言的布林型別資料,轉換成 tensorflow 內部布林型即可 需要注意的是,tensorflow 的布林型別和 python 語言的布林型別並不對等,不能通用 a tf.constant true a true 輸...

tensorflow基礎使用1

1.op的設計及執行乙個簡單的圖import tensorflow as tf x tf.variable 1,2 建立變數 a tf.constant 3,3 建立常量 sub tf.subtract x,a 定義減法op add tf.add x,sub 定義加法op init tf.globa...

tensorflow基礎使用2

fetch和 feed的用法 1.fetch的用法也就是在session執行時,可以以列表的方式傳參,從而同時run多個op coding utf 8 import tensorflow as tf how to use fetch input1 tf.constant 3.0 input2 tf....