RuntimeError: Expected object of type torch.DoubleTensor but found type torch.FloatTensor for argument #3 'other'

I am going to test my simple linear regression. However I got trouble with my program below:

x_train = x.reshape(-1, 1).astype('float32')
y_train = y.reshape(-1, 1).astype('float32')

class LinearRegressionModel(nn.Module):
    def __init__(self, input_dim, output_dim):
        super(LinearRegressionModel, self).__init__()
        self.linear = nn.Linear(input_dim, output_dim)
    
    def forward(self, x):
        out = self.linear(x)
        return out

input_dim = x_train.shape[1]
output_dim = y_train.shape[1]
input_dim, output_dim

model = LinearRegressionModel(input_dim, output_dim)

criterion = nn.MSELoss()
[w, b] = model.parameters()

def get_param_values():
    return w.data[0][0], b.data[0]

and my definition of graph

def plot_current_fit(title=""):
    plt.figure(figsize=(12,4))
    plt.title(title)
    plt.scatter(x, y, s=8)
    w1 = w.data[0][0]
    b1 = b.data[0]
    x1 = np.array([0., 1.])
    y1 = x1 * w1 + b1
    plt.plot(x1, y1, 'r', label='Current Fit ({:.3f}, {:.3f})'.format(w1, b1))
    plt.xlabel('x (input)')
    plt.ylabel('y (target)')
    plt.legend()
    plt.show()

and I got this error

RuntimeError Traceback (most recent call last)
in ()
1
2
----> 3 plot_current_fit(‘Before training’)
4

in plot_current_fit(title)
6 b1 = b.data[0]
7 x1 = np.array([0., 1.])
----> 8 y1 = x1 * w1 + b1
9 plt.plot(x1, y1, ‘r’, label=‘Current Fit ({:.3f}, {:.3f})’.format(w1, b1))
10 plt.xlabel(‘x (input)’)

RuntimeError: Expected object of type torch.DoubleTensor but found type torch.FloatTensor for argument #3 'other

Your x1 was created as np.float64. Try the following:

x1 = np.array([0., 1.], dtype=np.float32)

Thanks for your message.

After I followed your instructions:


def plot_current_fit(title=""):
    plt.figure(figsize=(12,4))
    plt.title(title)
    plt.scatter(x, y, s=8)
    w1 = w.data[0][0]
    b1 = b.data[0]
    # x1 = np.array([0., 1.])
    **x1 = np.array([0., 1.], dtype=np.float32)**
    y1 = x1 * w1 + b1
    plt.plot(x1, y1, 'r', label='Current Fit ({:.3f}, {:.3f})'.format(w1, b1))
    plt.xlabel('x (input)')
    plt.ylabel('y (target)')
    plt.legend()
    plt.show()

and

%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, (ax1) = plt.subplots(1, figsize=(12, 6))
ax1.scatter(x, y, s=8)

w1, b1 = get_param_values()
# x1 = np.array([0., 1.])
**x1 = np.array([0., 1.], dtype=np.float32)**
y1 = x1 * w1 + b1
fit, = ax1.plot(x1, y1, 'r', label='Predicted'.format(w1, b1))
ax1.plot(x1, x1 * m + c, 'g', label='Real')
ax1.legend()
ax1.set_title('Linear Regression')

def init():
    ax1.set_ylim(0, 6)
    return fit,

def animate(i):
    loss = run_epoch(i)
    w1, b1 = get_param_values()
    y1 = x1 * w1 + b1
    fit.set_ydata(y1)

epochs = np.arange(1, 250)
ani = FuncAnimation(fig, animate, epochs, init_func=init, interval=100, blit=True, repeat=False)
plt.show()

However, I got other error like this:


AttributeError Traceback (most recent call last)
in ()
10 x1 = np.array([0., 1.], dtype=np.float32)
11 y1 = x1 * w1 + b1
—> 12 fit, = ax1.plot(x1, y1, ‘r’, label=‘Predicted’.format(w1, b1))
13 ax1.plot(x1, x1 * m + c, ‘g’, label=‘Real’)
14 ax1.legend()

/usr/local/lib/python3.6/dist-packages/matplotlib/init.py in inner(ax, *args, **kwargs)
1853 “the Matplotlib list!)” % (label_namer, func.name),
1854 RuntimeWarning, stacklevel=2)
-> 1855 return func(ax, *args, **kwargs)
1856
1857 inner.doc = _add_data_doc(inner.doc,

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py in plot(self, *args, **kwargs)
1525 kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
1526
-> 1527 for line in self._get_lines(*args, **kwargs):
1528 self.add_line(line)
1529 lines.append(line)

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _grab_next_args(self, *args, **kwargs)
404 this += args[0],
405 args = args[1:]
–> 406 for seg in self._plot_args(this, kwargs):
407 yield seg
408

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
381 x, y = index_of(tup[-1])
382
–> 383 x, y = self._xy_from_xy(x, y)
384
385 if self.command == ‘plot’:

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
241 raise ValueError("x and y must have same first dimension, but "
242 “have shapes {} and {}”.format(x.shape, y.shape))
–> 243 if x.ndim > 2 or y.ndim > 2:
244 raise ValueError("x and y can be no greater than 2-D, but have "
245 “shapes {} and {}”.format(x.shape, y.shape))

AttributeError: ‘Tensor’ object has no attribute ‘ndim’

Try to convert all tensors to np.arrays using tensor.numpy().