简体   繁体   English

TypeError:ufunc'add'不包含签名匹配类型为dtype('的循环

[英]TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')

I am trying to normalize energy use data using weather data with Pandas. 我正在尝试使用Pandas的天气数据来规范能源使用数据。 I need my code to read a csv with weather data, calculate some numbers using that data, and sum up those numbers based on the month of the year. 我需要我的代码来读取包含天气数据的csv,使用该数据计算一些数字,并根据一年中的月份总结这些数字。 Here is my code so far: 到目前为止,这是我的代码:

    import pandas as pd
    import statsmodels.api as sm
    import statsmodels.formula.api as smf

    data = pd.read_csv("C:\\Users\\mparlo\\Documents\\Python\\NEWYORK - NEWYORK.csv", header=None)
    data.columns = ["Month", "Day", "Year", "Temperature"]

    ndays = len(data)
    data["hdd"] = ""
    data["cdd"] = ""

    t_bp = 65

    for i in range(0,ndays):
        if data.at[i,"Temperature"] > t_bp:
            data.at[i,"hdd"] = 0
            data.at[i,"cdd"] = data.at[i,"Temperature"]-t_bp
        elif data.at[i,"Temperature"] < t_bp:
            data.at[i,"hdd"] = t_bp - data.at[i,"Temperature"]
            data.at[i,"cdd"] = 0

    data

    hddjan = data.loc[data["Month"] == 1, "hdd"].sum()
    cddjan = data.loc[data["Month"] == 1, "cdd"].sum()

    hddfeb = data.loc[data["Month"] == 2, "hdd"].sum()
    cddfeb = data.loc[data["Month"] == 2, "cdd"].sum()

    hddmar = data.loc[data["Month"] == 3, "hdd"].sum()
    cddmar = data.loc[data["Month"] == 3, "cdd"].sum()

    hddapr = data.loc[data["Month"] == 4, "hdd"].sum()

The data is formatted such that Months are numbered 1-12. 数据被格式化,以使月份编号为1-12。

The code works up until the last line here, where I try to sum anything past Month 3/March. 该代码一直工作到这里的最后一行,在这里我尝试总结3月3日之后的所有内容。 I get this error: 我收到此错误:

> ---------------------------------------------------------------------------
>TypeError                                 Traceback (most recent call last)
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\nanops.py in 
>f(values, axis, skipna, **kwds)
>    118                 else:
>--> 119                     result = alt(values, axis=axis, skipna=skipna, >**kwds)
>    120             except Exception:
>
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\nanops.py in >nansum(values, axis, skipna)
>    292         dtype_sum = np.float64
>--> 293     the_sum = values.sum(axis, dtype=dtype_sum)
>    294     the_sum = _maybe_null_out(the_sum, axis, mask)
>
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\core\_methods.py >in _sum(a, axis, dtype, out, keepdims)
>     31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
>---> 32     return umr_sum(a, axis, dtype, out, keepdims)
>     33 
>
>TypeError: ufunc 'add' did not contain a loop with signature matching types >dtype('<U32') dtype('<U32') dtype('<U32')
>
>During handling of the above exception, another exception occurred:
>
>TypeError                                 Traceback (most recent call last)
><ipython-input-5-beeced82f47d> in <module>()
>      8 cddmar = data.loc[data["Month"] == 3, "cdd"].sum()
>      9 
>---> 10 hddapr = data.loc[data["Month"] == 4, "hdd"].sum()
>
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py >in stat_func(self, axis, skipna, level, numeric_only, **kwargs)
>   6340                                       skipna=skipna)
>   6341         return self._reduce(f, name, axis=axis, skipna=skipna,
>-> 6342                             numeric_only=numeric_only)
>   6343 
>   6344     return set_function_name(stat_func, name, cls)
>
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in >_reduce(self, op, name, axis, skipna, numeric_only, filter_type, **kwds)
>   2379                                           'numeric_only.'.format(name))
>   2380             with np.errstate(all='ignore'):
>-> 2381                 return op(delegate, skipna=skipna, **kwds)
>   2382 
>  2383         return delegate._reduce(op=op, name=name, axis=axis, >skipna=skipna,
>
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\nanops.py in >_f(*args, **kwargs)
>     60             try:
>     61                 with np.errstate(invalid='ignore'):
>---> 62                     return f(*args, **kwargs)
>     63             except ValueError as e:
>     64                 # we want to transform an object array
>
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\nanops.py in >f(values, axis, skipna, **kwds)
>    120             except Exception:
>    121                 try:
>--> 122                     result = alt(values, axis=axis, skipna=skipna, >**kwds)
>    123                 except ValueError as e:
>    124                     # we want to transform an object array
>
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\nanops.py in >nansum(values, axis, skipna)
>    291     elif is_timedelta64_dtype(dtype):
>    292         dtype_sum = np.float64
>--> 293     the_sum = values.sum(axis, dtype=dtype_sum)
>    294     the_sum = _maybe_null_out(the_sum, axis, mask)
>    295 
>
>~\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\core\_methods.py >in _sum(a, axis, dtype, out, keepdims)
>     30 
>     31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
>---> 32     return umr_sum(a, axis, dtype, out, keepdims)
>     33 
>     34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False):
>
>TypeError: ufunc 'add' did not contain a loop with signature matching types >dtype('<U32') dtype('<U32') dtype('<U32')

If anyone has any idea why the sum is working for only the first three months, any help is appreciated. 如果有人知道为什么这笔金额仅在头三个月内有效,我们将不胜感激。

[EDIT: here is a link to the data: https://docs.google.com/spreadsheets/d/1nUD1wS_ZEWCyjLFdeL14_HaYq6NBjP1VtHN9gvgPD14/edit?usp=sharing ] [编辑:这是数据的链接: https : //docs.google.com/spreadsheets/d/1nUD1wS_ZEWCyjLFdeL14_HaYq6NBjP1VtHN9gvgPD14/edit?usp=sharing ]

While your issue is unclear without data, consider adjusting your code to pandas data manipulation methods such as conditional .loc , groupby , or pivot_table instead of looping through all rows and assigning values by index and manually creating month sums. 尽管没有数据您的问题仍然不清楚,但请考虑将代码调整为适用于pandas数据处理方法(例如,条件.locgroupbypivot_table而不是遍历所有行并按索引分配值并手动创建月份和。 In fact with an adjusted approach, you will be able to see the extent of your data, if it cuts off after March or not. 实际上,如果调整后的方法,无论3月以后是否中断,您都可以看到数据的范围。

...
import calendar

data = pd.read_csv(r'C:\Users\mparlo\Documents\Python\NEWYORK - NEWYORK.csv', header=None)\
                  .set_axis(["Month", "Day", "Year", "Temperature"], axis=1, inplace=False)

t_bp = 65

data.loc[data['Temperature'] > t_bp, 'hdd'] = 0
data.loc[data['Temperature'] <= t_bp, 'hdd'] = t_bp - data['Temperature']

data.loc[data['Temperature'] > t_bp, 'cdd'] = data['Temperature'] - t_bp
data.loc[data['Temperature'] <= t_bp, 'cdd'] = 0

data['Location'] = 'New York'
data['MonthAbbrev'] = data['Month'].apply(lambda x: calendar.month_abbr[x])

# LONG FORMAT
agg_data = data.group_by(['MonthAbbrev']).agg({'hhd':'sum', 'cdd':'sum'})

# WIDE FORMAT
agg_data = data.pivot_table(index=['Location'], values=['hdd', 'cdd'],
                            columns='MonthAbbrev', aggfunc='sum')

UFuncTypeError:ufunc 'clip' 不包含具有签名匹配类型的循环(dtype(' <u32’), dtype(‘<u32’), dtype(‘<u32’)) -> dtype(' <u32’)< div><div id="text_translate"><p> 我使用 Deep Pavlov 框架与 Bert 分类器一起工作,只是因为我需要预测人员的语言是俄语。 基本上,我正在尝试解决多类分类问题。 根据 Deep Pavlov,我们可以轻松地更改配置文件上的一些配置。 我拿了这个配置文件<a href="https://github.com/deepmipt/DeepPavlov/blob/master/deeppavlov/configs/classifiers/rusentiment_convers_bert.json" rel="nofollow noreferrer">https://github.com/deepmipt/DeepPavlov/blob/master/deeppavlov/configs/classifiers/rusentiment_convers_bert.json</a>并训练它,结果我花了大约 13 个小时才完成它我的 model 过拟合。</p><p> 我做了一些改变,尤其是这些:</p><pre> "weight_decay_rate": 0.001, "learning_rate_drop_patience": 1, "learning_rate_drop_div": 2.0, "load_before_drop": True, "min_learning_rate": 1e-03, "attention_probs_keep_prob": 0.5, "hidden_keep_prob": 0.5,</pre><p> 另外,我增加了批量大小,之前是 16:</p><pre> "batch_size": 32</pre><p> 并添加了一些指标:</p><pre> "log_loss", "matthews_correlation",</pre><p> 还将validation_patience更改为1并添加了tensorboard func</p><pre> "validation_patience": 1, "tensorboard_log_dir": "logs/",</pre><p> 就是这样。 这些是我对 model 所做的所有更改,当我尝试训练我的 model 时,它给了我以下错误:</p><pre> UFuncTypeError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds) 60 try: ---&gt; 61 return bound(*args, **kwds) 62 except TypeError: 15 frames UFuncTypeError: ufunc 'clip' did not contain a loop with signature matching types (dtype('&lt;U32'), dtype('&lt;U32'), dtype('&lt;U32')) -&gt; dtype('&lt;U32') During handling of the above exception, another exception occurred: UFuncTypeError Traceback (most recent call last) &lt;__array_function__ internals&gt; in clip(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/numpy/core/_methods.py in _clip_dep_invoke_with_casting(ufunc, out, casting, *args, **kwargs) 83 # try to deal with broken casting rules 84 try: ---&gt; 85 return ufunc(*args, out=out, **kwargs) 86 except _exceptions._UFuncOutputCastingError as e: 87 # Numpy 1.17.0, 2019-02-24 UFuncTypeError: ufunc 'clip' did not contain a loop with signature matching types (dtype('&lt;U32'), dtype('&lt;U32'), dtype('&lt;U32')) -&gt; dtype('&lt;U32')</pre><p> 起初,我认为它与数据集有关,但是,我没有更改我的数据集,并且在我第一次训练这个 model 时它已经运行。 </p></div></u32’)<></u32’),> - UFuncTypeError: ufunc ‘clip’ did not contain a loop with signature matching types (dtype(‘<U32’), dtype(‘<U32’), dtype(‘<U32’)) -> dtype(‘<U32’)

UFuncTypeError:ufunc 'matmul' 不包含具有签名匹配类型的循环(dtype(' <u32'), dtype('<u32')) -> dtype(' <u32') - streamlit< div><div id="text_translate"><pre> #Linear Regression Model @st.cache(allow_output_mutation=True) def linearRegression(X_train, X_test, y_train, y_test): model = LinearRegression() model.fit(X_train,y_train) score = model.score(X_test, y_test)*100 return score, model</pre><hr><pre> #User input for the model def user_input(): bedrooms = st.slider("Bedrooms: ", 1,15) bathrooms = st.text_input("Bathrooms: ") sqft_living = st.text_input("Square Feet: ") sqft_lot = st.text_input("Lot Size: ") floors = st.text_input("Number Of Floors: ") waterfront = st.text_input("Waterfront? For Yes type '1', For No type '0': ") view = st.slider("View (A higher score will mean a better view): ", 0,4) condition = st.slider("House Condition (A higher score will mean a better condition): ", 1,5) yr_built = st.text_input("Year Built: ") yr_reno = st.text_input("A Renovated Property? For Yes type '1', For No type '0': ") zipcode = st.text_input("Zipcode (5 digit): ") year_sold = st.text_input("Year Sold: ") month_sold = st.slider("Month Sold: ", 1,12) user_input_prediction = np.array([bedrooms,bathrooms,sqft_living, sqft_lot,floors,waterfront,view,condition,yr_built,yr_reno,zipcode,year_sold,month_sold]).reshape(1,-1) return(user_input_prediction)</pre><hr><pre> #Main function if(st.checkbox("Start a Search")): user_input_prediction = user_input() st.write('error1') pred = model.predict(user_input_prediction) st.write('error2') if(st.button("Submit")): st.text("success")</pre><p> 我正在使用 Streamlit 构建一个接受用户输入的 ML model。 在我的主要 function 中,它返回错误UFuncTypeError: ufunc 'matmul' did not contain a loop with signature matching types (dtype('&lt;U32'), dtype('&lt;U32')) -&gt; dtype('&lt;U32') and trace返回pred = model.predict(user_input_prediction)主 function 将打印出 error1 但不会打印 error2</p></div></u32')></u32'),> - UFuncTypeError: ufunc 'matmul' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32') - Streamlit

TypeError: ufunc 'add' 不包含签名匹配类型 dtype(' <u1') dtype('<u1') dtype('<u1')< div><div id="text_translate"><p> 我是 Python 用户的初学者。 当我尝试在下面编写代码时发生错误</p><pre>import numpy as np np.array(['a', 'b', 'c']) + np.array(['d','e', 'f'])</pre><pre> TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('&lt;U1') dtype('&lt;U1') dtype('&lt;U1')</pre><p> 所以我尝试设置dtype = '&lt;U1' ,但它没有用</p><pre>import numpy as np np.array(['a', 'b', 'c'], dtype='&lt;U1') + np.array(['d','e', 'f'], dtype='&lt;U1')</pre><p> 如何无错误地连接那些 np.arrays ?</p></div></u1')> - TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')

UFuncTypeError: 无法从 dtype(' <u32') to dtype('float32') with casting rule 'same_kind'?< div><div id="text_translate"><p> 我正在尝试创建一个 ML model 来对石头、纸和剪刀的手势图像进行分类。 我不断收到如下错误消息:</p><blockquote><p> UFuncTypeError:无法使用转换规则“same_kind”将 ufunc 'multiply' output 从 dtype('&lt;U32') 转换为 dtype('float32')</p></blockquote><p> 这是我的代码:</p><pre> import tensorflow as to from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow import keras from tensorflow.keras import layers:wget --no-check-certificate \ https.//dicodingacademy.blob.core.windows.net/picodiploma/ml_pemula_academy/rockpaperscissors.zip -O /tmp/rockpaperscissors,zip import zipfile.os local_zip = '/tmp/rockpaperscissors.zip' zip_ref = zipfile,ZipFile(local_zip. 'r') zip_ref.extractall('/tmp') zip_ref.close(),pip install split_folders import split_folders as SF sf,ratio('/tmp/rockpaperscissors/rps-cv-images', output="/tmp/rockpaperscissors/data".seed=1337, ratio=(.8. .2)) root_path = '/tmp/rockpaperscissors/data' train_path = os,path.join(root_path. 'train') validation_path = os,path,join(root_path, 'val') train_datagen = ImageDataGenerator( rescale = "none", rotation_range = 30, vertical_flip = True. horizontal_flip = True, zoom_range = 0.1, width_shift_range = 0.1, height_shift_range = 0.1, shear_range = 0,2, fill_mode = 'nearest') test_datagen = ImageDataGenerator( rescale = "none", rotation_range = 30, vertical_flip = True. horizontal_flip = True, zoom_range = 0.1, width_shift_range = 0.1, height_shift_range = 0.1, shear_range = 0.2, fill_mode = 'nearest') train_generator = train_datagen,flow_from_directory( train_path, target_size=(150, 150). batch_size=32, class_mode='categorical') validation_generator = test_datagen,flow_from_directory( validation_path, target_size=(150, 150). batch_size=32. class_mode='categorical') model = keras.Sequential() model,add(layers,Conv2D(32, (5,5), activation='relu', input_shape=(150. 150. 3))) model,add(layers.MaxPooling2D(2. 2)) model,add(layers,Conv2D(64, (3.3). activation='relu')) model,add(layers.MaxPooling2D(2. 2)) model,add(layers,Conv2D(128, (3.3). activation='relu')) model,add(layers.MaxPooling2D(2. 2)) model,add(layers,Conv2D(256, (3.3). activation='relu')) model,add(layers.MaxPooling2D(2. 2)) model,add(layers,Conv2D(512, (3.3). activation='relu')) model,add(layers.MaxPooling2D(2. 2)) model.add(layers.Flatten()) model,add(layers.Dense(512. activation='relu')) model,add(layers.Dense(3. activation='softmax')) model.summary() loss_fn = keras.losses,SparseCategoricalCrossentropy() model,compile(loss=loss_fn. optimizer=RMSprop(), metrics=['accuracy']) model,fit( train_generator, steps_per_epoch=54, epochs=22, validation_data=validation_generator, validation_steps=13, verbose=2)</pre><p> 这是我的代码的链接: <a href="https://colab.research.google.com/drive/1stBPFyuIQTU_2LqDSHLlrLOSSBeuYLNT#scrollTo=r3Q3w-Tm6tnX" rel="nofollow noreferrer">Rock Paper Scissors Classifier</a>谢谢!</p></div></u32')> - UFuncTypeError: Cannot cast ufunc 'multiply' output from dtype('<U32') to dtype('float32') with casting rule 'same_kind'?

暂无
暂无

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

相关问题 UFuncTypeError:ufunc 'clip' 不包含具有签名匹配类型的循环(dtype(' <u32’), dtype(‘<u32’), dtype(‘<u32’)) -> dtype(' <u32’)< div><div id="text_translate"><p> 我使用 Deep Pavlov 框架与 Bert 分类器一起工作,只是因为我需要预测人员的语言是俄语。 基本上,我正在尝试解决多类分类问题。 根据 Deep Pavlov,我们可以轻松地更改配置文件上的一些配置。 我拿了这个配置文件<a href="https://github.com/deepmipt/DeepPavlov/blob/master/deeppavlov/configs/classifiers/rusentiment_convers_bert.json" rel="nofollow noreferrer">https://github.com/deepmipt/DeepPavlov/blob/master/deeppavlov/configs/classifiers/rusentiment_convers_bert.json</a>并训练它,结果我花了大约 13 个小时才完成它我的 model 过拟合。</p><p> 我做了一些改变,尤其是这些:</p><pre> "weight_decay_rate": 0.001, "learning_rate_drop_patience": 1, "learning_rate_drop_div": 2.0, "load_before_drop": True, "min_learning_rate": 1e-03, "attention_probs_keep_prob": 0.5, "hidden_keep_prob": 0.5,</pre><p> 另外,我增加了批量大小,之前是 16:</p><pre> "batch_size": 32</pre><p> 并添加了一些指标:</p><pre> "log_loss", "matthews_correlation",</pre><p> 还将validation_patience更改为1并添加了tensorboard func</p><pre> "validation_patience": 1, "tensorboard_log_dir": "logs/",</pre><p> 就是这样。 这些是我对 model 所做的所有更改,当我尝试训练我的 model 时,它给了我以下错误:</p><pre> UFuncTypeError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds) 60 try: ---&gt; 61 return bound(*args, **kwds) 62 except TypeError: 15 frames UFuncTypeError: ufunc 'clip' did not contain a loop with signature matching types (dtype('&lt;U32'), dtype('&lt;U32'), dtype('&lt;U32')) -&gt; dtype('&lt;U32') During handling of the above exception, another exception occurred: UFuncTypeError Traceback (most recent call last) &lt;__array_function__ internals&gt; in clip(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/numpy/core/_methods.py in _clip_dep_invoke_with_casting(ufunc, out, casting, *args, **kwargs) 83 # try to deal with broken casting rules 84 try: ---&gt; 85 return ufunc(*args, out=out, **kwargs) 86 except _exceptions._UFuncOutputCastingError as e: 87 # Numpy 1.17.0, 2019-02-24 UFuncTypeError: ufunc 'clip' did not contain a loop with signature matching types (dtype('&lt;U32'), dtype('&lt;U32'), dtype('&lt;U32')) -&gt; dtype('&lt;U32')</pre><p> 起初,我认为它与数据集有关,但是,我没有更改我的数据集,并且在我第一次训练这个 model 时它已经运行。 </p></div></u32’)<></u32’),> - UFuncTypeError: ufunc ‘clip’ did not contain a loop with signature matching types (dtype(‘<U32’), dtype(‘<U32’), dtype(‘<U32’)) -> dtype(‘<U32’) Scikit-Learn(类型错误:ufunc &#39;subtract&#39; 不包含签名匹配类型 dtype(&#39; - Scikit-Learn (TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')) UFuncTypeError:ufunc 'matmul' 不包含具有签名匹配类型的循环(dtype(' <u32'), dtype('<u32')) -> dtype(' <u32') - streamlit< div><div id="text_translate"><pre> #Linear Regression Model @st.cache(allow_output_mutation=True) def linearRegression(X_train, X_test, y_train, y_test): model = LinearRegression() model.fit(X_train,y_train) score = model.score(X_test, y_test)*100 return score, model</pre><hr><pre> #User input for the model def user_input(): bedrooms = st.slider("Bedrooms: ", 1,15) bathrooms = st.text_input("Bathrooms: ") sqft_living = st.text_input("Square Feet: ") sqft_lot = st.text_input("Lot Size: ") floors = st.text_input("Number Of Floors: ") waterfront = st.text_input("Waterfront? For Yes type '1', For No type '0': ") view = st.slider("View (A higher score will mean a better view): ", 0,4) condition = st.slider("House Condition (A higher score will mean a better condition): ", 1,5) yr_built = st.text_input("Year Built: ") yr_reno = st.text_input("A Renovated Property? For Yes type '1', For No type '0': ") zipcode = st.text_input("Zipcode (5 digit): ") year_sold = st.text_input("Year Sold: ") month_sold = st.slider("Month Sold: ", 1,12) user_input_prediction = np.array([bedrooms,bathrooms,sqft_living, sqft_lot,floors,waterfront,view,condition,yr_built,yr_reno,zipcode,year_sold,month_sold]).reshape(1,-1) return(user_input_prediction)</pre><hr><pre> #Main function if(st.checkbox("Start a Search")): user_input_prediction = user_input() st.write('error1') pred = model.predict(user_input_prediction) st.write('error2') if(st.button("Submit")): st.text("success")</pre><p> 我正在使用 Streamlit 构建一个接受用户输入的 ML model。 在我的主要 function 中,它返回错误UFuncTypeError: ufunc 'matmul' did not contain a loop with signature matching types (dtype('&lt;U32'), dtype('&lt;U32')) -&gt; dtype('&lt;U32') and trace返回pred = model.predict(user_input_prediction)主 function 将打印出 error1 但不会打印 error2</p></div></u32')></u32'),> - UFuncTypeError: ufunc 'matmul' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32') - Streamlit 收到错误:ufunc&#39;subtract&#39;不包含签名匹配类型为dtype(&#39;的循环 - Getting error: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32') sklearn.manifold.TSNE TypeError:ufunc&#39;multiply&#39;不包含签名匹配类型的循环(dtype(&#39; - sklearn.manifold.TSNE TypeError: ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32'))...) TypeError: ufunc 'add' 不包含签名匹配类型 dtype(' <u1') dtype('<u1') dtype('<u1')< div><div id="text_translate"><p> 我是 Python 用户的初学者。 当我尝试在下面编写代码时发生错误</p><pre>import numpy as np np.array(['a', 'b', 'c']) + np.array(['d','e', 'f'])</pre><pre> TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('&lt;U1') dtype('&lt;U1') dtype('&lt;U1')</pre><p> 所以我尝试设置dtype = '&lt;U1' ,但它没有用</p><pre>import numpy as np np.array(['a', 'b', 'c'], dtype='&lt;U1') + np.array(['d','e', 'f'], dtype='&lt;U1')</pre><p> 如何无错误地连接那些 np.arrays ?</p></div></u1')> - TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1') 如何解释 Python 输出 dtype=&#39; - How to interpret Python output dtype='<U32'? Python:Numpy dtype U32 - 简单的 if-else 语句 - Python: Numpy dtype U32 - simple if-else statement UFuncTypeError: 无法从 dtype(' <u32') to dtype('float32') with casting rule 'same_kind'?< div><div id="text_translate"><p> 我正在尝试创建一个 ML model 来对石头、纸和剪刀的手势图像进行分类。 我不断收到如下错误消息:</p><blockquote><p> UFuncTypeError:无法使用转换规则“same_kind”将 ufunc 'multiply' output 从 dtype('&lt;U32') 转换为 dtype('float32')</p></blockquote><p> 这是我的代码:</p><pre> import tensorflow as to from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow import keras from tensorflow.keras import layers:wget --no-check-certificate \ https.//dicodingacademy.blob.core.windows.net/picodiploma/ml_pemula_academy/rockpaperscissors.zip -O /tmp/rockpaperscissors,zip import zipfile.os local_zip = '/tmp/rockpaperscissors.zip' zip_ref = zipfile,ZipFile(local_zip. 'r') zip_ref.extractall('/tmp') zip_ref.close(),pip install split_folders import split_folders as SF sf,ratio('/tmp/rockpaperscissors/rps-cv-images', output="/tmp/rockpaperscissors/data".seed=1337, ratio=(.8. .2)) root_path = '/tmp/rockpaperscissors/data' train_path = os,path.join(root_path. 'train') validation_path = os,path,join(root_path, 'val') train_datagen = ImageDataGenerator( rescale = "none", rotation_range = 30, vertical_flip = True. horizontal_flip = True, zoom_range = 0.1, width_shift_range = 0.1, height_shift_range = 0.1, shear_range = 0,2, fill_mode = 'nearest') test_datagen = ImageDataGenerator( rescale = "none", rotation_range = 30, vertical_flip = True. horizontal_flip = True, zoom_range = 0.1, width_shift_range = 0.1, height_shift_range = 0.1, shear_range = 0.2, fill_mode = 'nearest') train_generator = train_datagen,flow_from_directory( train_path, target_size=(150, 150). batch_size=32, class_mode='categorical') validation_generator = test_datagen,flow_from_directory( validation_path, target_size=(150, 150). batch_size=32. class_mode='categorical') model = keras.Sequential() model,add(layers,Conv2D(32, (5,5), activation='relu', input_shape=(150. 150. 3))) model,add(layers.MaxPooling2D(2. 2)) model,add(layers,Conv2D(64, (3.3). activation='relu')) model,add(layers.MaxPooling2D(2. 2)) model,add(layers,Conv2D(128, (3.3). activation='relu')) model,add(layers.MaxPooling2D(2. 2)) model,add(layers,Conv2D(256, (3.3). activation='relu')) model,add(layers.MaxPooling2D(2. 2)) model,add(layers,Conv2D(512, (3.3). activation='relu')) model,add(layers.MaxPooling2D(2. 2)) model.add(layers.Flatten()) model,add(layers.Dense(512. activation='relu')) model,add(layers.Dense(3. activation='softmax')) model.summary() loss_fn = keras.losses,SparseCategoricalCrossentropy() model,compile(loss=loss_fn. optimizer=RMSprop(), metrics=['accuracy']) model,fit( train_generator, steps_per_epoch=54, epochs=22, validation_data=validation_generator, validation_steps=13, verbose=2)</pre><p> 这是我的代码的链接: <a href="https://colab.research.google.com/drive/1stBPFyuIQTU_2LqDSHLlrLOSSBeuYLNT#scrollTo=r3Q3w-Tm6tnX" rel="nofollow noreferrer">Rock Paper Scissors Classifier</a>谢谢!</p></div></u32')> - UFuncTypeError: Cannot cast ufunc 'multiply' output from dtype('<U32') to dtype('float32') with casting rule 'same_kind'? ufunc&#39;add&#39;不包含签名匹配类型为dtype(&#39; - ufunc 'add' did not contain a loop with signature matching types dtype('<U23') dtype('<U23') dtype('<U23')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM