繁体   English   中英

为什么我会收到“模块”不可调用错误?

[英]Why do I get the 'module' not callable error?

我对python有点陌生。 我正在尝试对加速度数据进行统计分析。

我正在尝试用我的数据做一个 PCA 图。 但我收到以下错误:

File ~\OneDrive - ##\##\Pyth\untitled0.py:41 in <module>
    fig = plt.figure(figsize = (8,8))

TypeError: 'module' object is not callable

我不知道我的脚本有什么问题。 也许有人知道。

这是我的 csv 的一部分(最后一列是一个类 (1,2,3):

-0.875,-0.143,0.516,2.0
-0.844,-0.143,0.548,2.0
-0.844,-0.143,0.516,2.0
-0.844,-0.143,0.548,2.0
-0.844,-0.143,0.548,2.0
-0.844,-0.143,0.516,2.0
-0.844,-0.143,0.548,2.0

这是我的代码:

import pandas as pd
import os
from sklearn.preprocessing import StandardScaler
import matplotlib as plt
from sklearn.decomposition import PCA

## find dir
os.chdir(r'C:\Users\##\OneDrive - ##\##\Pyth\HAR2')
os.getcwd()


## read csv
df = pd.read_csv('dataframe_0.csv', delimiter=',', names = ['x','y','z','target'])


features = ['x', 'y', 'z']

# Separating out the features
x = df.loc[:, features].values

# Separating out the target
y = df.loc[:,['target']].values

# Standardizing the features
x = StandardScaler().fit_transform(x)


pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x)
principalDf = pd.DataFrame(data = principalComponents
             , columns = ['principal component 1', 'principal component 2'])

finalDf = pd.concat([principalDf, df[['target']]], axis = 1)

fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(1,2,3) 
ax.set_xlabel('Principal Component 1', fontsize = 15)
ax.set_ylabel('Principal Component 2', fontsize = 15)
ax.set_title('2 component PCA', fontsize = 20)

targets = [1,2,3]
colors = ['r', 'g', 'b']
for target, color in zip(targets,colors):
    indicesToKeep = finalDf['target'] == target
    ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']
               , finalDf.loc[indicesToKeep, 'principal component 2']
               , c = color
               , s = 50)
ax.legend(targets)
ax.grid()

MatPlotLib ( [MatPlotLib]: API Reference ) 导入语句应为:

import matplotlib.pyplot as plt

或者

from matplotlib import pyplot as plt

这种情况的美妙之处(这使得错误更难被发现)是一个巧合。 图形名称同时存在于:

  • matplotlib - 作为一个模块

  • matplotlib.pyplot - 作为一个函数(这是需要的)

例子:

 >>> import matplotlib as mpl >>> >>> mpl <module 'matplotlib' from 'e:\\Work\\Dev\\VEnvs\\py_pc064_03.09_test0\\lib\\site-packages\\matplotlib\\__init__.py'> >>> mpl.figure <module 'matplotlib.figure' from 'e:\\Work\\Dev\\VEnvs\\py_pc064_03.09_test0\\lib\\site-packages\\matplotlib\\figure.py'> >>> >>> >>> import matplotlib.pyplot as plt >>> >>> plt <module 'matplotlib.pyplot' from 'e:\\Work\\Dev\\VEnvs\\py_pc064_03.09_test0\\lib\\site-packages\\matplotlib\\pyplot.py'> >>> plt.figure <function figure at 0x000001C31C139D30>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM