# TensorflowJs – what are tensors, creating and reshaping tensors, limiting the data types

So what is a tensor, anyway?

A tensor is just a fancy general name for any type of data structure such as arrays, matrixes (2d arrays), cubes (3d arrays), and so on. A tensor is just a structured collection of numbers.

Please note that we are not limited to a maximum or a 3d array. In the documentation, we have methods to create including 6d tensors. Not even sure what a 6d array is called.

We even have a 0d tensors. They are called scalars and they can be seen as similar to simple variables:

``````const intTensor = tf.scalar(12)
intTensor.print() // 12``````

## Creating tensors in TensorflowJs

One general way to create a new tensor with any number of dimensions in TensorflowJs is to use the tf.tensor() method:

``````// create a 1d tensor
tf.tensor([1, 2, 3, 4]).print();

// create a 2d tensor
tf.tensor([[1, 2, 3], [4, 5, 6]]).print();``````

However, even if the `tf.tensor()` method provides flexibility, the recommended way of creating tensors in TensorflowJs is to use methods such as tensor1d() to tensor6d(), as it makes the code more readable:

``````tf.tensor1d([1, 2]).print()
tf.tensor2d([[1, 2], [1, 2]]).print()
tf.tensor3d([[, ], [, ]]).print()
// till tf.tensor6d``````

## Getting the shape of a tensor and reshaping it

We can read the shape of a tensor by using its `shape` attribute:

``````const x = tf.tensor2d([[1, 2], [3, 4]])
console.log('The shape of X is:', a.shape) // [2,2]
x.print() // [[1, 2], [3, 4]]``````

We can also reshape a tensor to change its number of dimensions and update the way the data is stored in that tensor.

So, if we want to reshape the initial `x` tensor of 2rows and 2cols into one of 1row and 4cols we can do this:

``````const y = x.reshape([4, 1])
console.log('B shape:', y .shape) // [1,2,3,4]
y .print() // [1,2,3,4]``````

For tensors with more than 1 dimension, we can pass the shape as the second parameter to the constructor function:

``````// Pass a flat array and specify a shape.
const mat = tf.tensor2d([1, 2, 3, 4], [2, 2])
mat.print() // [[1, 2], [3, 4]]``````

In the case where we don't respect the shape of a tensor we will get an error like the one below:

``Uncaught Error: tensor1d() requires values to be a flat/TypedArray at Object.pE [as tensor1d]``

## Restrict the data type of a tensor in TensorflowJs

Given that Javascript does not have data types, we have a parameter named `dtype` that we can pass to set the type of data stored in that tensor:

``````const intTensor = tf.tensor1d([10, 20, 30], 'int32')
intTensor.print()``````

The data type can be any of the following, with `float32` as the default option:

``('float32'|'int32'|'bool'|'complex64'|'string')``

If we want to read the data type of a tensor we can do:

``console.log(intTensor.dtype)``

If we break the data type convention TensorflowJs will try to cast the wrong data to its closest rounding:

``````const intTensor = tf.tensor1d([1.5, 2, 'two'], 'int32')
intTensor.print() // [1,2,0]``````

Next, you can checkout some basic tensor operations and get the individual values from a tensor.

#### 📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

#### 📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

## 📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:
{"ft_lang_label":"__label__en","ft_lang_prob":0.7914932,"math_prob":0.93935245,"size":3368,"snap":"2023-40-2023-50","text_gpt3_token_len":946,"char_repetition_ratio":0.14565992,"word_repetition_ratio":0.14561403,"special_character_ratio":0.29780284,"punctuation_ratio":0.17315437,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98507184,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-11-30T21:53:50Z\",\"WARC-Record-ID\":\"<urn:uuid:45194eeb-3474-402b-aac0-14c6b492b8a2>\",\"Content-Length\":\"73156\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:29ea69c0-09f9-4ad2-bb61-ebc3cbc16316>\",\"WARC-Concurrent-To\":\"<urn:uuid:f2700f1d-5c73-425d-b432-6dd6fc7ffe88>\",\"WARC-IP-Address\":\"85.9.27.10\",\"WARC-Target-URI\":\"https://www.js-craft.io/blog/tensorflowjs-what-are-tensors-creating-reshaping-tensors-limiting-data-types/\",\"WARC-Payload-Digest\":\"sha1:HR5TF7TZOKY5XUAL6K5TVZCESNQRON3X\",\"WARC-Block-Digest\":\"sha1:NJCMMN4KMWCDBMIVIR5WK5QBXMINLQG5\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-50/CC-MAIN-2023-50_segments_1700679100232.63_warc_CC-MAIN-20231130193829-20231130223829-00561.warc.gz\"}"}