GVKun编程网logo

类型错误:'numpy.float32' 对象不可调用(python中对象不可调用)

1

如果您想了解类型错误:'numpy.float32'对象不可调用的相关知识,那么本文是一篇不可错过的文章,我们将对python中对象不可调用进行全面详尽的解释,并且为您提供关于'AttributeEr

如果您想了解类型错误:'numpy.float32' 对象不可调用的相关知识,那么本文是一篇不可错过的文章,我们将对python中对象不可调用进行全面详尽的解释,并且为您提供关于'AttributeError:'numpy.float32'对象没有属性'ctypes'、DJANGO:类型错误“需要一个整数”并且类型错误“bool”对象不可调用、Julia Flux 错误:MethodError:没有方法匹配 *(::Chain{Tuple{Conv{2,4,typeof(identity),Array{Float32,4},Array{Float32,1}},var"#13#15" }}, ::Int64)、numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32的有价值的信息。

本文目录一览:

类型错误:'numpy.float32' 对象不可调用(python中对象不可调用)

类型错误:'numpy.float32' 对象不可调用(python中对象不可调用)

如何解决类型错误:''numpy.float32'' 对象不可调用

我不明白为什么我会收到这个错误。谁能帮我吗?我是 python 的初学者,这个错误困扰着我。该函数基本上用于连接组件标记,但我发现使用 python 的 max() 函数很难获得最大值,如下所示。

一定是我遗漏了一些小错误。任何形式的帮助将不胜感激。

import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.morphology import disk

%matplotlib inline

def ccl(img):

    ##### first pass #####
    curr_label = 1;
    img = np.array(img)
    labels = np.array(img)

    # storing label conversions
    label_conv = []
    label_conv.append([])
    label_conv.append([])

    count = 0
    for i in range(1,len(img)):
        for j in range(1,len(img[0])):

            if img[i][j] > 0:
                label_x = int(labels[i][j - 1])
                label_y = int(labels[i - 1][j])

                if label_x > 0:
                    # both x and y have a label
                    if label_y > 0:

                        if not label_x == label_y:
                            labels[i][j] = min(label_x,label_y)
                            #print("i: ",i,"j: ",j)
                            #print("label_x: ",type(label_x),"label_y: ",type(label_y))
                            max_label = max(label_x,label_y)

                            if max_label not in label_conv[0]:
                                label_conv[0].append(max(label_x,label_y))
                                label_conv[1].append(min(label_x,label_y))

                            elif max(label_x,label_y) in label_conv[0]:
                                ind = label_conv[0].index(max(label_x,label_y))

                                if label_conv[1][ind] > min(label_x,label_y):
                                    l = label_conv[1][ind]
                                    label_conv[1][ind] = min(label_x,label_y)
                                    while l in label_conv[0] and count < 100:
                                        count += 1
                                        ind = label_conv[0].index(l)
                                        l = label_conv[1][ind]
                                        label_conv[1][ind] = min(label_x,label_y)

                                    label_conv[0].append(l)
                                    label_conv[1].append(min(label_x,label_y))

                        else:
                            labels[i][j] = label_y
                    # only x has a label
                    else:
                        labels[i][j] = label_x

                # only y has a label
                elif label_y > 0:
                    labels[i][j] = label_y

                # neither x nor y has a label
                else:
                    labels[i][j] = curr_label
                    curr_label += 1

    ##### second pass #####
    count = 1
    for idx,val in enumerate(label_conv[0]):

        if label_conv[1][idx] in label_conv[0] and count < 100:
            count += 1
            ind = label_conv[0].index(label_conv[1][idx])
            label_conv[1][idx] = label_conv[1][ind]

    for i in range(1,len(labels)):
        for j in range(1,len(labels[0])):

            if labels[i][j] in label_conv[0]:
                ind = label_conv[0].index(labels[i][j])
                labels[i][j] = label_conv[1][ind]

    return labels


img = cv2.imread("..\\\\disks.png",0)

img2 = cv2.bitwise_not(img,mask = None)

SE = disk(25)
img_eroded = cv2.erode(img2,SE) #Erode the image

plt.figure(figsize=(16,12))
plt.subplot(1,1,1)
plt.imshow(img_eroded,cmap="gray")
plt.title(''Image'')
plt.xticks([])
plt.yticks([])

labels = ccl(img_eroded)

print("size: ",labels)

plt.figure(figsize=(16,cmap="gray")
plt.title(''Image'')
plt.xticks([])
plt.yticks([])

这是我得到的错误输出。

    TypeError                                 Traceback (most recent call last)
<ipython-input-83-04f5b3d4d1e5> in <module>
    103 plt.yticks([])
    104 
--> 105 labels = ccl(img_eroded)
    106 
    107 print("size: ",labels)

<ipython-input-83-04f5b3d4d1e5> in ccl(img)
     34                             #print("i: ",j)
     35                             #print("label_x: ",type(label_y))
---> 36                             max_label = max(label_x,label_y)
     37 
     38                             if max_label not in label_conv[0]:

TypeError: ''numpy.float32'' object is not callable
enter code here

解决方法

这看起来您之前已将 max 指定为指向 numpy int 的变量。然后,当您尝试调用 max() 函数时,它会尝试调用您创建的变量。

清除命名空间,然后再次运行。

'AttributeError:'numpy.float32'对象没有属性'ctypes'

'AttributeError:'numpy.float32'对象没有属性'ctypes'

如何解决''AttributeError:''numpy.float32''对象没有属性''ctypes''

我试图根据从左上,右上等顺序排列的点来计算图像的尺寸。因此,我以后可以执行4点透视变换和变形。 (使用opencvSharp和numpy.net)

我想从中获取最大宽度和最大高度作为整数 ndarray,但此时它抛出 “ Python.Runtime.PythonException:''AttributeError:''numpy.float32''对象没有属性''ctypes''

不太确定如何作为一个新手来解决这个问题,这是我第一次使用此OpencvSharp和numpy.NET。

ndarray rect = OrderPoints(pts);
            // 4 Points order from top-left top- right etc..
            ndarray tL = rect[0],tR = rect[1],bR = rect[2],bL = rect[3];
      

                           // width of new image
            ndarray w1 = ((bR[0] - bL[0]) * (bR[0] - bL[0])) + ((bR[1] - bL[1]) * (bR[1] - bL[1])); // quietly throws exception here 
            ndarray w2 = ((tR[0] - tL[0]) * (tR[0] - tL[0])) + ((tR[1] - tL[1]) * (tR[1] - tL[1]));

             w1 = np.sqrt(w1);
             w2 = np.sqrt(w2);

            // get max width as an interger

             int[] width1 = w1.GetData<int>(); // same error blows up here
            int[] width2 = w2.GetData<int>();

            int maxWidth = Math.Max(width1[0],width2[0]);
          


            ndarray h1 = ((tR[0] - bR[0]) * (tR[0] - bR[0])) + ((tR[1] - bR[1]) * (tR[1] - bR[1]));
            ndarray h2 = (tL[0] - bL[0]) * (tL[0] - bL[0]) + (tL[1] - bL[1]) * (tL[1] - bL[1]);

           h1 = np.sqrt(h1);
            h2 = np.sqrt(h2);

            int[] height = h1.GetData<int>();
            int[] height2 = h2.GetData<int>();


            int maxHeight = Math.Max(height[0],height2[0]);

            // make a top - down view
            var dst = np.array(
                  new[,] {
                     { 0,0},{maxWidth - 1,0 },maxHeight - 1 },{0,maxHeight - 1 }
                      });
            
              var rectPts = rect.GetData<Point2f>();
               var dstarray = dst.GetData<Point2f>();


             Mat matr = Cv2.GetPerspectiveTransform(rectPts,dstarray);
            Mat output = new Mat();
            Cv2.WarpPerspective(image,output,matr,new Size(maxWidth,maxHeight)); 

            return output;

解决方法

我设法提出了一个解决方案,方法是使用repr属性返回数据字符串,然后将其解析为float并转换为Int。

int width1 = (int)float.Parse(w1.repr);
int width2 = (int)float.Parse(w2.repr);

DJANGO:类型错误“需要一个整数”并且类型错误“bool”对象不可调用

DJANGO:类型错误“需要一个整数”并且类型错误“bool”对象不可调用

如何解决DJANGO:类型错误“需要一个整数”并且类型错误“bool”对象不可调用

我是 DJANGO 的新手,编码经验有限。

我正在学习一个涉及构建购物车的 DJANGO 教程。我收到:前端需要一个类型错误整数;以及当我尝试手动创建购物车时,管理门户中不可调用的类型错误 bool 对象。

我认为教程中的代码有点过时,但我有限的经验意味着我尝试的任何更改都会导致更多错误。

代码如下: #追溯

import pandas as pd
import matplotlib.pyplot as plt  
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib as mpl


# Set plotting style
plt.style.use(''seaborn-white'')

dz=[]
z0 = np.array([ 1.,3.,11.,8.,7.,6.,5.,4.,10.,1.,])
dz.append(z0)

z1 =[ 5.,2.,0.,]

dz.append(z1)

z2 =[ 15.,]

dz.append(z2)

_zpos = z0*0


xlabels = pd.Index([''X01'',''X02'',''X03'',''X04''],dtype=''object'')

ylabels = pd.Index([''Y01'',''Y02'',''Y03'',''Y04'',''Y05'',''Y06'',''Y07''],dtype=''object'')

x = np.arange(xlabels.shape[0])

y = np.arange(ylabels.shape[0])

x_M,y_M = np.meshgrid(x,y,copy=False)

fig = plt.figure(figsize=(7,7))
ax = fig.add_subplot(111,projection=''3d'')
ax.set_Box_aspect((1,3.5,1))
plt.gca().view_init(15,20)

ls = mpl.colors.LightSource(azdeg=30,altdeg=10)

# Making the intervals in the axes match with their respective entries
ax.w_xaxis.set_ticks(x + 0.5/2.)
ax.w_yaxis.set_ticks(y + 0.5/2.)

# Renaming the ticks as they were before
ax.w_xaxis.set_ticklabels(xlabels)
ax.w_yaxis.set_ticklabels(ylabels)

# Labeling the 3 dimensions
ax.set_xlabel(''X label'')
ax.set_ylabel(''Y label'')
ax.set_zlabel(''Z label'')

# Choosing the range of values to be extended in the set colormap
values = np.linspace(0.2,x_M.ravel().shape[0])

# Selecting an appropriate colormap

colors = [''#FFC04C'',''blue'',''#3e9a19'',''#599be5'',''#bf666f'',''#a235bf'',''#848381'',''#fb90d6'',''#fb9125'']

# Increase the number of segment to 3 by changing the X in ''range(X)'' to 3.
for i in range(3):
    ax.bar3d(x_M.ravel(),y_M.ravel(),_zpos,dx=0.2,dy=0.1,dz=dz[i],color=colors[i],lightsource=ls)
    _zpos += dz[i]
 

Segment1_proxy         = plt.Rectangle((0,0),1,fc="#FFC04C")   
Segment2_proxy         = plt.Rectangle((0,fc="blue")
Segment3_proxy         = plt.Rectangle((0,fc="#3e9a19")

ax.legend([Segment1_proxy,Segment2_proxy,Segment3_proxy],[''Segment1'',''Segment2'',''Segment3''
         ])



plt.show()

settings.py

Internal Server Error: /cart/cart/
Traceback (most recent call last):
  File "C:\\Users\\nia\\Desktop\\Pharma-mart\\env\\lib\\site-packages\\django\\core\\handlers\\exception.py",line 47,in inner
    response = get_response(request)
  File "C:\\Users\\nia\\Desktop\\Pharma-mart\\env\\lib\\site-packages\\django\\core\\handlers\\base.py",line 181,in _get_response
    response = wrapped_callback(request,*callback_args,**callback_kwargs)
  File "C:\\Users\\nia\\Desktop\\Pharma-mart\\pharmamart\\cart\\views.py",line 13,in cart_home
    cart_obj = cart.objects.new_or_get(request)
  File "C:\\Users\\nia\\Desktop\\Pharma-mart\\pharmamart\\cart\\models.py",line 11,in new_or_get
    qs = self.getqueryset().filter(id=cart_id)
AttributeError: ''CartManager'' object has no attribute ''getqueryset''
[27/Mar/2021 10:49:42] "GET /cart/cart/ HTTP/1.1" 500 71680

#cart/admin.py

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 

DEBUG = True

ALLOWED_HOSTS = []


# Application deFinition

INSTALLED_APPS = [
    ''django.contrib.admin'',''django.contrib.auth'',''django.contrib.contenttypes'',''django.contrib.sessions'',''django.contrib.messages'',''django.contrib.staticfiles'',''store'',''patients'',''ckeditor'',''cart'',]

MIDDLEWARE = [
    ''django.middleware.security.SecurityMiddleware'',''django.contrib.sessions.middleware.SessionMiddleware'',''django.middleware.common.CommonMiddleware'',''django.middleware.csrf.CsrfViewMiddleware'',''django.contrib.auth.middleware.AuthenticationMiddleware'',''django.contrib.messages.middleware.MessageMiddleware'',''django.middleware.clickjacking.XFrameOptionsMiddleware'',]

ROOT_URLconf = ''pharmamart.urls''

TEMPLATES = [
    {
        ''BACKEND'': ''django.template.backends.django.DjangoTemplates'',''Dirs'': [BASE_DIR / ''''],''APP_Dirs'': True,''OPTIONS'': {
            ''context_processors'': [
                ''django.template.context_processors.debug'',''django.template.context_processors.request'',''django.contrib.auth.context_processors.auth'',''django.contrib.messages.context_processors.messages'',],},]

Wsgi_APPLICATION = ''pharmamart.wsgi.application''


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    ''default'': {
        ''ENGINE'': ''django.db.backends.sqlite3'',''NAME'': BASE_DIR / ''db.sqlite3'',}
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        ''NAME'': ''django.contrib.auth.password_validation.UserAttributeSimilarityValidator'',{
        ''NAME'': ''django.contrib.auth.password_validation.MinimumLengthValidator'',{
        ''NAME'': ''django.contrib.auth.password_validation.CommonPasswordValidator'',{
        ''NAME'': ''django.contrib.auth.password_validation.NumericPasswordValidator'',]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = ''en-us''

TIME_ZONE = ''UTC''

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS,JavaScript,Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = ''/static/''
MEDIA_URL =''/media/''

MEDIA_ROOT = os.path.join(BASE_DIR,''media'')

STATICFILES_Dirs = [
    BASE_DIR / "static",]
LOGIN_REDIRECT_URL = ""
logoUT_REDIRECT_URL = ""  

购物车/models.py

from django.contrib import admin
from .models import cart

admin.site.register(cart)

购物车/views.py

from django.db import models
from django.conf import settings
from store.models import product,customer
from django.contrib.auth.models import User


#User = settings.AUTH_USER.MODEL# if included it throws an error ''settings not defined''
class CartManager(models.Manager):
    def new_or_get(self,request):
        cart_id = request.session.get("cart_id",None)
        qs = self.getqueryset().filter(id=cart_id)
        if qs.count()==1:
            new_obj = False
            cart_obj = qs.first()
            if request.user.is_authenticated() and cart_obj.user is None:
                cart_obj-save()
            else:
                cart_obj = cart.objects.new(user=request.user)
                new_obj = True
                request.session[''cart_id''] = cart_obj.id
            return cart_obj,new_obj

    def new(self,user = None):
        user_obj = None
        if user is not None:
            if user is authenticated():
                user_obj = user
        return self.model.objects.create(user=user_obj)

class cart(models.Model):
    user = models.ForeignKey(User,related_name = "user",blank = True,null=True,on_delete=models.CASCADE)
    product = models.ManyToManyField(''store.product'')
    total = models.DecimalField(default = 0.0,max_digits = 50.00,decimal_places = 2)
    updated = models.DateTimeField(auto_Now=True)
    timestamp = models.DateTimeField(auto_Now=True)
    objects = CartManager()

    def __str__(self):
        return str(self.id)

购物车/urls.py

from django.shortcuts import render
from django.contrib import admin
from django.contrib.auth.models import User
from .models import cart

# Create your views here.
#def cart_create(user=None):
#   cart_obj = cart.objects.create(user = None)
#   print(''New Cart created'')
#   return cart_obj

def cart_home(request):
    cart_obj = cart.objects.new_or_get(request)
    return render(request,"home.html",{})

感谢任何有关修改代码以显示我的错误的帮助。

交流

Julia Flux 错误:MethodError:没有方法匹配 *(::Chain{Tuple{Conv{2,4,typeof(identity),Array{Float32,4},Array{Float32,1}},var

Julia Flux 错误:MethodError:没有方法匹配 *(::Chain{Tuple{Conv{2,4,typeof(identity),Array{Float32,4},Array{Float32,1}},var"#13#15" }}, ::Int64)

如何解决Julia Flux 错误:MethodError:没有方法匹配 *(::Chain{Tuple{Conv{2,4,typeof(identity),Array{Float32,4},Array{Float32,1}},var"#13#15" }}, ::Int64)?

using Flux
using Flux:@functor
function ConvBlock(inc,out,k,s,p,use_act)
    return Chain(
        Conv((k,k),inc=>out,stride = s,pad = p,bias=true),use_act ? x -> leakyrelu.(x,0.2) : x -> x
    )
end
mutable struct DenseResidualBlock
    residual_beta
    blocks
end

@functor DenseResidualBlock

function DenseResidualBlock(inc,c = 32,residual_beta = 0.2)
    blocks = []
    for i in 0:4
        in_channels = inc + c*i
        out_channels = i<=3 ? c : inc
        use_act = i<=3 ? true : false
        push!(blocks,ConvBlock(in_channels,out_channels,3,1,use_act))
    end

    return DenseResidualBlock(residual_beta,blocks)
end

function (m::DenseResidualBlock)(x) 
    new_inputs = x
    local out,new_inputs
    for block in m.blocks
        out = block(new_inputs)
        new_inputs = cat(new_inputs,dims=3)
    end
    return m.residual_beta * out + x
end

当我运行这个

drb = DenseResidualBlock(64)

我收到此错误 错误:方法错误:没有方法匹配 *(::Chain{Tuple{Conv{2,4,typeof(identity),Array{Float32,4},1}},var"#13#15"}},::Int64)

解决方法

试试

function DenseResidualBlock(inc;c = 32,residual_beta = 0.2)

代替

function DenseResidualBlock(inc,c = 32,residual_beta = 0.2)
,

当使用两个参数调用 DenseResidualBlock 时,您的代码中存在歧义。它可以直接构造 DenseResidualBlock 结构,也可以使用 DenseResidualBlock(inc,c) 调用 residual_beta = 0.2。如果您对 DenseResidualBlock(inc; c = 32,residual_beta = 0.2) 使用关键字参数,则会消除这种歧义。

错误消息表明,在 in_channels = inc + c*i 行,参数 c 不是预期的数字,而是无法乘以数字的 Flux.Chain

numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32

numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32

我试图读一个简单的空间分隔的文件用pandas read_csv方法。然而,熊猫似乎没有服从我的dtype参数。也许我错误地指定它?

我已经把我对read_csv的一些复杂的调用归结为这个简单的测试用例。我实际上在我的“真实”场景中使用转换器的参数,但我删除了为简单。

下面是我的ipython会话:

>>> cat test.out
a b
0.76398 0.81394
0.32136 0.91063
>>> import pandas
>>> import numpy
>>> x = pandas.read_csv('test.out',dtype={'a': numpy.float32},delim_whitespace=True)
>>> x
         a        b
0  0.76398  0.81394
1  0.32136  0.91063
>>> x.a.dtype
dtype('float64')

我也试过这个用numpy.int32或numpy.int64的dtype。这些选择导致异常:

AttributeError: 'nonetype' object has no attribute 'dtype'

我假设AttributeError是因为pandas不会自动尝试转换/截断浮点值为整数?

我在一个32位的机器上运行32位版本的Python。

>>> !uname -a
Linux ubuntu 3.0.0-13-generic #22-Ubuntu SMP Wed Nov 2 13:25:36 UTC 2011 i686 i686 i386 GNU/Linux
>>> import platform
>>> platform.architecture()
('32bit','ELF')
>>> pandas.__version__
'0.10.1'

解决方法

0.10.1并不真正支持float32

见http://pandas.pydata.org/pandas-docs/dev/whatsnew.html#dtype-specification

你可以在0.11这样做:

# dont' use dtype converters explicity for the columns you care about
# they will be converted to float64 if possible,or object if they cannot
df = pd.read_csv('test.csv'.....)

#### this is optional and related to the issue you posted ####
# force anything that is not a numeric to nan
# columns are the list of columns that you are interesetd in
df[columns] = df[columns].convert_objects(convert_numeric=True)


    # astype
    df[columns] = df[columns].astype('float32')

see http://pandas.pydata.org/pandas-docs/dev/basics.html#object-conversion

Its not as efficient as doing it directly in read_csv (but that requires

我已经确认用0.11-dev,这个DOES工作(对32位和64位,结果是一样的)

In [5]: x = pd.read_csv(StringIO.StringIO(data),dtype={'a': np.float32},delim_whitespace=True)

In [6]: x
Out[6]: 
         a        b
0  0.76398  0.81394
1  0.32136  0.91063

In [7]: x.dtypes
Out[7]: 
a    float32
b    float64
dtype: object

In [8]: pd.__version__
Out[8]: '0.11.0.dev-385ff82'

In [9]: quit()
vagrant@precise32:~/pandas$ uname -a
Linux precise32 3.2.0-23-generic-pae #36-Ubuntu SMP Tue Apr 10 22:19:09 UTC 2012 i686 i686 i386 GNU/Linux

 some low-level changes)

我们今天的关于类型错误:'numpy.float32' 对象不可调用python中对象不可调用的分享就到这里,谢谢您的阅读,如果想了解更多关于'AttributeError:'numpy.float32'对象没有属性'ctypes'、DJANGO:类型错误“需要一个整数”并且类型错误“bool”对象不可调用、Julia Flux 错误:MethodError:没有方法匹配 *(::Chain{Tuple{Conv{2,4,typeof(identity),Array{Float32,4},Array{Float32,1}},var"#13#15" }}, ::Int64)、numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32的相关信息,可以在本站进行搜索。

本文标签: