2016-12-24 83 views
0

我有日期溫度數據集,按日期排序,我需要在scikit-learn中使用[SVR] [1]預測未來溫度。scikit學習svr的時間序列預測

我堅持選擇XY的培訓和X測試 設置。例如,如果我想在時間t預測Y然後我需要 訓練集包含了X & Yt-1, t-2, ..., t-N其中N是用於在t預測Y以前的天數。

我該怎麼做?

這是它。

df=daily_temp1 
# define function for create N lags 
def create_lags(df, N): 
    for i in range(N): 
     df['datetime' + str(i+1)] = df.datetime.shift(i+1) 
     df['dewpoint' + str(i+1)] = df.dewpoint.shift(i+1) 
     df['humidity' + str(i+1)] = df.humidity.shift(i+1) 
     df['pressure' + str(i+1)] = df.pressure.shift(i+1) 
     df['temperature' + str(i+1)] = df.temperature.shift(i+1) 
    df['vism' + str(i+1)] = df.vism.shift(i+1) 
    df['wind_direcd' + str(i+1)] = df.wind_direcd.shift(i+1) 
    df['wind_speed' + str(i+1)] = df.wind_speed.shift(i+1) 
    df['wind_direct' + str(i+1)] = df.wind_direct.shift(i+1) 

    return df 

# create 10 lags 
df = create_lags(df,10) 


# the first 10 days will have missing values. can't use them. 
df = df.dropna() 

# create X and y 
y = df['temperature'] 
X = df.iloc[:, 9:] 

# Train on 70% of the data 
train_idx = int(len(df) * .7) 

# create train and test data 
X_train, y_train, X_test, y_test = X[:train_idx], y[:train_idx], X[train_idx:], y[train_idx:] 


# fit and predict 
clf = SVR() 
clf.fit(X_train, y_train) 

clf.predict(X_test) 

回答

1

下面是構建特徵矩陣X作爲LAG1簡單的解決方案 - lagN其中LAG1是前幾天的溫度和lagN是溫度N天前。

# create fake temperature 
df = pd.DataFrame({'temp':np.random.rand(500)}) 

# define function for create N lags 
def create_lags(df, N): 
    for i in range(N): 
     df['Lag' + str(i+1)] = df.temp.shift(i+1) 
    return df 

# create 10 lags 
df = create_lags(df,10) 

# the first 10 days will have missing values. can't use them. 
df = df.dropna() 

# create X and y 
y = df.temp.values 
X = df.iloc[:, 1:].values 

# Train on 70% of the data 
train_idx = int(len(df) * .7) 

# create train and test data 
X_train, y_train, X_test, y_test = X[:train_idx], y[:train_idx], X[train_idx:], y[:train_idx] 

# fit and predict 
clf = SVR() 
clf.fit(X_train, y_train) 

clf.predict(X_test) 
+0

謝謝!我試圖讓它符合我的目的,因爲我還需要除了以前的溫度之外的其他功能,但我一直有錯誤TypeError:float()參數必須是字符串或數字 –

+0

scikit學習不能處理字符串。您必須將所有字符串轉換爲數字。如果你有一個熊貓數據框,使用'pd.get_dummies'。如果您嚴格使用sklearn,請在預處理模塊中使用「LabelBinarizer」。 –

+0

我已經改變了弦的,現在我有浮動和日期時間數據類型 –