tensorflow一元二次函式擬合

2021-09-06 06:37:41 字數 2166 閱讀 2142

先看下要做的內容,建立一元二次函式y=x平方-0.5,其中為了更符合散點圖模擬需要,在方程加噪點,以標準方差0.05行駛,如圖所示

折線圖散點圖

下面我們要做的,是要計算機自動擬合出該散點圖的函式,畫出圖樣,如圖

下面,就通過tensorflow來看如何做出這個樣子

在tensorflow中,首先定義

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

#定義隱藏層

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_plus_b=tf.matmul(inputs,weights)+biases  #z=wx+b

if activation_function is none:

outputs=wx_plus_b

else:

outputs=activation_function(wx_plus_b)

return outputs

#make up some real data

x_data=np.linspace(-1,1,300)[:,np.newaxis]#加維度

noise=np.random.normal(0,0.05,x_data.shape)#加噪點,標準方差0.05

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

#train_step所要輸入的值

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

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

###建立第一,二次隱藏層layer

###add_layer(inputs,in_size,out_size,activation_function=none)

l1=add_layer(xs,1,10,activation_function=tf.nn.relu)#激勵函式(activation_function)relu

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

#建立損失函式

loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),

reduction_indices=[1]))

train_step=tf.train.gradientdescentoptimizer(0.1).minimize(loss)#梯度下降優化器,減少誤差,學習效率0.1

#important step

init=tf.initialize_all_variables()

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()

#學習1000步

for i in range(1000):

sess.run(train_step,feed_dict=)

if i%50==0:

#print(sess.run(loss,feed_dict=)) #輸出誤差

try:

ax.lines.remove(lines[0])

except exception:

pass

prediction_value=sess.run(prediction,feed_dict=)

lines=ax.plot(x_data,prediction_value,'r',lw=5)

plt.pause(0.1)

輸出誤差截圖,每50次輸出一次,截圖如下

誤差逐漸遞減的截圖

這樣就完成了

在html中繪製一元一次,一元二次,一元三次函式

入門級別,大神繞過。html畫布和js提供的一些繪製函式,可以輕鬆的幫助我們繪製函式。只要掌握好縮放比例。如果再把滾動條和對應的引數繫結,大概就可以實現函式圖隨引數改變而改變的效果吧。lang en charset utf 8 documenttitle head drawing width 160...

一元二次方程

作 者 a42 覃燕玲 完成日期 2014年 10 月 25 日 版 本 號 v1.0 問題描述 建立乙個程式解平方根 輸入描述 ax 2 bx x 0 a o 程式輸出 平方根 using system using system.collections.generic using system.l...

一元二次方程

一 知識要點 一元二次方程和一元一次方程都是整式方程,它是初中數學的乙個重點內容,也是今後學習數學的基 礎。一元二次方程的一般形式為 ax 2 2為次數,即x的平方 bx c 0,a 0 它是只含乙個未知數,並且未知數的最高次數是2 的整式方程。解一元二次方程的基本思想方法是通過 降次 將它化為兩個...