plt.scatter(self.target_sites[0][0], self.target_sites[1][0], color='', marker='o', edgecolors='b', s=50) # 什么意思
时间: 2023-05-18 20:02:53 浏览: 71
这是一个使用matplotlib库中的scatter函数绘制散点图的代码。其中self.target_sites是一个二维数组,第一个维度表示x轴坐标,第二个维度表示y轴坐标。这里取了第一个元素作为散点的位置。color=''表示散点不填充颜色,marker='o'表示散点形状为圆形,edgecolors='b'表示散点边缘颜色为蓝色,s=50表示散点大小为50。
相关问题
class RandomWalk(): def __init__(self,point_num=5000): self.point_num = point_num self.xval = [0] self.yval = [0] def fill_walk(self): while len(self.xval)<self.point_num: x_direction = choice([1,-1]) step_num = choice([0,1,2,3,4]) xstep = x_direction * step_num y_direction = choice([1,-1]) step_num = choice([0,1,2,3,4]) ystep = y_direction * step_num if xstep == 0 and ystep==0: continue x_next = self.xval[-1] + xstep y_next = self.yval[-1] + ystep self.xval.append(x_next) self.yval.append(y_next) rw = RandomWalk(50000) rw.fill_walk() point_numbers = list(range(rw.point_num())) plt.scatter(rw.x_val,rw.y_val,c=point_numbers,cmap=plt.cm.Blues,edgecolor = 'none',s=2) plt.scatter(0,0,c='green',edgecolors='none',s=100) plt.scatter(rw.x_val[-1],rw.y_val[-1],c='red',edgecolor='none',s=100) plt.axes().get_xaxis().set_visible(False) plt.axes().get_xaxis().set_yisible(False) plt.show()修改代码
以下是修改后的代码:
```python
import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
def __init__(self, point_num=5000):
self.point_num = point_num
self.x_val = [0]
self.y_val = [0]
def fill_walk(self):
while len(self.x_val) < self.point_num:
x_direction = choice([1, -1])
x_step = choice([0, 1, 2, 3, 4])
x_val = x_direction * x_step
y_direction = choice([1, -1])
y_step = choice([0, 1, 2, 3, 4])
y_val = y_direction * y_step
if x_val == 0 and y_val == 0:
continue
next_x = self.x_val[-1] + x_val
next_y = self.y_val[-1] + y_val
self.x_val.append(next_x)
self.y_val.append(next_y)
rw = RandomWalk(50000)
rw.fill_walk()
point_numbers = list(range(rw.point_num))
plt.scatter(rw.x_val, rw.y_val, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=2)
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(rw.x_val[-1], rw.y_val[-1], c='red', edgecolor='none', s=100)
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
```
主要的修改包括:
1. `xval` 和 `yval` 改为 `x_val` 和 `y_val`,以符合 Python 的命名规范。
2. `rw.point_num()` 改为 `rw.point_num`,因为 `point_num` 是一个属性而不是方法。
3. `plt.axes().get_xaxis().set_yisible(False)` 改为 `plt.axes().get_yaxis().set_visible(False)`,因为原来的代码中打错了单词。
import torch import matplotlib.pyplot as plt def features(x): x = x.unsqueeze(1) return torch.cat([x ** i for i in range(1, 5)], 1) x_weight = torch.Tensor([-1.13, -2.14, 3.15, -0.01]).unsqueeze(1) b = torch.Tensor([0.512]) def target(x): return x.mm(x_weight) + b.item() def get_batch_data(batch_size): batch_x = torch.rand(batch_size) features_x = features(batch_x) target_y = target(features_x) return features_x, target_y class PR(torch.nn.Module): def __init__(self): super(PR, self).__init__() self.poly = torch.nn.Linear(4, 1) def forward(self, x): return self.poly(x) epochs = 10000 batch_size = 32 model = PR() criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), 0.01) for i in range(epochs): batch_x, batch_y = get_batch_data(batch_size) out = model(batch_x) loss = criterion(out, batch_y) optimizer.zero_grad() loss.backward() optimizer.step() if(i % 100 == 0): print(f"Epoch:{i+1}/{epochs}, loss:{loss.item}") if(i%1000 == 0): predict = model(features(batch_x)) plt.plot(batch_x.data.numpy(), predict.squeeze().data.numpy(), "r") loss = criterion(predict, batch_y) plt.title(f"Loss:{loss.item()}") plt.xlabel("X") plt.ylabel("Y") plt.scatter(batch_x, batch_y) plt.show()哪里出错了
代码有一个小错误,第26行应该是`print(f"Epoch:{i+1}/{epochs}, loss:{loss.item()}")`,需要加上括号。另外,在第34行,应该是`loss = criterion(out, batch_y)`,而不是`loss = criterion(predict, batch_y)`。正确的代码如下所示:
```
import torch
import matplotlib.pyplot as plt
def features(x):
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, 5)], 1)
x_weight = torch.Tensor([-1.13, -2.14, 3.15, -0.01]).unsqueeze(1)
b = torch.Tensor([0.512])
def target(x):
return x.mm(x_weight) + b.item()
def get_batch_data(batch_size):
batch_x = torch.rand(batch_size)
features_x = features(batch_x)
target_y = target(features_x)
return features_x, target_y
class PR(torch.nn.Module):
def __init__(self):
super(PR, self).__init__()
self.poly = torch.nn.Linear(4, 1)
def forward(self, x):
return self.poly(x)
epochs = 10000
batch_size = 32
model = PR()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), 0.01)
for i in range(epochs):
batch_x, batch_y = get_batch_data(batch_size)
out = model(batch_x)
loss = criterion(out, batch_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if(i % 100 == 0):
print(f"Epoch:{i+1}/{epochs}, loss:{loss.item()}")
if(i%1000 == 0):
predict = model(features(batch_x))
plt.plot(batch_x.data.numpy(), predict.squeeze().data.numpy(), "r")
loss = criterion(out, batch_y)
plt.title(f"Loss:{loss.item()}")
plt.xlabel("X")
plt.ylabel("Y")
plt.scatter(batch_x, batch_y)
plt.show()
```
阅读全文