我想在我的資料框的第一列中找到回歸系數的數量。我的代碼提出
TypeError: object of type 'numpy.float64' has no len()
from sklearn.linear_model import LinearRegression
df = pd.read_csv("master.csv")
# Drop redundant features
X = df.drop(['suicides/100k pop', 'country-year', 'suicides_no'], axis=1)
y = df['suicides/100k pop']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression(n_jobs=4, normalize=True, copy_X=True)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(f"There are {len(model.coef_[0])} regression coefficients:")
print(model.coef_[0])
X_train
print(type(X_train))
> <class 'scipy.sparse.csr.csr_matrix'>
y_train
print(type(y_train))
> <class 'pandas.core.series.Series'>
追溯:
> --------------------------------------------------------------------------- TypeError Traceback (most recent call
> last) /tmp/ipykernel_6232/341058392.py in <module>
> 1 # Check number of and values of coefficients
> ----> 2 print(f"There are {len(model.coef_[0])} regression coefficients:")
> 3 print(model.coef_[0])
>
> TypeError: object of type 'numpy.float64' has no len()
uj5u.com熱心網友回復:
當您使用 [0] 時,您是在“呼叫”一個特定的值。它是一個數字,因此它沒有 len() 這是一個字串函式。
如果你想列印出 len 使用:
len(model.coef_)
uj5u.com熱心網友回復:
恐怕你在建模部分聽起來很困惑,這會導致你以編程方式請求無效的東西。
我想在我的資料框的第一列中找到回歸系數的數量。
哪有這回事。根據定義,線性回歸中的系數數等于變數數,即陣列/資料框中的列數;因此,資料框中的第一列始終只有一個系數。
同樣,您的print宣告:
print(f"There are {len(model.coef_[0])} regression coefficients:")
是不正確的; 您的回歸系數的數量將為len(model.coef_). model.coef_[0]只是這些系數中的第一個;它永遠是一個數字,這就是為什么len(model.coef_[0])總是會產生一個(預期的和合理的)錯誤(單個數字沒有任何長度)。
使用檔案中提供的玩具示例演示上述內容:
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) # 2 variables/columns
# y = 1 * x_0 2 * x_1 3
y = np.dot(X, np.array([1, 2])) 3
model = LinearRegression()
model.fit(X, y)
在這里,我們有 2 個變數(列)X,所以它將是
len(model.coef_)
# 2
和
X.shape[1] == len(model.coef_)
# True
根據定義。
(請注意,截距不包含在系數中;它與 分開回傳model.intercept_)
因此,為了實際獲得您在print宣告中似乎要求的內容,您應該將宣告更改為
print(f"There are {len(model.coef_)} regression coefficients:")
print(model.coef_)
請記住,報告的數字不包括攔截。
我示例中的上述命令將產生正確的結果:
There are 2 regression coefficients:
[1. 2.]
如果您還想包括完整的攔截項,您應該添加:
print("and the intercept term is:")
print(model.intercept_)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/316936.html
