GVKun编程网logo

当 dtype 是对象时,numpy.array_equal 和 numpy.testing.assert_array_equal 不会将 NaN 比较为相等 1. np.array_equal2. np.testing.assert_array_equalNumPy/Python 版本信息:

1

本文将为您提供关于当dtype是对象时,numpy.array_equal和numpy.testing.assert_array_equal不会将NaN比较为相等1.np.array_equal2.n

本文将为您提供关于当 dtype 是对象时,numpy.array_equal 和 numpy.testing.assert_array_equal 不会将 NaN 比较为相等 1. np.array_equal2. np.testing.assert_array_equalNumPy/Python 版本信息:的详细介绍,同时,我们还将为您提供关于"CALayer position contains NaN: [nan nan]" 自定义滑块导致的错误信息、Go testing 库 testing.T 和 testing.B 简介、msg_dtype if msg_dtype is not None else X.dtype) ValueError: Input contains NaN, infinity or a value too large for dtype('float64')、NetCDF Python 无法将 ufunc 'multiply' 输出从 dtype('的实用信息。

本文目录一览:

当 dtype 是对象时,numpy.array_equal 和 numpy.testing.assert_array_equal 不会将 NaN 比较为相等 1. np.array_equal2. np.testing.assert_array_equalNumPy/Python 版本信息:

当 dtype 是对象时,numpy.array_equal 和 numpy.testing.assert_array_equal 不会将 NaN 比较为相等 1. np.array_equal2. np.testing.assert_array_equalNumPy/Python 版本信息:

如何解决当 dtype 是对象时,numpy.array_equal 和 numpy.testing.assert_array_equal 不会将 NaN 比较为相等 1. np.array_equal2. np.testing.assert_array_equalNumPy/Python 版本信息:

当 dtype 是对象时,比较 np.nan 的正确方法是什么? 我尝试了以下两种方法,但都失败了

1. np.array_equal

  1. import numpy as np
  2. np.array_equal(np.array([np.nan],dtype=object),np.array([np.nan],equal_nan=True)

我得到的是:

  1. Traceback (most recent call last):
  2. File "c:\\Users\\xxxx\\xxxxx\\.venv\\lib\\site-packages\\numpy\\core\\numeric.py",line 2455,in array_equal
  3. a1nan,a2nan = isnan(a1),isnan(a2)
  4. TypeError: ufunc ''isnan'' not supported for the input types,and the inputs Could not be safely coerced to any supported types according to the casting rule ''''safe''''

2. np.testing.assert_array_equal

  1. import numpy as np
  2. np.testing.assert_array_equal(np.array([np.nan],dtype=object))

我得到的是:

  1. Traceback (most recent call last):
  2. File "<string>",line 1,in <module>
  3. File "c:\\Users\\xxxx\\xxxxx\\.venv\\lib\\site-packages\\numpy\\testing\\_private\\utils.py",line 932,in assert_array_equal
  4. assert_array_compare(operator.__eq__,x,y,err_msg=err_msg,File "c:\\Users\\xxxx\\xxxxx\\.venv\\lib\\site-packages\\numpy\\testing\\_private\\utils.py",line 842,in assert_array_compare
  5. raise AssertionError(msg)
  6. AssertionError:
  7. Arrays are not equal
  8. Mismatched elements: 1 / 1 (100%)
  9. Max absolute difference: nan
  10. Max relative difference: nan
  11. x: array([nan],dtype=object)
  12. y: array([nan],dtype=object)

NumPy/Python 版本信息:

1.20.3 3.9.5(标签/v3.9.5:0a7dcbd,2021 年 5 月 3 日,17:27:52)[MSC v.1928 64 位 (AMD64)]

"CALayer position contains NaN: [nan nan]" 自定义滑块导致的错误信息

如何解决"CALayer position contains NaN: [nan nan]" 自定义滑块导致的错误信息

我有一个视频播放器开始播放视频(来自 firebase URL),在某些情况下(70% 的情况)我在物理设备上运行时收到此错误消息(异常)(但在模拟器中启动时没有问题) : “CALayer 位置包含 NaN:[nan nan]”

我发现当我评论“VideoPlayerControlsView()”时没有出现错误,所以我很确定问题是我的 CustomerSlider 对象位于这个 VideoPlayerControlsView 视图的内部。

我认为这可能是由加载远程视频引起的,因为视频没有加载,应用程序不知道 AVPlayer 对象的大小/边界,因此无法创建一些父视图(可能是 CustomerSlider)。 .

构建一个最小的可重现示例将是一场噩梦,我只是希望有些人能在我的代码/逻辑中发现错误..如果没有 - 当然会构建它。别无选择。

struct DetailedplayerView : View {
    // The progress through the video,as a percentage (from 0 to 1)
    @State private var videoPos: Double = 0
    // The duration of the video in seconds
    @State private var videoDuration: Double = 0
    // Whether we''re currently interacting with the seek bar or doing a seek
    @State private var seeking = false

    private var player: AVPlayer = AVPlayer()
        
    init(item: ExerciseItem,hVideoURL: URL?) {

        if hVideoURL != nil {
            player = AVPlayer(url: hVideoURL!)
            player.isMuted = true
            player.play()
        } else {
            print("[debug] hVideoURL is nil")
        }
    }

    var body: some View {
        ZStack {
            //vstack {
            VideoPlayerView(videoPos: $videoPos,videoDuration: $videoDuration,seeking: $seeking,//timeline: $timeline,//videoTimeline: videoTimeline,player: player)
                .frame(width: UIScreen.screenHeight,height: UIScreen.screenWidth)
                
            vstack {
                
                Spacer()
                VideoPlayerControlsView(videoPos: $videoPos,**<<-----------------------**
                                        videoDuration: $videoDuration,player: player)
                    .frame(width: UIScreen.screenHeight - 2*Constants.scrollPadding,height: 20)
                    .padding(.bottom,20)
            }
                
        }
        .ondisappear {
            // When this View isn''t being shown anymore stop the player
            self.player.replaceCurrentItem(with: nil)
        }
    }
}

struct VideoPlayerControlsView : View {
    @Binding private(set) var videoPos: Double
    @Binding private(set) var videoDuration: Double
    @Binding private(set) var seeking: Bool
//    @Binding private(set) var timeline: [Advice]

    @State var shouldStopPlayer: Bool = false
    
    @State var player: AVPlayer
    //let player: AVPlayer
    
    @State private var playerPaused = false
    
    var body: some View {
        HStack {
            // Play/pause button
            Button(action: togglePlayPause) {
                Image(systemName: playerPaused ? "arrowtriangle.right.fill" : "pause.fill")
                    .foregroundColor(Color.mainSubtitleColor)
                    .contentShape(Rectangle())

                    .padding(.trailing,10)
            }
            
            // Current video time
            if videoPos.isFinite && videoPos.isCanonical && videoDuration.isFinite && videoDuration.isCanonical {
            Text(Utility.formatSecondsToHMS(videoPos * videoDuration))
                .foregroundColor(Color.mainSubtitleColor)
            }
            
            // Slider for seeking / showing video progress
            CustomSlider(value: $videoPos,shouldStopPlayer: self.$shouldStopPlayer,range: (0,1),knobWidth: 4) { modifiers in
              ZStack {
                Group {

                    Color(#colorLiteral(red: 1,green: 1,blue: 1,alpha: 0.5799999833106995))//Color((red: 0.4,green: 0.3,blue: 1)
                        .opacity(0.4)
                        .frame(height: 4)
                        .modifier(modifiers.barRight)

                    Color.mainSubtitleColor//Color(red: 0.4,blue: 1)
                        .frame(height: 4)
                        .modifier(modifiers.barLeft)

                }
                .cornerRadius(5)

                vstack {
                    Image(systemName: "arrowtriangle.down.fill") // SF Symbol
                    .foregroundColor(Color.mainSubtitleColor)
                    .offset(y: -3)
                }
                .frame(width: 20,height: 20)
                .contentShape(Rectangle())
                .modifier(modifiers.knob)
              }
            }
            .onChange(of: shouldStopPlayer) { _ in
                if shouldStopPlayer == false {
                    print("[debug] shouldStopPlayer == false")
                    sliderEditingChanged(editingStarted: false)
                } else {
                    if seeking == false {
                        print("[debug] shouldStopPlayer == true")
                        sliderEditingChanged(editingStarted: true)
                    }
                }
            }
            .frame(height: 20)

            // Video duration
            if videoDuration.isCanonical && videoDuration.isFinite {
            Text(Utility.formatSecondsToHMS(videoDuration))
                .foregroundColor(Color.mainSubtitleColor)
            }
        }
        .padding(.leading,40)
        .padding(.trailing,40)
    }
    
    private func togglePlayPause() {
        pausePlayer(!playerPaused)
    }
    
    private func pausePlayer(_ pause: Bool) {
        playerPaused = pause
        
        if playerPaused {
            player.pause()
        }
        else {
           player.play()
        }
    }
    
    private func sliderEditingChanged(editingStarted: Bool) {
        if editingStarted {
            // Set a flag stating that we''re seeking so the slider doesn''t
            // get updated by the periodic time observer on the player
            seeking = true
            pausePlayer(true)
        }
        
        // Do the seek if we''re finished
        if !editingStarted {
            let targetTime = CMTime(seconds: videoPos * videoDuration,preferredTimescale: 600)
            player.seek(to: targetTime) { _ in
                // Now the seek is finished,resume normal operation
                self.seeking = false
                self.pausePlayer(false)
            }
        }
    }
}

extension Double {
    func convert(fromrange: (Double,Double),toRange: (Double,Double)) -> Double {
        // Example: if self = 1,fromrange = (0,2),toRange = (10,12) -> solution = 11
        var value = self
        value -= fromrange.0
        value /= Double(fromrange.1 - fromrange.0)
        value *= toRange.1 - toRange.0
        value += toRange.0
        return value
    }
}

struct CustomSliderComponents {
    let barLeft: CustomSliderModifier
    let barRight: CustomSliderModifier
    let knob: CustomSliderModifier
}

struct CustomSliderModifier: ViewModifier {
    enum Name {
        case barLeft
        case barRight
        case knob
    }
    let name: Name
    let size: CGSize
    let offset: CGFloat

    func body(content: Content) -> some View {
        content
            .frame(width: (size.width >= 0) ? size.width : 0)
            .position(x: size.width*0.5,y: size.height*0.5)
            .offset(x: offset)
    }
}

struct CustomSlider<Component: View>: View {

    @Binding var value: Double
    var range: (Double,Double)
    var knobWidth: CGFloat?
    let viewbuilder: (CustomSliderComponents) -> Component
    @Binding var shouldStopPlayer: Bool
    
    init(value: Binding<Double>,shouldStopPlayer: Binding<Bool>,range: (Double,knobWidth: CGFloat? = nil,_ viewbuilder: @escaping (CustomSliderComponents) -> Component
    ) {
        _value = value
        _shouldStopPlayer = shouldStopPlayer
        self.range = range
        self.viewbuilder = viewbuilder
        self.knobWidth = knobWidth
    }

    var body: some View {
      return GeometryReader { geometry in
        self.view(geometry: geometry) // function below
      }
    }

    private func view(geometry: GeometryProxy) -> some View {
      let frame = geometry.frame(in: .global)
      let drag = DragGesture(minimumdistance: 0)
        .onChanged { drag in
                    shouldStopPlayer = true
                    self.onDragChange(drag,frame)
        }
        .onEnded { drag in
            shouldStopPlayer = false
            //self.updatedValue = value
            print("[debug] slider drag gesture ended,value = \\(value)")
        }
      let offsetX = self.getoffsetX(frame: frame)

      let knobSize = CGSize(width: knobWidth ?? frame.height,height: frame.height)
      let barLeftSize = CGSize(width: CGFloat(offsetX + knobSize.width * 0.5),height:  frame.height)
      let barRightSize = CGSize(width: frame.width - barLeftSize.width,height: frame.height)

      let modifiers = CustomSliderComponents(
          barLeft: CustomSliderModifier(name: .barLeft,size: barLeftSize,offset: 0),barRight: CustomSliderModifier(name: .barRight,size: barRightSize,offset: barLeftSize.width),knob: CustomSliderModifier(name: .knob,size: knobSize,offset: offsetX))

      return ZStack { viewbuilder(modifiers).gesture(drag) }
    }
    
    private func onDragChange(_ drag: DragGesture.Value,_ frame: CGRect) {
        let width = (knob: Double(knobWidth ?? frame.size.height),view: Double(frame.size.width))
        let xrange = (min: Double(0),max: Double(width.view - width.knob))
        var value = Double(drag.startLocation.x + drag.translation.width) // knob center x
        value -= 0.5*width.knob // offset from center to leading edge of knob
        value = value > xrange.max ? xrange.max : value // limit to leading edge
        value = value < xrange.min ? xrange.min : value // limit to trailing edge
        value = value.convert(fromrange: (xrange.min,xrange.max),toRange: range)
        //print("[debug] slider drag gesture detected,value = \\(value)")
        self.value = value
    }
    
    private func getoffsetX(frame: CGRect) -> CGFloat {
        let width = (knob: knobWidth ?? frame.size.height,view: frame.size.width)
        let xrange: (Double,Double) = (0,Double(width.view - width.knob))

        let result = self.value.convert(fromrange: range,toRange: xrange)
        return CGFloat(result)
    }
  
}

一些额外的代码展示了如何触发DetailedplayerView:

struct DetailedVideo: View {
    var item: ExerciseItem
    var url: URL
    @Binding var isPaused: Bool
    
    var body: some View {
        ZStack {
            
            DetailedplayerView(item: self.item,hVideoURL: url)
                //.frame(width: 500,height: 500) //@@UPDATED: Apr 10 
            
            HStack {
                
                vstack {
                    
                    ZStack {
                        //Rectangle 126
                        RoundedRectangle(cornerRadius: 1)
                            .fill(Color(#colorLiteral(red: 0.3063802123069763,green: 0.3063802123069763,blue: 0.3063802123069763,alpha: 1)))
                            .frame(width: 2,height: 20.3)
                            .rotationEffect(.degrees(-135))
                        
                        //Rectangle 125
                        RoundedRectangle(cornerRadius: 1)
                            .fill(Color(#colorLiteral(red: 0.3063802123069763,height: 20.3)
                            .rotationEffect(.degrees(-45))
                        
                    }
                    .frame(width: 35,height: 35)//14.4
                    .contentShape(Rectangle())
                    .onTapGesture {
                        print("[debugUI] isPaused = false")
                        self.isPaused = false
                    }
                    .offset(x:20,y:20)
                    
                    Spacer()
                }
                
                Spacer()
                
            }
        }
        .ignoresSafeArea(.all)
    }
}

@viewbuilder
    var detailedVideoView: some View {
        if self.hVideoURL != nil {
            DetailedVideo(item: self.exerciseVM.exerciseItems[self.exerciseVM.currentIndex],url: self.hVideoURL!,isPaused: self.$exerciseVM.isPaused) // when is paused - we are playing detailed video?
                .frame(width: UIScreen.screenHeight,height: UIScreen.screenWidth) //UPDATED: Apr 9,2021
                .onAppear {
                    AppDelegate.orientationLock = UIInterfaceOrientationMask.landscapeLeft
                    UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue,forKey: "orientation")
                    UINavigationController.attemptRotationToDeviceOrientation()
                }
                .ondisappear {
                    dispatchQueue.main.async {
                        AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
                        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue,forKey: "orientation")
                        UINavigationController.attemptRotationToDeviceOrientation()
                    }
                }
        } else {
            EmptyView()
        }
    }

Go testing 库 testing.T 和 testing.B 简介

Go testing 库 testing.T 和 testing.B 简介

testing.T

  • 判定失败接口
    • Fail 失败继续
    • FailNow 失败终止
  • 打印信息接口
    • Log 数据流 (cout 类似)
    • Logf format (printf 类似)
  • SkipNow 跳过当前测试
  • Skiped 检测是否跳过

综合接口产生

  • Error / Errorf 报告出错继续 [ Log / Logf + Fail ]
  • Fatel / Fatelf 报告出错终止 [ Log / Logf + FailNow ]
  • Skip / Skipf 报告并跳过 [ Log / Logf + SkipNow ]

testing.B

  • 首先 , testing.B 拥有testing.T 的全部接口。
  • SetBytes( i uint64) 统计内存消耗, 如果你需要的话。
  • SetParallelism(p int) 制定并行数目。
  • StartTimer / StopTimer / ResertTimer 操作计时器

testing.PB

    • Next() 接口 。 判断是否继续循环

 

msg_dtype if msg_dtype is not None else X.dtype) ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

msg_dtype if msg_dtype is not None else X.dtype) ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

如何解决msg_dtype if msg_dtype is not None else X.dtype) ValueError: Input contains NaN, infinity or a value too large for dtype(''float64'')

我正在尝试训练我的模型,但每次使用 self.gnb.fit(self.x_train,self.y_train) 时都会出现此错误:

Traceback (most recent call last):
  File "d:/Projects/Data_Processings/test.py",line 47,in <module>
    gnb.fit(x_train,y_train)
  File "C:\\Users\\Doctor\\anaconda3\\envs\\main_int\\lib\\site-packages\\sklearn\\naive_bayes.py",line 207,in fit
    X,y = self._validate_data(X,y)
  File "C:\\Users\\Doctor\\anaconda3\\envs\\main_int\\lib\\site-packages\\sklearn\\base.py",line 433,in _validate_data
    X,y = check_X_y(X,y,**check_params)
  File "C:\\Users\\Doctor\\anaconda3\\envs\\main_int\\lib\\site-packages\\sklearn\\utils\\validation.py",line 63,in inner_f
    return f(*args,**kwargs)
  File "C:\\Users\\Doctor\\anaconda3\\envs\\main_int\\lib\\site-packages\\sklearn\\utils\\validation.py",line 827,in check_X_y
    _assert_all_finite(y)
  File "C:\\Users\\Doctor\\anaconda3\\envs\\main_int\\lib\\site-packages\\sklearn\\utils\\validation.py",line 106,in _assert_all_finite
    msg_dtype if msg_dtype is not None else X.dtype)
ValueError: Input contains NaN,infinity or a value too large for dtype(''float64'').

代码如下:

class Data:
    def __init__(self):
        self.data = pd.read_csv(''data.csv'')
        self.comment = re.sub(''[^a-zA-Z]'','' '',self.data[''Review''][1])

        self.ps = Porterstemmer()
        self.the_derlem = []

        self.cv = CountVectorizer(max_features=1000)
        self.gnb = GaussianNB()
        self.sc = StandardScaler()

    def fixer(self,comment):
        comment = comment.lower()
        comment = comment.split()

        comment = [self.ps.stem(word) for word in comment if not word in set(stopwords.words(''english''))]
        comment = '' ''.join(comment)

        self.the_derlem.append(comment)

        return comment

    def fitter(self):
        self.X = self.cv.fit_transform(self.the_derlem).toarray()
        self.Y = self.data.iloc[:,1].values

        self.x_train,self.x_test,self.y_train,self.y_test = train_test_split(self.X,self.Y,test_size=0.20,random_state=0)

    def teach(self):
        self.gnb.fit(self.x_train,self.y_train)

    def loop(self):
        for i in range(1000):
            self.comment = re.sub(''[^a-zA-Z]'',self.data[''Review''][i])
            self.fixer(self.comment)

        self.fitter()
        self.teach()

data = Data()
data.loop()

我不知道该怎么做。我试图用 x_train and x_testStandardScaler 进行标准处理,但没有奏效。同样的错误再次发生。请有人帮助我!

这是我的数据的一部分:

I found this place by accident and I Could not be happier.,1
seems like a good quick place to grab a bite of some familiar pub food but do yourself a favor and look elsewhere.,0
Overall I like this place a lot.,1
The only redeeming quality of the restaurant was that it was very inexpensive.,1
Ample portions and good prices.,1
Poor service the waiter made me feel like I was stupid every time he came to the table.,0
My first visit to Hiro was a delight!,1
Service sucks.,0
The shrimp tender and moist.,1
There is not a deal good enough that would drag me into that establishment again.,0
Hard to judge whether these sides were good because we were grossed out by the melted styrofoam and didn''t want to eat it for fear of getting sick.,0

NetCDF Python 无法将 ufunc 'multiply' 输出从 dtype('<U32') 转换为 dtype('float32')

NetCDF Python 无法将 ufunc 'multiply' 输出从 dtype('

如何解决NetCDF Python 无法将 ufunc ''multiply'' 输出从 dtype(''<U32'') 转换为 dtype(''float32'')

我正在尝试使用 xarray 或 netCDF4 库将 netCDF 加载到数据帧中。通常这不会成为问题,因为我的 netCDF 大部分带有 Float32 中的纬度、经度和数据值。我假设我的错误是因为我有一些数据类型被作为 Float64 传递。

我目前在加载时从两个库中收到相同的错误,大概是因为它们都使用了 numpy。我没有做任何数学运算 - 只是加载。

  1. numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc ''multiply'' output from dtype(''<U32'')
  2. to dtype(''float32'') with casting rule ''same_kind''

使用 print(netCDF4.Dataset("d:\\netdcdf.nc") 产生以下描述:

  1. dimensions(sizes): time(1),lon(841),lat(681)
  2. variables(dimensions): float64 time(time),float64 lon(lon),float64 lat(lat),int32 crs(),float32 deadpool(time,lat,lon)

我的脚本如下,包括 xarray 和 netCDF4 的加载示例。

  1. #This file is designed to convert netcdf files to the BOM standard format.
  2. import netCDF4
  3. import pandas as pd
  4. import xarray as xr
  5. def main():
  6. pass
  7. if __name__ == ''__main__'':
  8. inputfile = ''D:\\\\Temp\\\\WeatherDownloads\\\\Weather\\\\deadpool.aus.nc''
  9. #xarray setup,debug and load
  10. ncx = xr.open_dataset(inputfile)
  11. ncdf = ncx.deadpool.to_dataframe() #fails here if we use xarray
  12. print(ncdf.head(10))
  13. #NetCDF4 setup,debug and load
  14. nc = netCDF4.Dataset(inputfile,mode=''r'')
  15. nc.variables.keys()
  16. lat = nc.variables[''lat''][:]
  17. lon = nc.variables[''lon''][:]
  18. time = nc.variables[''time'']
  19. datavar = nc.variables[''deadpool''][:] #fails here if we use netCDF4
  20. print("The dtype of lat is: " + str(dtype(lat)))
  21. print("The dtype of lon is: " + str(dtype(lon)))
  22. print("The dtype of time is: " + str(dtype(time)))
  23. print("The dtype of datavar is: " + str(dtype(datavar)))
  24. data_ts = pd.Series(datavar,index=time)
  25. print(data_ts.head(10))

今天关于当 dtype 是对象时,numpy.array_equal 和 numpy.testing.assert_array_equal 不会将 NaN 比较为相等 1. np.array_equal2. np.testing.assert_array_equalNumPy/Python 版本信息:的讲解已经结束,谢谢您的阅读,如果想了解更多关于"CALayer position contains NaN: [nan nan]" 自定义滑块导致的错误信息、Go testing 库 testing.T 和 testing.B 简介、msg_dtype if msg_dtype is not None else X.dtype) ValueError: Input contains NaN, infinity or a value too large for dtype('float64')、NetCDF Python 无法将 ufunc 'multiply' 输出从 dtype('的相关知识,请在本站搜索。

本文标签: