簡體   English   中英

使用Python構建預測模型。 投影始終為0

[英]Building a predictive model with Python. Projections are always 0

我正在查看我在網上找到的一些房地產數據。 我用Python建立了一個模型; 所有代碼如下所示。 所有數據均來自紐約市,例如郵政編碼,手數,商業,住宅和其他一些指標。 我正在嘗試基於各種因素來預測可能開發商業房地產地段的“目標”變量。

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# Load data
train = pd.read_csv('C:\\Users\\Excel\\Desktop\\train.csv')
test = pd.read_csv('C:\\Users\\Excel\\Desktop\\test.csv')

df = pd.concat([train,test],axis=0) #Combined both Train and Test Data set
df.shape
pd.set_option('display.max_columns', None)


# fill in NANs.
df = df.fillna(0)

print('Data frame:', df)

# convert to numbers
df = df.select_dtypes(include=[np.number])


# Get all the columns from the dataframe.
columns = df.columns.tolist()
# Filter the columns to remove ones we don't want to use in the training
columns = [c for c in columns if c not in ['target']]


# Store the variable we'll be predicting on.
target = 'target'
train['target'] = 0
# Generate the training set.  Set random_state to be able to replicate results.
train = df.sample(frac=0.8, random_state=1)
# Select anything not in the training set and put it in the testing set.
test = df.loc[~df.index.isin(train.index)]
# Print the shapes of both sets.
print('Training set shape:', train.shape)
print('Testing set shape:', test.shape)
# Initialize the model class.
lin_model = LinearRegression()
# Fit the model to the training data.
lin_model.fit(train[columns], train[target])


# Generate our predictions for the test set.
lin_predictions = lin_model.predict(test[columns])
print('Predictions:', lin_predictions)
# Compute error between our test predictions and the actual values.
lin_mse = mean_squared_error(lin_predictions, test[target])
print('Computed error:', lin_mse)

這行拋出一個錯誤:

lin_model.fit(train[columns], train[target])

這是錯誤消息:

KeyError: 'target'

基本上,“目標”字段不會出現在此處: train[target]

即使我將字段添加進去,投影也總是0! 我一定缺少簡單的東西,但是我不確定。

我從這里開始跟隨示例,但是使用了完全不同的數據集。

https://microsoft.github.io/sql-ml-tutorials/python/rentalprediction/step/2.html

使用此代碼片段,我可以了解因素的“功能重要性”。

# Create a new matplotlib figure
fig = plt.figure()
ax = fig.add_subplot()

viz = FeatureImportances(GradientBoostingClassifier(), ax=ax)
viz.fit(X, y)
viz.poof()

在此處輸入圖片說明

我想添加評論,但還不能。 為什么要使用線性回歸來預測我認為是二元變量的變量? 請改用物流。 這條線又是什么: columns = [c for c in columns if c not in ['target']] ['target']來自哪里? 另一件事, train['target'] = 0將整個列設置為0,即使您要重新分配列值,也應該使用df.loc方法。 這就是為什么將所有預測值都設為零的原因,因為目標是您的因變量,並且所有值都設置為0。

如果輸入代碼,則訓練集中的所有樣本的輸出/目標均為0

train['target'] = 0

然后,該算法將學習到,無論模型中具有什么功能,預測都應該始終為0。

回顧為什么需要將其設置為0。這行似乎是不必要的。 嘗試刪除該行並運行模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM