This article assumes python 3.x. Also, please note that I am a python amateur. The first thing I wanted to do with machine learning was to do some learning on my own dataset, but the first thing I got stuck in was this variable.
import numpy as np
import chainer as Variable
The type must be Variable when throwing data to a machine learning network defined using chainer. At that time, it is necessary to always use np.array for the data given to the argument. This np.array is an array used by python's numpy, which is different from the standard python list ([]). Looking at the Chainer documentation, what you can specify for variable is [data – Data array of type either numpy.ndarray or cupy.ndarray.] Since it is described as, it is necessary to convert it to a numpy array once instead of using the list data as it is. Also, if you use floating point, you may need to convert to float32. I think the reason for using float32 is that chainer does not support float64, so an error occurs. This time, I considered some conversion patterns up to variable.
Example 1: ** Array **
x_train = [0,0,0,0,0]
x_np_train = np.array(x_train, dtype=np.float32)
x_val_train = Variable(x_np_train, 1)
By doing so, the array is converted to np.array while specifying float32, and it is further converted to variable.
Example 2: ** Multidimensional array ** You can follow the same procedure.
x_train = [[0.1, 0,2],[0.3, 0.4]]
x_np_train = np.array(x_train, dtype=np.float32)
x_val_train = Variable(x_np_train, 1)
Example 3: ** If np.array already exists **
x_train = [[0.1, 0,2],[0.3, 0.4]]
x_np_train = np.array(x_train)
x_np_train.dtype
Then it is dtype ('float64'). When dealing with np.array data from the beginning, I think that there are many cases where you have to cast to float32.
x_np_train.dtype = np.float32
x_val_train = Variable(x_np_train, 1)
Example 4: ** Variable has already been created with another type **
x_train = [[0.1, 0,2],[0.3, 0.4]]
x_np_train = np.array(x_train, dtype=np.float64)
x_val_train = Variable(x_np_train, 1)
x_val_train.data.dtype
If, dtype ('float64') is displayed. If nothing is done, an error will occur.
x_val_train.data.dtype = np.float32
x_val_train.data.dtype
Then, dtype ('float32') is displayed.
Recommended Posts