2016-07-14 129 views
0

我已經使用Theano來做一個簡單的線性迴歸。現在我想要顯示數據集以及其斜率每次優化的行。 我做了一個動態的實時情節,但問題是它保留了以前的情節。我想保留oroginal數據集並每次繪製新行。這裏是我的代碼:如何在python中實時繪製實時圖而不保留之前的圖?

import theano 
from theano import tensor as T 
import numpy as np 
import matplotlib.pyplot as plt 


trX = np.linspace(-1, 1, 10) 
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 
# PLOT THE ORIGINAL DATASET 
plt.figure() 
plt.ion() 
plt.scatter(trX,trY) 

X = T.scalar() 
Y = T.scalar() 

def model(X, w): 
    return X * w 

w = theano.shared(np.asarray(0., dtype=theano.config.floatX)) 
y = model(X, w) 

cost = T.mean(T.sqr(y - Y)) 
gradient = T.grad(cost=cost, wrt=w) 
updates = [[w, w - gradient * 0.01]] 

train = theano.function(inputs=[X, Y], outputs=cost, updates=updates,  allow_input_downcast=True) 

for i in range(10): 
    for x, y in zip(trX, trY): 
     train(x, y) 
     Weight = w.get_value() 
     ablineValues = [] 
     for i in trX: 
      ablineValues.append(Weight*i) 
     # PLOT THE NEW OPTIMISED LINE 
     plt.plot(trX,ablineValues,'r') 
     plt.pause(0.0000001) 

plt.show() 

你知道我該怎麼做嗎? 我已閱讀其他相關問題,但仍無法完成。如果你認爲可以幫助我,請直接給我一個好的頁面。

+0

http://stackoverflow.com/questions/8213522/matplotlib-clearing-a-plot-when-to-use-cla-clf-或關閉? –

回答

0

也許我不理解你的問題(我想寫一條評論,但是我不能......) 爲什麼不在每次創建新圖的時候刪除前面的圖? 或者爲創建圖形的文件命名,所以每次創建新文件時都會刪除具有相同名稱的文件。也許你會發現this有用。

+0

我其實並沒有使用這種創建和刪除的方法。有點快一個。但是,我發現它。通過'axes = plt.gca()'和 'axes.lines = []'之前 'plt.plot(trX,ablineValues,'r')'我做到了。謝謝。 – user6352340

0

使用plot_handle.set_ydata(和向量化比特)

import theano 
from theano import tensor as T 
import numpy as np 
import matplotlib.pyplot as plt 


trX = np.linspace(-1, 1, 10) 
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 
# PLOT THE ORIGINAL DATASET 
plt.figure() 
plt.ion() 
plt.scatter(trX,trY) 

X = T.scalar() 
Y = T.scalar() 

def model(X, w): 
    return X * w 

w = theano.shared(np.asarray(0., dtype=theano.config.floatX)) 
y = model(X, w) 

cost = T.mean(T.sqr(y - Y)) 
gradient = T.grad(cost=cost, wrt=w) 
updates = [[w, w - gradient * 0.01]] 

train = theano.function(inputs=[X, Y], outputs=cost, updates=updates,  allow_input_downcast=True) 

h, = plt.plot(trX,np.zeros(trX.shape)+np.nan,'r') # INITIALIZE YOUR PLOT 
for i in range(10): 
    for x, y in zip(trX, trY): 
     train(x, y) 
     Weight = w.get_value() 
     ablineValues = Weight*trX # VECTORIZE! 
     # PLOT THE NEW OPTIMISED LINE 
     h.set_ydata(ablineValues) # SET DATA INSTEAD OF REPLOTTING IT 
     plt.pause(0.0000001) 

plt.show()