почему не работает код import torch def target_function(x): return 2*x torch.sin(2**-x)…
- User
почему не работает код import torch
def target_function(x): return 2x * torch.sin(2-x)
class RegressionNet(torch.nn.Module): def init(self, n_hidden_neurons): super().init() self.fc1 = torch.nn.Linear(1, n_hidden_neurons) self.act1 = torch.nn.Sigmoid() self.fc2 = torch.nn.Linear(n_hidden_neurons, n_hidden_neurons) #self.act2 = torch.nn.Tanh() #self.fc3 = torch.nn.Linear(n_hidden_neurons, 1) # your code here
net = RegressionNet(50)
------Dataset preparation start--------:
x_train = torch.linspace(-10, 5, 100) y_train = target_function(x_train) noise = torch.randn(y_train.shape) / 20. y_train = y_train + noise x_train.unsqueeze_(1) y_train.unsqueeze_(1)
x_validation = torch.linspace(-10, 5, 100) y_validation = target_function(x_validation) x_validation.unsqueeze_(1) y_validation.unsqueeze_(1)
------Dataset preparation end--------:
optimizer = torch.optim.Adam(net.parameters(), lr=0.001)
def loss(pred, target): squares = abs(pred - target) return squares.mean()
for epoch_index in range(1000): optimizer.zero_grad() y_pred = net.forward(x_train) loss_value = loss(y_pred, y_train) loss_val.backward() optimizer.step()
Проверка осуществляется вызовом кода:
def metric(pred, target):
return (pred - target).abs().mean()
print(metric(net.forward(x_validation), y_validation).item())
(раскомментируйте, если решаете задание локально)
def predict(net, x, y): y_pred = net.forward(x)
codeplt.plot(x.numpy(), y.numpy(), 'o', label='Groud truth') plt.plot(x.numpy(), y_pred.data.numpy(), 'o', c='r', label='Prediction'); plt.legend(loc='upper left') plt.xlabel('$x$') plt.ylabel('$y$')predict(net, x_validation, y_validation)
- Assistant
- User
Traceback (most recent call last): File "jailed_code", line 2, in import matplotlib.pyplot as plt File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 115, in _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/matplotlib/backends/init.py", line 62, in pylab_setup [backend_name], 0) File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py", line 4, in from . import tkagg # Paint image to Tk photo blitter extension. File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/matplotlib/backends/tkagg.py", line 5, in from six.moves import tkinter as Tk File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/six.py", line 92, in get result = self._resolve() File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/six.py", line 115, in _resolve return _import_module(self.mod) File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/six.py", line 82, in _import_module (name) File "/opt/pythonz/pythons/CPython-3.6.2/lib/python3.6/tkinter/.py", line 36, in import _tkinter # If this fails your Python may not be configured for Tk ModuleNotFoundError: No module named '_tkinter'
- Assistant
The error you encountered suggests that your execution environment does not have access to a necessary module for using
matplotlib, more specifically thetkintermodule, which is used bymatplotlibfor rendering plots in a Tkinter window. This is a common issue when running code in environments or servers where the graphical user interface (GUI) components are not fully installed or supported.Given this context, if your goal is simply to visualize data or the results of your neural network predictions without needing a GUI to display plots, you might consider saving the plots to files instead of attempting to display them in an unsupported environment.
- User
import torch import matplotlib.pyplot as plt
def target_function(x): return 2x * torch.sin(2-x)
class RegressionNet(torch.nn.Module): def init(self, n_hidden_neurons): super().init() self.fc1 = torch.nn.Linear(1, n_hidden_neurons) self.act1 = torch.nn.Sigmoid() self.fc2 = torch.nn.Linear(n_hidden_neurons, n_hidden_neurons) self.act2 = torch.nn.Tanh() self.fc3 = torch.nn.Linear(n_hidden_neurons, 1) # your code here
codedef forward(self, x): x = self.act1(self.fc1(x)) x = self.act2(self.fc2(x)) x = self.fc3(x) # Окончательный вывод сети return xnet = RegressionNet(50)
------Dataset preparation start--------:
x_train = torch.linspace(-10, 5, 100) y_train = target_function(x_train) noise = torch.randn(y_train.shape) / 20. y_train = y_train + noise x_train.unsqueeze_(1) y_train.unsqueeze_(1)
- Assistant