简体   繁体   English

如果在 anaconda 提示符下运行没有问题,但是 ModuleNotFoundError: No module named 'keras' in Spyder

[英]It's OK if run in anaconda prompt but ModuleNotFoundError: No module named 'keras' in Spyder

I run a project downloaded from GitHub .我运行了一个从GitHub下载的项目。 Strangely, if I run it in anaconda prompt, it is OK, but if I run it in Spyder, it emerges(I installed anaconda and Sypder in win10, and keras installed as well):奇怪的是,如果我在anaconda提示符下运行它,它是可以的,但是如果我在Spyder中运行它,它就会出现(我在win10中安装了anaconda和Sypder,并且也安装了keras):

runfile('E:/MySourceCode/neural_image_captioning-master-oarriaga/src/train.py', wdir='E:/MySourceCode/neural_image_captioning-master-oarriaga/src') Reloaded modules: evaluator, generator Traceback (most recent call last): runfile('E:/MySourceCode/neural_image_captioning-master-oarriaga/src/train.py', wdir='E:/MySourceCode/neural_image_captioning-master-oarriaga/src') 重载模块:评估器、生成器回溯(最近一次调用):

File "", line 1, in runfile('E:/MySourceCode/neural_image_captioning-master-oarriaga/src/train.py', wdir='E:/MySourceCode/neural_image_captioning-master-oarriaga/src') File "", line 1, in runfile('E:/MySourceCode/neural_image_captioning-master-oarriaga/src/train.py', wdir='E:/MySourceCode/neural_image_captioning-master-oarriaga/src')

File "D:\\ProgramData\\Anaconda3\\lib\\site-packages\\spyder\\utils\\site\\sitecustomize.py", line 710, in runfile execfile(filename, namespace)文件“D:\\ProgramData\\Anaconda3\\lib\\site-packages\\spyder\\utils\\site\\sitecustomize.py”,第 710 行,在运行文件 execfile(filename, namespace) 中

File "D:\\ProgramData\\Anaconda3\\lib\\site-packages\\spyder\\utils\\site\\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace)文件“D:\\ProgramData\\Anaconda3\\lib\\site-packages\\spyder\\utils\\site\\sitecustomize.py”,第 101 行,在 execfile exec(compile(f.read(), filename, 'exec'), namespace)

File "E:/MySourceCode/neural_image_captioning-master-oarriaga/src/train.py", line 3, in from keras.callbacks import CSVLogger文件“E:/MySourceCode/neural_image_captioning-master-oarriaga/src/train.py”,第 3 行,来自 keras.callbacks import CSVLogger

ModuleNotFoundError: No module named 'keras' ModuleNotFoundError:没有名为“keras”的模块

train.py is as follows: train.py 如下:

from evaluator import Evaluator
from generator import Generator
from keras.callbacks import CSVLogger
from keras.callbacks import ModelCheckpoint
from keras.callbacks import ReduceLROnPlateau
from models import NIC
from data_manager import DataManager

num_epochs = 50  
batch_size = 64 
root_path = '../datasets/IAPR_2012/'
captions_filename = root_path + 'IAPR_2012_captions.txt'
data_manager = DataManager(data_filename=captions_filename,
                            max_caption_length=30,
                            word_frequency_threshold=2,
                            extract_image_features=False,
                            cnn_extractor='inception',
                            image_directory=root_path + 'iaprtc12/',
                            split_data=True,
                            dump_path=root_path + 'preprocessed_data/')

data_manager.preprocess()
print(data_manager.captions[0])
print(data_manager.word_frequencies[0:20])

preprocessed_data_path = root_path + 'preprocessed_data/'
generator = Generator(data_path=preprocessed_data_path,
                      batch_size=batch_size)

num_training_samples =  generator.training_dataset.shape[0]
num_validation_samples = generator.validation_dataset.shape[0]
print('Number of training samples:', num_training_samples)
print('Number of validation samples:', num_validation_samples)

model = NIC(max_token_length=generator.MAX_TOKEN_LENGTH,
            vocabulary_size=generator.VOCABULARY_SIZE,
            rnn='gru',
            num_image_features=generator.IMG_FEATS,
            hidden_size=128,
            embedding_size=128)

model.compile(loss='categorical_crossentropy',
              optimizer = 'adam',
              metrics=['accuracy'])

print(model.summary())
print('Number of parameters:', model.count_params())

training_history_filename = preprocessed_data_path + 'training_history.log'
csv_logger = CSVLogger(training_history_filename, append=False) 
model_names = ('../trained_models/IAPR_2012/' +
               'iapr_weights.{epoch:02d}-{val_loss:.2f}.hdf5')
model_checkpoint = ModelCheckpoint(model_names,                 #Callback
                                   monitor='val_loss',
                                   verbose=1,
                                   save_best_only=False,
                                   save_weights_only=False)

reduce_learning_rate = ReduceLROnPlateau(monitor='val_loss', factor=0.1,  #Callback
                                         patience=5, verbose=1)

callbacks = [csv_logger, model_checkpoint, reduce_learning_rate]

model.fit_generator(generator=generator.flow(mode='train'), 
                    steps_per_epoch=int(num_training_samples / batch_size),
                    epochs=num_epochs,
                    verbose=1,
                    callbacks=callbacks,
                    validation_data=generator.flow(mode='validation'),
                    validation_steps=int(num_validation_samples / batch_size))

evaluator = Evaluator(model, data_path=preprocessed_data_path,
                      images_path=root_path + 'iaprtc12/')

evaluator.display_caption()

Is there anything wrong with setting in Spyder?在 Spyder 中设置有什么问题吗? And in anoconda prompt, is there any difference while pip keras before "activate tensorflow" and after " activate tensorflow"?Many thanks.在 anoconda 提示中,“激活 tensorflow”之前和“激活 tensorflow”之后的 pip keras 有什么区别吗?非常感谢。

It might be an issue with your keras installation.这可能是您的 keras 安装问题。 If you already tried installing it with:如果您已经尝试安装它:

$ conda install keras

and it didn't work, I suggest uninstalling it and then reinstalling it with pip3:它没有用,我建议卸载它,然后用 pip3 重新安装它:

$ conda uninstall keras
$ sudo pip3 install keras

You can check if it works by importing keras in Spyder:您可以通过在 Spyder 中导入 keras 来检查它是否有效:

> import keras

The error may be that you are using the wrong environment.错误可能是您使用了错误的环境。 In anaconda navigator make sure you are in the right environment before you launch spyder在 anaconda navigator 中,在启动 spyder 之前确保您处于正确的环境中

If you're using conda then it's best to install everything with conda if you can, rather than mixing it up with pip.如果您使用的是 conda,那么最好尽可能使用 conda 安装所有内容,而不是将其与 pip 混用。

The purpose of conda is that you can create multiple environments which each have different packages installed, or different versions of the same package, without causing conflicts, because only one environment is activated at one time. conda 的目的是你可以创建多个环境,每个环境都安装了不同的包,或者同一个包的不同版本,而不会引起冲突,因为一次只激活一个环境。 Those packages include Python itself, and Spyder.这些包包括 Python 本身和 Spyder。 So to use a Python module with Spyder you need to create a conda environment containing both the module and Spyder:因此,要在 Spyder 中使用 Python 模块,您需要创建一个包含模块和 Spyder 的 conda 环境:

conda create -n mykerasenv keras spyder

Then to use that environment you need to activate it before starting Spyder:然后要使用该环境,您需要在启动 Spyder 之前激活它:

activate mykerasenv # (or 'source activate mykerasenv' if that doesn't work)
spyder

Depending on your conda/Anaconda installation you may be able to do the same thing through the Anaconda Navigator and/or Anaconda Start menu shortcuts, but the command line version should always work.根据您的 conda/Anaconda 安装,您可以通过 Anaconda Navigator 和/或 Anaconda Start 菜单快捷方式执行相同的操作,但命令行版本应始终有效。

If you do need to use pip to install a package that you can't get via conda, you need to do that after creating and activating the conda environment, so that pip installs it in the correct place.如果确实需要使用 pip 安装无法通过 conda 获取的包,则需要在创建并激活 conda 环境后执行此操作,以便 pip 将其安装在正确的位置。

If you've tried installing things into your root conda environment (ie without first creating a new environment with conda create and then activating it) then you may be best off uninstalling Anaconda and starting from scratch.如果您已经尝试将东西安装到您的根 conda 环境中(即没有先使用conda create创建一个新环境然后激活它),那么您最好卸载 Anaconda 并从头开始。 If any of this is confusing I recommend having another read of the conda docs .如果其中任何一个令人困惑,我建议再次阅读conda 文档

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

相关问题 ModuleNotFoundError:anaconda spyder 中没有名为“pyLDAvis”的模块 - ModuleNotFoundError: No module named 'pyLDAvis' in anaconda spyder ModuleNotFoundError:在anaconda 3,spyder中未发生名为“ sklearn”的模块错误 - ModuleNotFoundError: No module named 'sklearn' error occurred in anaconda 3, spyder ModuleNotFoundError:尽管 Anaconda 导航器上安装了 ffmpeg,但 Spyder 上没有名为“ffmpeg”的模块 - ModuleNotFoundError: No module named 'ffmpeg' on Spyder although ffmpeg is installed on Anaconda navigator Spyder 崩溃:ModuleNotFoundError:没有名为“prompt_toolkit.enums”的模块 - Spyder Crash: ModuleNotFoundError: No module named 'prompt_toolkit.enums' ModuleNotFoundError:为anaconda3安装Keras时,没有名为“ tensorflow”的模块 - ModuleNotFoundError: No module named 'tensorflow' while installing Keras for anaconda3 ModuleNotFoundError:没有名为“keras”的模块 - ModuleNotFoundError: No module named 'keras' ModuleNotFoundError:没有名为 keras 的模块 - ModuleNotFoundError: No module named keras ModuleNotFoundError :没有名为“keras”的模块? - ModuleNotFoundError : No module named 'keras'? 模块在 Anaconda 提示符下工作,但在 Spyder 中不工作 - A module is working in Anaconda prompt, but not in Spyder ModuleNotFoundError:spyder 中没有名为“pip”的模块 - ModuleNotFoundError: No module named 'pip' in spyder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM