【问题标题】:Why is my code generating a scalar array error despite providing reshape array command?尽管提供了 reshape array 命令,为什么我的代码会生成标量数组错误?
【发布时间】:2020-11-13 09:11:18
【问题描述】:

我是一名 Python 新手。在编写代码时,从一门在线课程中,我遇到了与数组相关的错误。我复查了多次,但仍然找不到错误。

代码如下:

boston_dataset = load_boston()

data = pd.DataFrame(data=boston_dataset.data, columns=boston_dataset.feature_names)
features = data.drop(['INDUS','AGE'], axis=1)
log_prices = np.log(boston_dataset.target)

target = pd.DataFrame(log_prices, columns=['PRICE'])

property_stats = features.mean().values.reshape(1,11)

regr = LinearRegression().fit(features, target) 
regr.predict(features) 

fitted_vals = regr.predict(features) 
MSE = mean_squared_error(target, fitted_vals) 
RMSE = np.sqrt(MSE)


CRIME_IDX = 0
ZN_IDX = 1
CHAS_IDX = 2
NOX_IDX = 3
RM_IDX = 4
DIS_IDX = 5
RAD_IDX = 6
TAX_IDX = 7
PTRATIO_IDX = 8
B_IDX = 9
LSTAT_IDX = 10

def get_log_estimate(nr_rooms,
                    students_per_classroom,
                    next_to_river=False,
                    high_confidence=True):
    property_stats[0][RM_IDX] = nr_rooms
    property_stats[0][PTRATIO_IDX] = students_per_classroom
    
    log_estimate = regr.predict(property_stats[0][0])
    
    if next_to_river:
        property_stats[0][CHAS_IDX] = 1
    else:
            property_stats[0][CHAS_IDX] = 0
            
    if high_confidence:
        upper_bound = log_estimate + 2*RMSE
        lower_bound = log_estimate - 2*RMSE
        interval = 95
    else:
            upper_bound = log_estimate + RMSE
            lower_bound = log_estimate - RMSE
            interval = 68
            
    return log_estimate, upper_bound, lower_bound, interval
While running these lines of code, I am having this error:

"

ValueError: Expected 2D array, got scalar array instead:
array=3.6135235573122535.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

"

我在下面的代码行中调用了

get_log_estimate(5, 20)

但仍然出现同样的错误。

【问题讨论】:

    标签: python arrays pandas data-science scalar


    【解决方案1】:

    我也是数据科学的新手,所以我不确定答案。但是在你的代码的第 8 行,我建议你试试这个:regr.predict([features])

    【讨论】:

    • 感谢您的宝贵建议,但不幸的是,它不适用于我的代码
    猜你喜欢
    • 1970-01-01
    • 2018-06-12
    • 2021-06-21
    • 2017-01-08
    • 2015-05-10
    • 1970-01-01
    • 2021-11-05
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多