본문 바로가기

Contact English

【Python】 파이썬 주요 트러블슈팅 [21-40]

 

파이썬 주요 트러블슈팅 [21-40]

 

추천글 : 【Python】  파이썬 목차 


 

21. rpy2.rinterface_lib.embedded.RRuntimeError: Error in library(ggplot2) : there is no package called 'ggplot2'

 (package) 해결책 : R로 접속한 뒤 install.packages('ggplot2')

22. ERROR: pip's dependecy resolver does not currently take into account all the packages that are installed. This behavior is the source of the following dependency conflicts. stlearn 0.4.5 requires scikit-image>=0.19.2, but you have scikit-image 0.18.3 which is incompatible.

(package) 문제점 발생 : pip install stlearn==0.4.5를 할 때 

(package) 해결책 : pip install stlearn==0.4.5 --no-deps

⑶ 레퍼런스 : https://stackoverflow.com/questions/12759761/pip-force-install-ignoring-dependencies/12759996#12759996

 

pip: force install ignoring dependencies

Is there any way to force install a pip python package ignoring all it's dependencies that cannot be satisfied? (I don't care how "wrong" it is to do so, I just need to do it, any logic and reason...

stackoverflow.com

 

 

23. ImportError: cannot import name '_tsne_fix' from 'scanpy.tools'

 (package) 해결책 : scanpy==1.9.1scanpy==1.7.2로 downgrade

 

 

24. ValueError: m has more than 2 dimensions

(grammar) 문제점 : numpy.corrcoef를 사용하는 과정에서 두 입력 벡터 인자 내 각 성분이 np.ndarray여서 문제가 됐음

(grammar) 해결책 : 각 입력 벡터 인자 내 모든 성분을 스칼라로 바꾸었음. 이때 ~.item()을 사용

 

 

25. TypeError: Descriptors cannot not be created directly. If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0. If you cannot immediately regenerate your protos, some other possible workarounds are: 1. Downgrade the protobuf package to 3.20.x or lower. 2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).

(package) 해결책 : protobuf==3.19.1으로 downgrade 한 뒤 anaconda를 껐다가 켜서 재실행

레퍼런스 

 

Changes announced May 6, 2022

Changes announced for Protocol Buffers on May 6, 2022.

protobuf.dev

 

 

26. TypeError: only length-1 arrays can be converted to Python scalars

 (grammar) 문제점 : 함수는 특정 값을 예상하는데 인자로 배열을 넘긴 경우

 (grammar) 해결책 : 배열 내 각 원소별로 해당 함수를 사용

⑶ 해결책 예시

 

for i in range(len(top)):
    top[i] = -math.log10(top[i])

 

 

27. UnicodeDecodeError: 'cp949' codec can't decode bytes in position : illegal multibyte sequence

⑴ (grammar) 문제점 발생 : f = open("example.txt", 'r')

⑵ 원인 : python3부터는 ANSI로 encoding된 것만 읽을 수 있고 UTF-8은 별도의 encoding 방법을 지시해야 함

(grammar) 해결책 : f = open("example.txt", 'r', encoding = 'utf-8')

 

 

28. TypeError: can only concatenate str (not "int") to str

(grammar) 문제점 : int 형 변수를 str 형 변수에 concatenation 하려고 한 경우

⑵ 문제점 예시 : a = 3; print('a = ' + a)

(grammar) 해결책 : int 형 변수를 str() 함수로 형 변환

⑷ 해결책 예시 : a = 3; print('a = ' + str(a))

 

 

29. _csv.Error: field larger than field limit (131072)

(grammar) 해결책

 

import sys
import csv

csv.field_size_limit(sys.maxsize)

 

레퍼런스 

 

_csv.Error: field larger than field limit (131072)

I have a script reading in a csv file with very huge fields: # example from http://docs.python.org/3.3/library/csv.html?highlight=csv%20dictreader#examples import csv with open('some.csv', newline...

stackoverflow.com

 

 

30. AttributeError: type object 'scipy.spatial.transform.rotation.Rotation' has no attribute 'from_dcm'

 (package) 해결책 : scipy==1.5.2로 downgrade

레퍼런스 

 

AttributeError: 'scipy.spatial.transform.rotation.Rotation' object has no attribute 'as_dcm' · Issue #22 · benjiebob/SMALify

Hi, I switched it to try running off of a Stanford image, as per the Github instructions. I ended up with this error: (smalifythis) s@s-To-be-filled-by-O-E-M:~/SMALify$ python smal_fitter/optimize_...

github.com

 

 

31. ERROR: Could not install packages due to an OSError: [WinError 225] Operation did not complete successfully because the file contains a virus or potentially unwanted software ... ERROR: Could not install packages due to an OSError: [WinError 225] Operation did not complete successfully because the file contains a virus or potentially unwanted software

⑴ (others) 원인 : 보안 프로그램으로 인해 패키지 설치가 차단됨

(others) 해결방법 1. 다음과 같이 문제가 되는 보안 프로그램을 종료  

 

Solved: Operation Did Not Complete Successfully [Virus/PUP]

Can’t open a file because Windows 10 detects a virus in the file location: “Operation did not complete successfully:” Here are the methods to fix it.

softwarekeep.com

(others) 해결방법 2. 다른 컴퓨터를 통해 해당 패키지를 다운받고, 그 패키지를 설치가 안 되는 그 컴퓨터에 직접 옮기기

 

 

32. error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' 

 (grammar) 문제점 : 디렉토리를 잘못 입력하여 cv2.imread로 이미지를 제대로 입력하지 못한 경우

 

 

33. ERROR: Could not find a version that satisfies the requirement git (from versions: none). ERROR: No matching distribution found for git

(package) 문제점 : git이 설치돼 있지 않음

(package) 해결방법

 

conda install git

 

 

34. AttributeError: 'dict' object has no attribute 'iteritems', 'iterkeys' or 'itervalues'

(grammar) 문제점 : Python3부터는 .iteritems(), .iterkeys(), .itervalues() 함수가 제거됐기 때문에 이러한 에러가 발생함

(grammar) 해결방법 : .items() 함수로 대신 사용

 

 

35. The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70. If you want to use the NVIDIA GeForce RTX 3090 GPU with PyTorch, please check the instruction.

(package) 문제점 : 현재 RTX3090은 CUDA11 이상을 사용하여야 함

(package) 해결방법

 

pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 -f https://download.pytorch.org/whl/torch_stable.html

 

 

36. ImportError: DLL load failed while importing utilsextension: The specified module could not be found.

 (package) 문제점 : 파이썬 3.8 버전에서는 scanpy와 연결된 pytables 부분에 문제가 있음

(package) 해결방법

 

conda install -c conda-forge pytables

 

 

37. AttributeError: module 'tensorflow.keras.layers' has no attribute 'RandomContrast'

(grammar) 문제점 : tensorflow version 2.11.0tf.keras.layers.RandomContrast와 같이 쓰지만, tensorflow version 2.4tf.keras.layers.experimental.preprocessing.RandomContrast와 같이 씀

 

 

38. NotImplementedError: Cannot convert a symbolic Tensor

 (package) 해결방법 : numpy==1.19.5로 downgrade

 

 

39. ModuleNotFoundError: No module named 'pydatset'

(grammar) 문제점 : 다음 코드를 실행할 때 에러가 발생

 

from pydatset.cifar10 import get_CIFAR10_data

 

 (grammar) 해결방법 : 대신 다음 코드를 직접 실행시킴 (출처)

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cPickle as pickle
import numpy as np
import os


def get_CIFAR10_data(cifar10_dir, num_training=49000, num_validation=1000, num_test=1000):
    '''
    Load the CIFAR-10 dataset from disk and perform preprocessing to prepare
    it for the neural net classifier.
    '''
    # Load the raw CIFAR-10 data
    X_train, y_train, X_test, y_test = load(cifar10_dir)

    # Subsample the data
    mask = range(num_training, num_training + num_validation)
    X_val = X_train[mask]
    y_val = y_train[mask]
    mask = range(num_training)
    X_train = X_train[mask]
    y_train = y_train[mask]
    mask = range(num_test)
    X_test = X_test[mask]
    y_test = y_test[mask]

    X_train = X_train.astype(np.float64)
    X_val = X_val.astype(np.float64)
    X_test = X_test.astype(np.float64)

    # Transpose so that channels come first
    X_train = X_train.transpose(0, 3, 1, 2)
    X_val = X_val.transpose(0, 3, 1, 2)
    X_test = X_test.transpose(0, 3, 1, 2)

    mean_image = np.mean(X_train, axis=0)
    std = np.std(X_train)

    X_train -= mean_image
    X_val -= mean_image
    X_test -= mean_image

    X_train /= std
    X_val /= std
    X_test /= std

    return {
        'X_train': X_train, 'y_train': y_train,
        'X_val': X_val, 'y_val': y_val,
        'X_test': X_test, 'y_test': y_test,
        'mean': mean_image, 'std': std
    }


def load_CIFAR_batch(filename):
    ''' load single batch of cifar '''
    with open(filename, 'r') as f:
        datadict = pickle.load(f)
        X = datadict['data']
        Y = datadict['labels']
        X = X.reshape(10000, 3, 32, 32).transpose(0, 2, 3, 1).astype("float")
        Y = np.array(Y)
        return X, Y


def load(ROOT):
    ''' load all of cifar '''
    xs = []
    ys = []
    for b in range(1, 6):
        f = os.path.join(ROOT, 'data_batch_%d' % (b, ))
        X, Y = load_CIFAR_batch(f)
        xs.append(X)
        ys.append(Y)
    Xtr = np.concatenate(xs)
    Ytr = np.concatenate(ys)
    del X, Y
    Xte, Yte = load_CIFAR_batch(os.path.join(ROOT, 'test_batch'))
    return Xtr, Ytr, Xte, Yte

 

 

40. ModuleNotFoundError: No module named 'cPickle'

(grammar) 문제점 : Python3에서는 'pickle'로 변경되었음

(grammar) 해결방법

 

pip install pickle

 

입력 : 2022.05.09 22:23