文章目录
1. plt.show() 与 zsh: segmentation fault
import matplotlib.pyplot as plt
plt.show()
在pycharm中使用run执行时,正常
在terminal中使用python XXX.py
执行时,报错:zsh: segmentation fault python XXX.py
并且显示python 3.7异常退出。将引用如下修改,正常运行。
import matplotlib as mpl
mpl.use('TkAgg') #必须要写在这两个import中间
import matplotlib.pyplot as plt
plt.show()
2.类型转换:numpy和Tensor
使用np.array(a)
报错:RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
当计算中的数据类型为tensor时,也就是说并不是直接创建的tensor数据,而是通过深度网络或者其他方式计算得到的tensor,由于它带梯度值,Python开发者在这里对用户机进行提示,所以不能直接转为numpy格式,因此类型转换语句修改为a.detach().numpy()
3. 深度学习网络的输入数据
使用深度学习网络(Pytorch)进行预测:model(x)
,报错if input.dim() == 2 and bias is not None: AttributeError: ‘numpy.ndarray’ object has no attribute ‘dim’
,因为x为numpy.ndarray类型,而网络接受的数据是Tensor,因此需要将x进行类型转换:torch.Tensor(x)
4.引入自己的py文件,终端运行
背景:在pycharm中创建一个名为01的文件,在01中创建codes文件夹、a.py和d.py,codes文件夹中创建b.py和c.py,如下图所示:
(1)pycharm中运行
① a.py中引入d.py
from d import *
② b.py中引入c.py
from codes.c import *
(2)终端中运行
① a.py中引入d.py
依然是from d import *
② b.py中引入c.py
除了from codes.c import *
还要加上
import sys
sys.path.append(r"……/01") #codes文件夹上一级,即01文件夹的绝对路径
5. concat列连接
f = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
f1 = pd.concat([f, pd.DataFrame({"A": 20, "B": 40}, index=[0])])
print(f1)
A B
0 1 2
1 3 4
0 20 40
f2 = pd.DataFrame([[9], [90]], index=[0, 1])
print(f2)
0
0 9
1 90
pd.concat([f2, f1], axis=1,join='inner')
报错ValueError: Shape of passed values is (5, 3), indices imply (3, 3)
因为对于f2来说,f1中有两个索引是0,因而不确定要链接哪个索引0
因而改为
f3 = pd.concat([f1, f2], axis=1,join='inner')
print(f3)
A B 0
0 1 2 9
1 3 4 90
0 20 40 9
这样对于f1来说,f2中只有一个索引是0