GVKun编程网logo

Numpy - ValueError:无法将 NumPy 数组转换为张量不支持的对象类型 int(无法将变量类型((void)转换为对象))

2

在本文中,您将会了解到关于Numpy-ValueError:无法将NumPy数组转换为张量不支持的对象类型int的新资讯,同时我们还将为您解释无法将变量类型((void)转换为对象)的相关在本文中,我

在本文中,您将会了解到关于Numpy - ValueError:无法将 NumPy 数组转换为张量不支持的对象类型 int的新资讯,同时我们还将为您解释无法将变量类型((void)转换为对象)的相关在本文中,我们将带你探索Numpy - ValueError:无法将 NumPy 数组转换为张量不支持的对象类型 int的奥秘,分析无法将变量类型((void)转换为对象)的特点,并给出一些关于/编写一个函数,要求从给定的向量A中删除元素值在x到y之间的所有元素(向量要求各个元素之间不能有间断), 函数原型为int del(int A ,int n , int x , int y),其...、2022-03-11:int n, int[][] roads, int x, int y, n表示城市数量,城市编号0~n-1, roads[i][j] == distance,表示城市i到城市j距、2022-05-26:void add(int L, int R, int C)代表在arr[L...R]上每个数加C, int get(int L, int R)代表查询arr[L...R]上的累加、android中用view.layout(int ,int,int,int)这4个参数是不是view的左上角的横坐标,纵坐标,view的宽,view的高?的实用技巧。

本文目录一览:

Numpy - ValueError:无法将 NumPy 数组转换为张量不支持的对象类型 int(无法将变量类型((void)转换为对象))

Numpy - ValueError:无法将 NumPy 数组转换为张量不支持的对象类型 int(无法将变量类型((void)转换为对象))

如何解决Numpy - ValueError:无法将 NumPy 数组转换为张量不支持的对象类型 int

这是我的火车数据:

    Message_body                                      Label
0   Rofl. Its true to its name  0
1   The guy did some bitching but I acted like i''d...   0
2   Pity,* was in mood for that. So...any other s...   0
3   Will ?b going to esplanade fr home? 0
4   This is the 2nd time we have tried 2 contact u...   1
... ... ...
970 BangBabes Ur order is on the way. U SHOULD rec...   1
971 -PLS STOP bootydelIoUs (32/F) is inviting you ...   1
972 You are a winner U have been specially selecte...   1
973 Customer service annoncement. You have a New Y...   1
974 FreeMsg Why haven''t you replied to my text? I''...   1

这是我的模型:

X_train = np.array(train)
y_train = np.array(train[''Label''])
X_test = test

from tensorflow.keras.layers import Dense,Conv1D,GlobalMaxPooling1D,Embedding,Dropout,MaxPooling1D
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import EarlyStopping,ModelCheckpoint

model = Sequential()
model.add(Embedding(vocab_num,32))
model.add(Dropout(0.2))
model.add(Conv1D(32,5,strides=1,padding=''valid'',activation=''relu''))
model.add(GlobalMaxPooling1D())
model.add(Dense(64,activation=''relu''))
model.add(Dropout(0.2))
model.add(Dense(1,activation=''sigmoid''))
model.summary()
model.compile(optimizer=''adam'',loss=''binary_crossentropy'',metrics=[''acc''])

es = EarlyStopping(monitor = ''val_loss'',mode = ''min'',verbose = 1,patience = 3)
mc = ModelCheckpoint(''best_model.h5'',monitor = ''val_acc'',mode = ''max'',save_best_only = True)

history = model.fit(X_train,y_train,epochs = 10,batch_size=64,validation_split=0.2,callbacks=[es,mc])

这里是错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-54-d78723a788e4> in <module>
----> 1 history = model.fit(X_train,mc])

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\keras\\engine\\training.py in fit(self,x,y,batch_size,epochs,verbose,callbacks,validation_split,validation_data,shuffle,class_weight,sample_weight,initial_epoch,steps_per_epoch,validation_steps,validation_batch_size,validation_freq,max_queue_size,workers,use_multiprocessing)
   1048          training_utils.RespectCompiledTrainableState(self):
   1049       # Creates a `tf.data.Dataset` and handles batch and epoch iteration.
-> 1050       data_handler = data_adapter.DataHandler(
   1051           x=x,1052           y=y,~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\keras\\engine\\data_adapter.py in __init__(self,use_multiprocessing,model,steps_per_execution)
   1098 
   1099     adapter_cls = select_data_adapter(x,y)
-> 1100     self._adapter = adapter_cls(
   1101         x,1102         y,sample_weights,sample_weight_modes,steps,**kwargs)
    261                **kwargs):
    262     super(TensorLikeDataAdapter,self).__init__(x,**kwargs)
--> 263     x,sample_weights = _process_tensorlike((x,sample_weights))
    264     sample_weight_modes = broadcast_sample_weight_modes(
    265         sample_weights,sample_weight_modes)

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\keras\\engine\\data_adapter.py in _process_tensorlike(inputs)
   1014     return x
   1015 
-> 1016   inputs = nest.map_structure(_convert_numpy_and_scipy,inputs)
   1017   return nest.list_to_tuple(inputs)
   1018 

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\util\\nest.py in map_structure(func,*structure,**kwargs)
    657 
    658   return pack_sequence_as(
--> 659       structure[0],[func(*x) for x in entries],660       expand_composites=expand_composites)
    661 

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\util\\nest.py in <listcomp>(.0)
    657 
    658   return pack_sequence_as(
--> 659       structure[0],660       expand_composites=expand_composites)
    661 

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\keras\\engine\\data_adapter.py in _convert_numpy_and_scipy(x)
   1009       if issubclass(x.dtype.type,np.floating):
   1010         dtype = backend.floatx()
-> 1011       return ops.convert_to_tensor_v2_with_dispatch(x,dtype=dtype)
   1012     elif scipy_sparse and scipy_sparse.issparse(x):
   1013       return _scipy_sparse_to_sparse_tensor(x)

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\util\\dispatch.py in wrapper(*args,**kwargs)
    199     """Call target,and fall back on dispatchers if there is a TypeError."""
    200     try:
--> 201       return target(*args,**kwargs)
    202     except (TypeError,ValueError):
    203       # Note: convert_to_eager_tensor currently raises a ValueError,not a

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\ops.py in convert_to_tensor_v2_with_dispatch(value,dtype,dtype_hint,name)
   1402     ValueError: If the `value` is a tensor not of given `dtype` in graph mode.
   1403   """
-> 1404   return convert_to_tensor_v2(
   1405       value,dtype=dtype,dtype_hint=dtype_hint,name=name)
   1406 

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\ops.py in convert_to_tensor_v2(value,name)
   1408 def convert_to_tensor_v2(value,dtype=None,dtype_hint=None,name=None):
   1409   """Converts the given `value` to a `Tensor`."""
-> 1410   return convert_to_tensor(
   1411       value=value,1412       dtype=dtype,~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\profiler\\trace.py in wrapped(*args,**kwargs)
    161         with Trace(trace_name,**trace_kwargs):
    162           return func(*args,**kwargs)
--> 163       return func(*args,**kwargs)
    164 
    165     return wrapped

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\ops.py in convert_to_tensor(value,name,as_ref,preferred_dtype,ctx,accepted_result_types)
   1538 
   1539     if ret is None:
-> 1540       ret = conversion_func(value,name=name,as_ref=as_ref)
   1541 
   1542     if ret is NotImplemented:

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\tensor_conversion_registry.py in _default_conversion_function(***Failed resolving arguments***)
     50 def _default_conversion_function(value,as_ref):
     51   del as_ref  # Unused.
---> 52   return constant_op.constant(value,name=name)
     53 
     54 

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\constant_op.py in constant(value,shape,name)
    262     ValueError: if called on a symbolic tensor.
    263   """
--> 264   return _constant_impl(value,verify_shape=False,265                         allow_broadcast=True)
    266 

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\constant_op.py in _constant_impl(value,verify_shape,allow_broadcast)
    274       with trace.Trace("tf.constant"):
    275         return _constant_eager_impl(ctx,value,verify_shape)
--> 276     return _constant_eager_impl(ctx,verify_shape)
    277 
    278   g = ops.get_default_graph()

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\constant_op.py in _constant_eager_impl(ctx,verify_shape)
    299 def _constant_eager_impl(ctx,verify_shape):
    300   """Implementation of eager constant."""
--> 301   t = convert_to_eager_tensor(value,dtype)
    302   if shape is None:
    303     return t

~\\anaconda3\\lib\\site-packages\\tensorflow\\python\\framework\\constant_op.py in convert_to_eager_tensor(value,dtype)
     96       dtype = dtypes.as_dtype(dtype).as_datatype_enum
     97   ctx.ensure_initialized()
---> 98   return ops.EagerTensor(value,ctx.device_name,dtype)
     99 
    100 

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).

X_train.shape 是 (961,2),Y_train.shape 是 (961,)。

train data的dtype是object,更详细,train[''Message_body'']有object,train[''Label'']有int8。

我通过谷歌搜索找到了一些对任何其他类似错误的帮助。

我将 numpy 数组更改为 float32、np.int、...而且我还使用 tf.convert_to_tensor 来定义 y_train 但它们产生了相同的错误。

我认为这是因为我的数据是字符串。

/编写一个函数,要求从给定的向量A中删除元素值在x到y之间的所有元素(向量要求各个元素之间不能有间断), 函数原型为int del(int A ,int n , int x , int y),其...

/编写一个函数,要求从给定的向量A中删除元素值在x到y之间的所有元素(向量要求各个元素之间不能有间断), 函数原型为int del(int A ,int n , int x , int y),其...

/**
 * @author:(LiberHome)
 * @date:Created in 2019/2/28 19:39
 * @description:
 * @version:$
 */
/* 编写一个函数,要求从给定的向量A中删除元素值在x到y之间的所有元素(向量要求各个元素之间不能有间断),
函数原型为int del(int A ,int n , int x , int y),其中n为输入向量的维数,返回值为删除元素后的维数*/

public class page0602 {
    public static void main(String[] args) {
        int[] A={1,2,3,4,5,6,7,8,9,10};
        int result=-1;
        int x=3;
        int y=5;
        result=del(A,A.length,x,y);
    }

    private static int del(int[] arr, int len, int a, int b) {
        int i=a;
        int j=b+1;
        while (j+1<len){
            arr[i]=arr[j];
        }
        return len-(b+1-a);
    }


}

 

2022-03-11:int n, int[][] roads, int x, int y, n表示城市数量,城市编号0~n-1, roads[i][j] == distance,表示城市i到城市j距

2022-03-11:int n, int[][] roads, int x, int y, n表示城市数量,城市编号0~n-1, roads[i][j] == distance,表示城市i到城市j距

2022-03-11:int n, int[][] roads, int x, int y, n表示城市数量,城市编号0~n-1, roads[i][j] == distance,表示城市i到城市j距离为distance(无向图), 求城市x到城市y的最短距离。

答案2022-03-11:

有向图,没有负数环。小根堆。

代码用golang编写。代码如下:

package main

import (
	"fmt"
	"math"
	"sort"
)

func main() {
	roads := [][]int{{1, 2, 3}, {1, 3, 5}, {2, 3, 1}}
	n := 3
	x := 1
	y := 3
	ret := minDistance2(n, roads, x, y)
	fmt.Println(ret)
}

func minDistance2(n int, roads [][]int, x, y int) int {
	// 第一步生成邻接矩阵
	map0 := make([][]int, n+1)
	for i := 0; i < n+1; i++ {
		map0[i] = make([]int, n+1)
	}
	for i := 0; i <= n; i++ {
		for j := 0; j <= n; j++ {
			map0[i][j] = math.MaxInt64
		}
	}
	// 建立路!
	for _, road := range roads {
		map0[road[0]][road[1]] = getMin(map0[road[0]][road[1]], road[2])
		map0[road[1]][road[0]] = getMin(map0[road[1]][road[0]], road[2])
	}
	// computed[i] = true,表示从源出发点到i这个城市,已经计算出最短距离了
	// computed[i] = false,表示从源出发点到i这个城市,还没有计算出最短距离
	computed := make([]bool, n+1)
	// 距离小根堆
	//PriorityQueue<Node> heap = new PriorityQueue<>((a, b) -> (a.pathSum - b.pathSum));
	heap0 := make([]*Node, 0)
	heap0 = append(heap0, NewNode(x, 0))
	for len(heap0) > 0 {
		// x -> ... -> 当前的城市, 有距离
		sort.Slice(heap0, func(i, j int) bool {
			a := heap0[i]
			b := heap0[j]
			return a.pathSum < b.pathSum
		})
		cur := heap0[0]
		heap0 = heap0[1:]
		if computed[cur.city] {
			continue
		}
		// 没算过
		// 开始算!
		if cur.city == y {
			return cur.pathSum
		}
		computed[cur.city] = true
		for next := 1; next <= n; next++ {
			if next != cur.city && map0[cur.city][next] != math.MaxInt64 && !computed[next] {
				heap0 = append(heap0, NewNode(next, cur.pathSum+map0[cur.city][next]))
			}
		}
	}
	return math.MaxInt64
}

func getMin(a, b int) int {
	if a < b {
		return a
	} else {
		return b
	}
}

// 当前来到的Node,注意这不是城市的意思,这是就是一个普通的封装类
// Node封装了,当前来到的城市是什么,以及,从源出发点到这个城市的路径和是多少?
type Node struct {
	// 当前来到的城市编号
	city int
	// 从源出发点到这个城市的路径和
	pathSum int
}

func NewNode(c, p int) *Node {
	ans := &Node{}
	ans.city = c
	ans.pathSum = p
	return ans

}

执行结果如下: 在这里插入图片描述


左神java代码

2022-05-26:void add(int L, int R, int C)代表在arr[L...R]上每个数加C, int get(int L, int R)代表查询arr[L...R]上的累加

2022-05-26:void add(int L, int R, int C)代表在arr[L...R]上每个数加C, int get(int L, int R)代表查询arr[L...R]上的累加

2022-05-26:void add(int L, int R, int C)代表在arr[L...R]上每个数加C, int get(int L, int R)代表查询arr[L...R]上的累加和, 假设你可以在所有操作开始之前,重新排列arr。 请返回每一次get查询的结果都加在一起最大能是多少。 输入参数: int[] arr : 原始数组, int[][] ops,二维数组每一行解释如下: [a,b,c],如果数组有3个数,表示调用add(a,b,c), [a,b],如果数组有2个数,表示调用get(a,b), a和b表示arr范围,范围假设从1开始,不从0开始。 输出: 假设你可以在开始时重新排列arr,返回所有get操作返回值累计和最大是多少? 来自美团。

答案2022-05-26:

线段树。

代码用rust编写。代码如下:

fn main() {
    let mut arr: Vec<i32> = vec![1, 2, 3, 4, 5];
    let mut ops: Vec<Vec<i32>> = vec![vec![1, 3], vec![2, 4], vec![1, 5]];
    println!("ans = {}", max_gets(&mut arr, &mut ops));
}

fn max_gets(arr: &mut Vec<i32>, ops: &mut Vec<Vec<i32>>) -> i32 {
    let n = arr.len() as i32;
    let mut get_tree = SegmentTree::new(n);
    for op in ops.iter_mut() {
        if op.len() == 2 {
            get_tree.add(op[0], op[1], 1);
        }
    }
    let mut get_cnts: Vec<Vec<i32>> = vec![];
    for i in 0..n {
        get_cnts.push(vec![]);
        for _j in 0..2 {
            get_cnts[i as usize].push(0);
        }
    }
    let mut i: i32 = 1;
    let mut j: i32 = 0;
    while i <= n {
        get_cnts[j as usize][0] = j;
        get_cnts[j as usize][1] = get_tree.get(i, i);
        i += 1;
        j += 1;
    }
    get_cnts.sort_by(|a, b| a[1].cmp(&b[1]));
    arr.sort();
    let mut re_arrange: Vec<i32> = vec![];
    for _i in 0..n {
        re_arrange.push(0);
    }
    for i in 0..n {
        re_arrange[get_cnts[i as usize][0] as usize] = arr[i as usize];
    }
    let mut st = SegmentTree::new2(&mut re_arrange);
    let mut ans = 0;
    for op in ops.iter_mut() {
        if op.len() == 3 {
            st.add(op[0], op[1], op[2]);
        } else {
            ans += st.get(op[0], op[1]);
        }
    }
    return ans;
}
pub struct SegmentTree {
    pub n: i32,
    pub arr: Vec<i32>,
    pub sum: Vec<i32>,
    pub lazy: Vec<i32>,
}

impl SegmentTree {
    pub fn new(size: i32) -> Self {
        let mut n = size + 1;
        let mut sum: Vec<i32> = vec![];
        let mut lazy: Vec<i32> = vec![];
        let arr: Vec<i32> = vec![];
        for _i in 0..n << 2 {
            sum.push(0);
            lazy.push(0);
        }
        n -= 1;
        Self { n, arr, sum, lazy }
    }

    pub fn new2(origin: &mut Vec<i32>) -> Self {
        let mut n = origin.len() as i32 + 1;
        let mut arr: Vec<i32> = vec![];
        arr.push(0);
        for i in 1..n {
            arr.push(origin[(i - 1) as usize]);
        }
        let mut lazy: Vec<i32> = vec![];
        let mut sum: Vec<i32> = vec![];
        for _i in 0..n << 2 {
            sum.push(0);
            lazy.push(0);
        }
        n -= 1;
        let mut a = Self { n, arr, sum, lazy };
        a.build(1, n, 1);
        return a;
    }

    fn build(&mut self, l: i32, r: i32, rt: i32) {
        if l == r {
            self.sum[rt as usize] = self.arr[l as usize];
            return;
        }
        let mid = (l + r) >> 1;
        self.build(l, mid, rt << 1);
        self.build(mid + 1, r, rt << 1 | 1);
        self.push_up(rt);
    }

    fn push_up(&mut self, rt: i32) {
        self.sum[rt as usize] = self.sum[(rt << 1) as usize] + self.sum[(rt << 1 | 1) as usize];
    }

    fn push_down(&mut self, rt: i32, ln: i32, rn: i32) {
        if self.lazy[rt as usize] != 0 {
            self.lazy[(rt << 1) as usize] += self.lazy[rt as usize];
            self.sum[(rt << 1) as usize] += self.lazy[rt as usize] * ln;
            self.lazy[(rt << 1 | 1) as usize] += self.lazy[rt as usize];
            self.sum[(rt << 1 | 1) as usize] += self.lazy[rt as usize] * rn;
            self.lazy[rt as usize] = 0;
        }
    }

    pub fn add(&mut self, ll: i32, rr: i32, cc: i32) {
        self.add0(ll, rr, cc, 1, self.n, 1);
    }

    fn add0(&mut self, ll: i32, rr: i32, cc: i32, l: i32, r: i32, rt: i32) {
        if ll <= l && r <= rr {
            self.sum[rt as usize] += cc * (r - l + 1);
            self.lazy[rt as usize] += cc;
            return;
        }
        let mid = (l + r) >> 1;
        self.push_down(rt, mid - l + 1, r - mid);
        if ll <= mid {
            self.add0(ll, rr, cc, l, mid, rt << 1);
        }
        if rr > mid {
            self.add0(ll, rr, cc, mid + 1, r, rt << 1 | 1);
        }
        self.push_up(rt);
    }

    pub fn get(&mut self, ll: i32, rr: i32) -> i32 {
        return self.query(ll, rr, 1, self.n, 1);
    }

    fn query(&mut self, ll: i32, rr: i32, l: i32, r: i32, rt: i32) -> i32 {
        if ll <= l && r <= rr {
            return self.sum[rt as usize];
        }
        let mid = (l + r) >> 1;
        self.push_down(rt, mid - l + 1, r - mid);
        let mut ans = 0;
        if ll <= mid {
            ans += self.query(ll, rr, l, mid, rt << 1);
        }
        if rr > mid {
            ans += self.query(ll, rr, mid + 1, r, rt << 1 | 1);
        }
        return ans;
    }
}

执行结果如下:

在这里插入图片描述


左神java代码

android中用view.layout(int ,int,int,int)这4个参数是不是view的左上角的横坐标,纵坐标,view的宽,view的高?

android中用view.layout(int ,int,int,int)这4个参数是不是view的左上角的横坐标,纵坐标,view的宽,view的高?

今天的关于Numpy - ValueError:无法将 NumPy 数组转换为张量不支持的对象类型 int无法将变量类型((void)转换为对象)的分享已经结束,谢谢您的关注,如果想了解更多关于/编写一个函数,要求从给定的向量A中删除元素值在x到y之间的所有元素(向量要求各个元素之间不能有间断), 函数原型为int del(int A ,int n , int x , int y),其...、2022-03-11:int n, int[][] roads, int x, int y, n表示城市数量,城市编号0~n-1, roads[i][j] == distance,表示城市i到城市j距、2022-05-26:void add(int L, int R, int C)代表在arr[L...R]上每个数加C, int get(int L, int R)代表查询arr[L...R]上的累加、android中用view.layout(int ,int,int,int)这4个参数是不是view的左上角的横坐标,纵坐标,view的宽,view的高?的相关知识,请在本站进行查询。

本文标签: