我也想挨着顺序慢慢学,时间来不及了,穿插进行。

目前同时准备的有

数据结构准备在力扣刷题,python基础,深度学习基础,八股每天背一两个问题

早上晚上都有课,下午学了一点张量。

创建张量

import torch

# 创建一维张量(包含0到11的整数序列)
x = torch.arange(12)
print(x)               # 打印张量内容
print(x.shape)         # 查看张量形状(一维,长度12)
print(x.numel())       # 计算张量中元素的总个数(12)

# 创建一维张量并重塑为3行4列的二维张量(reshape不改变元素总数)
y = torch.arange(12).reshape(3, 4)
print(y)

# 创建形状为2×3×4的全0张量(三维张量,元素全为0)
z = torch.zeros((2, 3, 4))
print(z)

# 创建形状为1×2×4的全1张量(三维张量,元素全为1)
w = torch.ones((1, 2, 4))
print(w)

# 创建形状为3×4的随机张量(元素服从标准正态分布N(0,1))
a = torch.randn(3, 4)
print(a)

# 从Python列表直接创建二维张量(手动指定元素值)
b = torch.tensor([[2,1,4,3],[1,2,3,4],[4,3,2,1]])
print(b)
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
torch.Size([12])
12
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
tensor([[[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]],

        [[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]])
tensor([[[1., 1., 1., 1.],
         [1., 1., 1., 1.]]])
tensor([[-0.3502, -1.3474,  1.2167,  1.3067],
        [-1.6128,  0.2049, -0.2820, -0.3725],
        [ 1.1904, -0.1356,  0.5495,  0.6055]])
tensor([[2, 1, 4, 3],
        [1, 2, 3, 4],
        [4, 3, 2, 1]])

张量运算拼接

import torch

# 创建两个一维张量,用于基础算术运算
x = torch.tensor([1,2,4,8])
y = torch.tensor([2,2,2,2])
# 逐元素算术运算(加、乘、减、除),维度需一致
print(x+y, x*y, x-y, x/y)

# 创建3行4列的浮点型二维张量(dtype指定数据类型)
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
# 手动创建与X同形状的二维张量(浮点型)
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
# 按行拼接(dim=0):拼接后形状为6行4列(行数相加,列数不变)
print(torch.cat((X, Y), dim=0))
# 按列拼接(dim=1):拼接后形状为3行8列(列数相加,行数不变)
print(torch.cat((X, Y), dim=1))

# 张量转NumPy数组(共享内存,修改一方另一方会同步)
A = X.numpy()
# NumPy数组转回PyTorch张量
B = torch.tensor(A)
# 打印类型,验证转换结果(numpy.ndarray / torch.Tensor)
print(type(A), type(B))
tensor([ 3,  4,  6, 10]) tensor([ 2,  4,  8, 16]) tensor([-1,  0,  2,  6]) tensor([0.5000, 1.0000, 2.0000, 4.0000])
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.],
        [ 2.,  1.,  4.,  3.],
        [ 1.,  2.,  3.,  4.],
        [ 4.,  3.,  2.,  1.]])
tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
        [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
        [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]])
<class 'numpy.ndarray'> <class 'torch.Tensor'>

数据处理

建立了一个CSV文件,查看文件,用均值填充缺失值,转为张量

import os
import pandas as pd
import torch

# 创建数据文件夹并写入测试数据
os.makedirs(os.path.join('..', 'data'), exist_ok=True)
data_file = os.path.join('..', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
    f.write('NumRooms,Alley,Price\n')
    f.write('NA,Pave,127500\n')
    f.write('2,NA,106000\n')
    f.write('4,NA,178100\n')
    f.write('NA,NA,140000\n')

# 读取CSV数据为DataFrame
data = pd.read_csv(data_file)
print("原始数据:")
print(data)
print("-" * 40)

# 拆分输入特征(前2列)和输出标签(第3列),注意iloc[:,2]是取列而非行
inputs, outputs = data.iloc[:, 0:2], data.iloc[:, 2]

# 填充数值列NumRooms的缺失值(均值填充)
inputs['NumRooms'] = inputs['NumRooms'].fillna(inputs['NumRooms'].mean())

# 对类别列Alley做独热编码,dummy_na=True保留缺失值类别
inputs = pd.get_dummies(inputs, dummy_na=True)
print("独热编码后的inputs:")
print(inputs)
print("-" * 40)

# 转换为PyTorch张量,指定float类型;y.reshape(-1,1)转为二维(适配模型输入)
x = torch.tensor(inputs.to_numpy(dtype=float))
y = torch.tensor(outputs.to_numpy(dtype=float)).reshape(-1, 1)

# 打印最终张量
print("输入张量x:")
print(x)
print("\n输出张量y:")
print(y)
   NumRooms Alley   Price
0       NaN  Pave  127500
1       2.0   NaN  106000
2       4.0   NaN  178100
3       NaN   NaN  140000
4       1.0   NaN  163000
   NumRooms Alley
0  2.333333  Pave
1  2.000000   NaN
2  4.000000   NaN
3  2.333333   NaN
4  1.000000   NaN
tensor([[2.3333, 1.0000, 0.0000],
        [2.0000, 0.0000, 1.0000],
        [4.0000, 0.0000, 1.0000],
        [2.3333, 0.0000, 1.0000],
        [1.0000, 0.0000, 1.0000]], dtype=torch.float64) tensor([127500., 106000., 178100., 140000., 163000.], dtype=torch.float64)

进程已结束,退出代码0

更多推荐