python中import的引用機制引起的坑

cppshooter發表於2018-09-14

最近在擼Scikit-Learn的程式碼,想載入點Seaborn的資料訓練模型,簡單的一句seaborn.load_dataset(“)都編譯通不過。

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.linear_model import LinearRegression
# 選擇模型
model = LinearRegression(fit_intercept=True)
# 整理資料
iris = sns.load_dataset(`iris`)
rng = np.random.RandomState(42)
x = 10* rng.rand(50)
y = 2*x - 1 + rng.randn(50)
X = x[:, np.newaxis]
#擬合資料
model.fit(X,y)
#預測
xfit = np.linspace(-1,11)
Xfit = xfit[:, np.newaxis]
yfit = model.predict(Xfit)
plt.scatter(x,y)
plt.plot(xfit, yfit)
plt.show()
PS D:sanyepythonDEMO> python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import seaborn as sns
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:sanyepythonDEMOseaborn.py", line 5, in <module>
    iris = sns.load_dataset(`iris`)
AttributeError: module `seaborn` has no attribute `load_dataset`

慌了,一臉懵。仔細檢查發現專案路徑下有一個seaborn.py檔案,改名一起恢復平靜。汗~
這個完全是因為python匯入模組的搜尋路徑以及優先順序問題引起的。import匯入模組搜尋順序:先當前路徑,再環境變數路徑。


相關文章