2021-09-20


```python
#工具一  tensorflow 主要集中keras模块
import tensorflow as tf

print(tf.__version__)
#加载数据集
data=tf.keras.datasets.mnist()
data_dir=tf.keras.utils.get_file()
import tensorflow_dataset as tfds
data=tfds.load(name='imdb_reviews',split=['train','test'],batch_size=1)

#构建模型:
#1.自建
model=tf.keras.Sequential(
    tf.keras.layers.Conv2D(),
    tf.keras.layers.Dense(),
    tf.keras.layers.Flatten()

)
model.summary()
#2、引入他人的模型参数
import tensorflow_hub as hub
model="https://tfhub.dev/google/nnlm-en-dim50/2"
hub_layer=hub.KerasLayer(model,input_shape=[])
model=tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(1))
model.summary()

#配置模型,加入优化器和损失函数
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
    loss==tf.keras.losses.BinaryCrossentropy()
)

# 训练模型
history=model.fit()#history.history 是一个字典,the key is ['loss', 'accuracy', 'val_loss', 'val_accuracy']
result=model.evaluate()
#结果展示
import matplotlib.pyplot as plt

#工具二:torch(torch.nn模块)

import torch
import torchvision
from torch.utils.data import Dataset,DataLoader
# torch.nn,torch.optim,torch.utils.data.Dataset
#加载数据集
#直接加载
data=torchvision.datasets.CIFAR10(root='data',train=True,target_transform=torchvision.transforms.ToTensor())
#从文件夹导入
import pickle
with open(file=) as tf:
	data=pickle.load(f)
data=DataLoader(dataset=data,batch_size=4)
#建立模型
class Model(torch.nn):
    def __init__(self):
        super(Model, self).__init__()
        self.model=torch.nn.Sequential(
            torch.nn.Conv2d(),
            ...

        )
    def forward(self,result):
        result=self.model
        return result
model=Model()
loss=torch.nn.MSELoss()
optimizer=torch.optim.Adam()
#训练
for epoch in range(epochs):
    pre=model(x_train)
    loss=loss(pre,y_train)
    optimizer.step()
    optimizer.zero_grad()
    

上一篇:AI小白的学习记录


下一篇:Python3.9+tensorflow2.6.0安装(留作记录)