GVKun编程网logo

unhashable 类型:在 Pandas 中将 Object 转换为 datetime 时的“numpy.ndarray”(pandas object转float)

1

在这篇文章中,我们将带领您了解unhashable类型:在Pandas中将Object转换为datetime时的“numpy.ndarray”的全貌,包括pandasobject转float的相关情况

在这篇文章中,我们将带领您了解unhashable 类型:在 Pandas 中将 Object 转换为 datetime 时的“numpy.ndarray”的全貌,包括pandas object转float的相关情况。同时,我们还将为您介绍有关"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类、'<=' 在 'numpy.ndarray' 和 'numpy.ndarray' 的实例之间不受支持但 LHS 是 pd.Timestamp、Angular 10:运行 ng xi18n 时无法解析 SomeComponent (?, [object Object], [object Object]) 的所有参数、angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])的知识,以帮助您更好地理解这个主题。

本文目录一览:

unhashable 类型:在 Pandas 中将 Object 转换为 datetime 时的“numpy.ndarray”(pandas object转float)

unhashable 类型:在 Pandas 中将 Object 转换为 datetime 时的“numpy.ndarray”(pandas object转float)

如何解决unhashable 类型:在 Pandas 中将 Object 转换为 datetime 时的“numpy.ndarray”

每当我尝试将列转换为 DateTime 格式时,我都会收到此错误。我的列是字符串格式,我试过在网上查找,但找不到任何可以帮助我解决此问题的内容。

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-87-9a285deef407> in <module>
----> 1 pd.to_datetime(bookings_ship_time[''purchase_order_requested_cargo_ready_date''],infer_datetime_format=True)
      2 
      3 

c:\\users\\marcus\\appdata\\local\\programs\\python\\python38-32\\lib\\site-packages\\pandas\\core\\tools\\datetimes.py in to_datetime(arg,errors,dayfirst,yearfirst,utc,format,exact,unit,infer_datetime_format,origin,cache)
    799                 result = result.tz_localize(tz)
    800     elif isinstance(arg,ABCSeries):
--> 801         cache_array = _maybe_cache(arg,cache,convert_listlike)
    802         if not cache_array.empty:
    803             result = arg.map(cache_array)

c:\\users\\marcus\\appdata\\local\\programs\\python\\python38-32\\lib\\site-packages\\pandas\\core\\tools\\datetimes.py in _maybe_cache(arg,convert_listlike)
    171     if cache:
    172         # Perform a quicker unique check
--> 173         if not should_cache(arg):
    174             return cache_array
    175 

c:\\users\\marcus\\appdata\\local\\programs\\python\\python38-32\\lib\\site-packages\\pandas\\core\\tools\\datetimes.py in should_cache(arg,unique_share,check_count)
    135     assert 0 < unique_share < 1,"unique_share must be in next bounds: (0; 1)"
    136 
--> 137     unique_elements = set(islice(arg,check_count))
    138     if len(unique_elements) > check_count * unique_share:
    139         do_caching = False

TypeError: unhashable type: ''numpy.ndarray''

采购订单栏信息如下:

purchase_order_id
1140     [2017-04-10]
1148     [2017-07-01]
1151     [2017-05-30]
3156     [2017-10-13]
3363     [2017-09-08]
             ...     
56584    [2019-09-30]
56585    [2019-09-30]
56586    [2019-09-23]
56587    [2019-09-23]
56588    [2019-09-23]

编辑: 数据类型是 (''O'') 我曾尝试使用 pd.to_datetime 方法和:

bookings_ship_time[''purchase_order_requested_cargo_ready_date''] = datetime.strptime(bookings_ship_time[''purchase_order_requested_cargo_ready_date''],''%Y/%m/%d'')

"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类

如何解决"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类

我一直在研究用于图像分类的 CNN,但我一直遇到同样的错误,我的数据正在加载到数据帧中,但我无法将其转换为张量以将其输入 CNN。如您所见,我使用此代码将图片加载到数据框中:

  1. for i in range(len(merged)):
  2. full_path = merged.iloc[i][''Image Path Rel'']
  3. filename = full_path[-22:-1] + ''G''
  4. try:
  5. img = img_to_array(load_img(''D:/Serengeti_Data/Compressed/Compressed/'' + filename,target_size=(32,32,3)))
  6. except:
  7. img = np.zeros((32,3),dtype=np.float32)
  8. images = images.append({''Capture Id'' : merged.iloc[i][''Capture Id''],''Image'' : img},ignore_index = True)
  9. else:
  10. images = images.append({''Capture Id'' : merged.iloc[i][''Capture Id''],ignore_index = True)

然后,一旦我使用 load_img()img_to_array() 加载了图像,我进行了重塑以获得所需的 (32,3) 形状。还通过将 Image 列除以 255 来标准化这些值。

然后我这样做是为了尝试将其转换为张量:

  1. train_tf = tf.data.Dataset.from_tensor_slices(images[''Image''])
  2. # Also tried this,but didn''t got the same results:
  3. # train_tf = tf.convert_to_tensor(train_df[''Image''])

但不断收到错误:

ValueError: 无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)

我也尝试跳过它并立即尝试适应我们的模型,但得到了完全相同的错误:

  1. trying_df = pd.DataFrame(images[''Image''])
  2. target_df = pd.DataFrame(targets)
  3. animal_model = models.Sequential()
  4. animal_model.add(layers.Conv2D(30,kernel_size = (3,padding = ''valid'',activation = ''relu'',input_shape =(32,3)))
  5. animal_model.add(layers.MaxPooling2D(pool_size=(1,1)))
  6. animal_model.add(layers.Conv2D(60,kernel_size=(1,1),activation = ''relu''))
  7. animal_model.add(layers.Flatten())
  8. animal_model.add(layers.Dense(100,activation = ''relu''))
  9. animal_model.add(layers.Dense(10,activation = ''softmax''))
  10. ## compiler to model
  11. animal_model.compile(loss = ''categorical_crossentropy'',metrics = [''accuracy''],optimizer =''adam'')
  12. ## training the model
  13. animal_model.fit(trying_df,target_df,batch_size = 128,epochs = 15)
  14. animal_model.summary()

TensorFlow 版本:2.4.1

Numpy 版本:1.19.5

熊猫版本:1.0.1

解决方法

为了加载图像,您可以使用以下代码:

  1. image = cv2.imread(filename)
  2. image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)

为了调整图像的大小和缩放比例,最好让模型“嵌入”预处理功能。

  1. IMG_SIZE = 180
  2. resize_and_rescale = tf.keras.Sequential([
  3. layers.experimental.preprocessing.Resizing(IMG_SIZE,IMG_SIZE),layers.experimental.preprocessing.Rescaling(1./255)
  4. ])
  5. model = tf.keras.Sequential(
  6. [
  7. resize_and_rescale,layers.Conv2D(32,3,activation="relu"),layers.MaxPooling2D(),layers.Conv2D(64,layers.Conv2D(128,layers.Flatten(),layers.Dense(128,layers.Dense(len(class_names),activation="softmax"),]
  8. )
  9. model.compile(
  10. optimizer="adam",loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=["accuracy"],)

注意:
处理图像时使用 tf.Data 而不是 numpy 数组。您可以使用以下代码作为示例:
https://github.com/alessiosavi/tensorflow-face-recognition/blob/90d4acbea8f79539826b50c82a63a7c151441a1a/dense_embedding.py#L155

'<=' 在 'numpy.ndarray' 和 'numpy.ndarray' 的实例之间不受支持但 LHS 是 pd.Timestamp

'<=' 在 'numpy.ndarray' 和 'numpy.ndarray' 的实例之间不受支持但 LHS 是 pd.Timestamp

如何解决''<='' 在 ''numpy.ndarray'' 和 ''numpy.ndarray'' 的实例之间不受支持但 LHS 是 pd.Timestamp

代码:

print(min_time.__class__,min_time,times.__class__)
print(max_time.__class__,max_time)
mask = (times >= min_time) * (times <= max_time)

产量:

''pandas._libs.tslibs.timestamps.Timestamp''> 2020-02-12 00:00:00+00:00

''pandas._libs.tslibs.timestamps.Timestamp''> 2020-02-12 00:00:00+00:00

''

什么给? LHS 显然是 pandas.Timestamp,RHS 显然是 numpy.ndarray。我的类型发生了什么神奇的事情吗?

Angular 10:运行 ng xi18n 时无法解析 SomeComponent (?, [object Object], [object Object]) 的所有参数

Angular 10:运行 ng xi18n 时无法解析 SomeComponent (?, [object Object], [object Object]) 的所有参数

如何解决Angular 10:运行 ng xi18n 时无法解析 SomeComponent (?, [object Object], [object Object]) 的所有参数

应用运行/构建良好,但是当我尝试运行 List<SubItem> tempSplitFilesList = new ArrayList<>(); List<SubItem> splitFilesList = new ArrayList<>(); for (SubItem item1 : tempSplitFilesList) { for (SubItem item2 : tempSplitFilesList) { if (item1.getStop().equals(item2.getStart())) { splitFilesList.add(item2); } } } 时,我得到 ng xi18n --output-path src/translate

从错误中我可以假设它是导致问题的构造函数中的第一个参数,但是,我的构造函数看起来像这样:

ERROR in Can''t resolve all parameters for SomeComponent in /path/some.component.ts: (?,[object Object],[object Object]).

被扩展的类的构造函数如下所示:

constructor(
        $window: Window,service1: Service1,service2: Service2
    ) {
        super($window,service1,Service2);
    }

似乎这些错误通常来自注射和/或放置在枪管中的问题?如果是这样,window 是如何在这里出错的,或者它可能是完全不相关的东西?

解决方法

问题似乎与错误注入 Window 一样简单。编写一个自定义服务来处理它解决了这个问题。您可以在这里找到正确的注入方式:How to inject window into a service?

angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])

angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])

我遇到了下一个错误,无法理解如何解决它.

Can’t resolve all parameters for AuthenticationService: ([object Object],?,[object Object])

我已经检查了几乎每个主题,并尝试了多种方法来解决它,但仍然无法在第二天击败它.

我试图像这样在appService中注入第一个authService但是得到了同样的错误

@Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService

我检查了所有DI和服务内部的导入顺序,在我看来一切都是正确的

如果有人可以帮我处理它,我很感激.

Angular 4.0.0

AuthService

import { Injectable } from '@angular/core';
import {Http,Headers,Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

import {AppServices} from "../../app.services";
import {Router} from "@angular/router";

@Injectable()
export class AuthenticationService {
  public token: any;

  constructor(
    private http: Http,private appService: AppServices,private router: Router
  ) {
    this.token = localStorage.getItem('token');
  }

  login(username: string,password: string): Observable<boolean> {
    let headers = new Headers();
    let body = null;
    headers.append("Authorization",("Basic " + btoa(username + ':' + password)));

    return this.http.post(this.appService.api + '/login',body,{headers: headers})
      .map((response: Response) => {
        let token = response.json() && response.json().token;
        if (token) {
          this.token = token;
          localStorage.setItem('Conform_token',token);
          return true;
        } else {
          return false;
        }
      });
  }

  logout(): void {
    this.token = null;
    localStorage.removeItem('Conform_token');
    this.router.navigate(['/login']);
  }
}

应用服务

import {Injectable} from '@angular/core';
import {Headers,Http,RequestOptions} from '@angular/http';
import {Router} from "@angular/router";
import {AuthenticationService} from "./auth/auth.service";

import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

@Injectable()

export class AppServices {

  api = '//endpoint/';

  public options: any;
  constructor(
    private http: Http,private router: Router,public authService: AuthenticationService // doesn't work
  //  @Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService // doesn't work either
      ) {
        let head = new Headers({
      'Authorization': 'Bearer ' + this.authService.token,"Content-Type": "application/json; charset=utf8"
    });
    this.options = new RequestOptions({headers: head});
  }

  // ====================
  //    data services
  // ====================

  getData(): Promise<any> {
    return this.http
      .get(this.api + "/data",this.options)
      .toPromise()
      .then(response => response.json() as Array<Object>)
      .catch((err)=>{this.handleError(err);})
  }

应用模块

import { browserModule } from '@angular/platform-browser';
import { browserAnimationsModule } from '@angular/platform-browser/animations';

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {BaseRequestOptions,HttpModule} from '@angular/http';

import { MaterialModule} from '@angular/material';
import {FlexLayoutModule} from "@angular/flex-layout";
import 'hammerjs';

import { routing,appRoutingProviders }  from './app.routing';
import { AppServices } from './app.services';
import {AuthGuard} from "./auth/auth.guard";
import {AuthenticationService} from "./auth/auth.service";

import {AppComponent} from './app.component';
import {AuthComponent} from './auth/auth.component';
import {NotFoundComponent} from './404/not-found.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,AuthComponent,NotFoundComponent,HomeComponent
  ],imports: [
    browserModule,browserAnimationsModule,FormsModule,HttpModule,routing,MaterialModule,FlexLayoutModule
  ],providers: [AppServices,AuthGuard,AuthenticationService],bootstrap: [AppComponent]
})
export class AppModule { }

解决方法

AppServices和AuthenticationService之间存在循环依赖关系 – 这与Angular使用的构造函数注入无法实现.

你可以使用

export class AuthenticationService {
  public token: any;
  appService: AppServices;
  constructor(
    private http: Http,// private appService: AppServices,injector:Injector;
    private router: Router
  ) {
    setTimeout(() => this.appService = injector.get(AppServices));
    this.token = localStorage.getItem('token');
  }

另见DI with cyclic dependency with custom HTTP and ConfigService

要避免使用setTimeout,您还可以从AppService的构造函数中设置AuthenticationService.appService(或者相反)

今天关于unhashable 类型:在 Pandas 中将 Object 转换为 datetime 时的“numpy.ndarray”pandas object转float的介绍到此结束,谢谢您的阅读,有关"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类、'<=' 在 'numpy.ndarray' 和 'numpy.ndarray' 的实例之间不受支持但 LHS 是 pd.Timestamp、Angular 10:运行 ng xi18n 时无法解析 SomeComponent (?, [object Object], [object Object]) 的所有参数、angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])等更多相关知识的信息可以在本站进行查询。

本文标签: