2017-05-03 54 views
1

https://github.com/llSourcell/predicting_stock_prices/blob/master/demo.py複製的代碼 當我在jupyter筆記本中運行它掛起並掛在最後一行。我在筆記本電腦和下載文件夾中的.csv ......不知道這是錯誤Jupyter筆記本掛sklearn返回?

import csv 
import numpy as np 
from sklearn.svm import SVR 
import matplotlib.pyplot as plt 


#plt.switch_backend('newbackend') 

dates = [] 
prices = [] 

def get_data(filename): 
    with open(filename, 'r') as csvfile: 
     csvFileReader = csv.reader(csvfile) 
     next(csvFileReader) # skipping column names 
     for row in csvFileReader: 
      dates.append(int(row[0].split('-')[0])) 
      prices.append(float(row[1])) 
    return 

def predict_price(dates, prices, x): 
    dates = np.reshape(dates,(len(dates), 1)) # converting to matrix of n X 1 

    svr_lin = SVR(kernel= 'linear', C= 1e3) 
    svr_poly = SVR(kernel= 'poly', C= 1e3, degree= 2) 
    svr_rbf = SVR(kernel= 'rbf', C= 1e3, gamma= 0.1) # defining the support vector regression models 
    svr_rbf.fit(dates, prices) # fitting the data points in the models 
    svr_lin.fit(dates, prices) 
    svr_poly.fit(dates, prices) 

    plt.scatter(dates, prices, color= 'black', label= 'Data') # plotting the initial datapoints 
    plt.plot(dates, svr_rbf.predict(dates), color= 'red', label= 'RBF model') # plotting the line made by the RBF kernel 
    plt.plot(dates,svr_lin.predict(dates), color= 'green', label= 'Linear model') # plotting the line made by linear kernel 
    plt.plot(dates,svr_poly.predict(dates), color= 'blue', label= 'Polynomial model') # plotting the line made by polynomial kernel 
    plt.xlabel('Date') 
    plt.ylabel('Price') 
    plt.title('Support Vector Regression') 
    plt.legend() 
    plt.show() 

    return svr_rbf.predict(x)[0], svr_lin.predict(x)[0], svr_poly.predict(x)[0] 

get_data('table.csv') # calling get_data method by passing the csv file to it 

predicted_price = predict_price(dates, prices, 29) 

我分了代碼轉換成細胞jupyter和
predicted_price
似乎掛起In [*]:

+0

'plt.show()'會導致身材保持打開狀態,並停止代碼執行弗羅姆的其餘部分。你可能想使用'plt.show(block = False)'。或者在腳本的最後一次調用'plt.show()'。 – DavidG

+0

我不應該看到彈出的圖嗎? –

+0

我嘗試將plt.show()移動到最後,仍然遇到同一個攤位 –

回答

1

的代碼很好。 SVR需要時間進行計算。瞭解更多here。你可以用線性迴歸來嘗試下面的代碼。

與進口

from sklearn import linear_model 

# defining the linear regression model 
linear_mod = linear_model.LinearRegression() 

# fitting the data points in the model 
linear_mod.fit(dates, prices) 

plt.scatter(dates, prices, color='black', label='Data') 
# plotting the initial datapoints 
plt.plot(dates, linear_mod.predict(dates), color='red', 
      label='Linear model')