手把手教你用python演奏音乐(以富士山下为例)

目录

1.代码

2.文本

3.效果图 


这两天,我非常无聊,琢磨出了十二平均律,并利用mido库进行编写,实现了利用python演奏音乐。废话不多说了,直接上代码,供诸位大佬把玩。

1.代码

import os
import threading
import time

import mido
import pygame

mid = mido.MidiFile()
track = mido.MidiTrack()
mid.tracks.append(track)


def play_midi(file):
    freq = 44100
    bitsize = -16
    channels = 2
    buffer = 1024
    pygame.mixer.init(freq, bitsize, channels, buffer)
    pygame.mixer.music.set_volume(1)
    clock = pygame.time.Clock()
    try:
        pygame.mixer.music.load(file)
    except:
        import traceback
        print(traceback.format_exc())
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        clock.tick(30)


KEY = 1
neg_SPEED = 1.2  # 数值越小速度越快


# bpm = \frac{60000000}{tempo}
def music(note, base_num, base_time):
    base_num, base_time = base_num + KEY, base_time * neg_SPEED
    # mid = mido.MidiFile()
    # track = mido.MidiTrack()
    # mid.tracks.append(track)
    # meta_time = 60 * 60 * 10 / bpm
    major_notes = [0, 2, 2, 1, 2, 2, 2, 1]
    base_note = 60
    track.append(mido.Message('note_on', note=base_note + base_num * 12 + sum(major_notes[0:note]), velocity=96, time=0,
                              channel=1))
    track.append(mido.Message('note_off', note=base_note + base_num * 12 + sum(major_notes[0:note]), velocity=96,
                              time=int(480 * base_time), channel=1))
    # print('正在合成(',note, base_num, base_time,')音')
    # track.append(mido.Message('note_on', note=base_note, velocity=96, time=0))
    # track.append(mido.Message('note_off', note=base_note, velocity=96, time=480*base_time))
    # mid.save('1.mid')
    # play_midi('1.mid')


def lemon_music():
    a = 0
    b = 1
    # 前奏
    # music(1, a+b + 1, 2)

    music(1, a + 1, 1 * 2)
    music(6, a + 0, 0.5 * 2)
    music(1, a + 1, 0.5 * 2)
    music(3, a + 1, 1)
    music(3, a + 1, 0.5)
    music(2, a + 1, 0.5)

    music(3, a + 1, 0.5)
    music(2, a + 1, 0.5)
    music(3, a + 1, 0.5)
    music(2, a + 1, 0.5)
    music(1, a + 1, 0.5)
    music(7, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)

    music(6, a + 0, 1)
    music(7, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(2, a + 1, 1)
    music(3, a + 1, 0.5)
    music(4, a + 1, 0.5)

    music(5, a + 1, 2)
    music(3, a + 1, 0.5)
    music(5, a + 1, 1)
    music(2, a + 1, 0.5)

    music(3, a + b + 1, 0.25)
    music(1, a + b + 1, 0.25)
    music(6, a + b + 0, 0.25)
    music(3, a + b + 0, 0.25)
    music(3, a + b + 1, 0.25)
    music(1, a + b + 1, 0.25)
    music(6, a + b + 0, 0.25)
    music(3, a + b + 0, 0.25)
    music(3, a + b + 1, 0.25)
    music(1, a + b + 1, 0.25)
    music(6, a + b + 0, 0.25)
    music(3, a + b + 0, 0.25)
    music(3, a + b + 1, 0.25)
    music(1, a + b + 1, 0.25)
    music(6, a + b + 0, 0.25)
    music(3, a + b + 0, 0.25)

    music(2, a + b + 1, 0.25)
    music(7, a + b + 0, 0.25)
    music(5, a + b + 0, 0.25)
    music(2, a + b + 0, 0.25)
    music(2, a + b + 1, 0.25)
    music(7, a + b + 0, 0.25)
    music(5, a + b + 0, 0.25)
    music(2, a + b + 0, 0.25)
    music(2, a + b + 1, 0.25)
    music(7, a + b + 0, 0.25)
    music(5, a + b + 0, 0.25)
    music(2, a + b + 0, 0.25)
    music(2, a + b + 1, 0.25)
    music(7, a + b + 0, 0.25)
    music(5, a + b + 0, 0.25)
    music(2, a + b + 0, 0.25)

    music(1, a + b + 1, 0.25)
    music(6, a + b + 0, 0.25)
    music(4, a + b + 0, 0.25)
    music(1, a + b + 0, 0.25)
    music(1, a + b + 1, 0.25)
    music(6, a + b + 0, 0.25)
    music(4, a + b + 0, 0.25)
    music(1, a + b + 0, 0.25)
    music(7, a + b + 0, 0.25)
    music(5, a + b + 0, 0.25)
    music(2, a + b + 0, 0.25)
    music(7, a + b + 0, 0.25)
    music(7, a + b + 0, 0.25)
    music(5, a + b + 0, 0.25)
    music(2, a + b + 0, 0.25)
    music(7, a + b + 0, 0.25)

    music(1, a + b + 1, 4)

    # 主歌
    track.append(mido.Message('note_on', note=0, velocity=0, time=0))
    track.append(mido.Message('note_off', note=0, velocity=0, time=480 * 1))
    music(5, a - 1, 1)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(3, a + 0, 1)
    music(3, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(3, a + 0, 1)
    music(3, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.75)
    music(1, a + 0, 0.75)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.75)
    music(2, a + 0, 0.75)
    music(3, a + 0, 0.5)

    music(3, a + 0, 1.5)
    music(5, a - 1, 0.5)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(5, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(3, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.75)
    music(2, a + 0, 0.75)
    music(2, a + 0, 0.5)
    music(2, a + 0, 0.75)
    music(1, a + 0, 0.75)
    music(6, a - 1, 0.5)

    music(2, a + 0, 1.5)
    music(5, a - 1, 0.5)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(3, a + 0, 1)
    music(5, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(3, a + 0, 1)
    music(6, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.75)
    music(1, a + 0, 0.75)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.75)
    music(2, a + 0, 0.75)
    music(3, a + 0, 0.5)

    music(5, a + 0, 1.5)
    music(5, a - 1, 0.5)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(6, a + 0, 1)
    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(3, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.75)
    music(2, a + 0, 0.75)
    music(2, a + 0, 0.5)
    music(2, a + 0, 0.75)
    music(1, a + 0, 0.75)
    music(6, a - 1, 0.5)

    music(1, a + 0, 1.5)
    # 副歌
    music(1, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(7, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.5)

    music(1, a + 1, 0.75)
    music(6, a + 0, 0.75)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)

    music(3, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 1)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)

    music(6, a + 0, 0.75)
    music(6, a + 0, 0.75)
    music(6, a + 0, 0.5)
    music(6, a + 0, 0.75)
    music(5, a + 0, 0.75)
    music(6, a + 0, 0.5)

    music(5, a + 0, 0.5)
    music(3, a + 0, 1.5)
    track.append(mido.Message('note_on', note=0, velocity=0, time=0))
    track.append(mido.Message('note_off', note=0, velocity=0, time=480 * 1))
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(6, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(1, a + 0, 0.5)
    music(1, a + 0, 0.5)
    music(1, a + 1, 0.5)

    music(1, a + 1, 0.75)
    music(1, a + 1, 0.75)
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.75)
    music(1, a + 1, 0.5)

    music(6, a + 0, 1.5)
    music(5, a + 0, 1)
    music(1, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(7, a + 0, 0.5)

    music(1, a + 1, 0.5)
    music(7, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)

    music(3, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 1)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)

    music(6, a + 0, 0.75)
    music(6, a + 0, 0.75)
    music(6, a + 0, 0.5)
    music(6, a + 0, 0.75)
    music(5, a + 0, 0.75)
    music(6, a + 0, 0.5)

    music(5, a + 0, 0.5)
    music(3, a + 0, 1.5)
    track.append(mido.Message('note_on', note=0, velocity=0, time=0))
    track.append(mido.Message('note_off', note=0, velocity=0, time=480 * 1))
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(6, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)
    music(1, a + 1, 2)
    track.append(mido.Message('note_on', note=0, velocity=0, time=0))
    track.append(mido.Message('note_off', note=0, velocity=0, time=480 * 3))
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.5)
    music(1, a + 1, 0.5)

    music(6, a + 0, 0.5)
    music(5, a + 0, 1)
    music(5, 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)

    music(3, a + 0, 0.5)
    music(2, a + 0, 1)
    music(1, a + 0, 0.5)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)

    music(1, a + 0, 4)
    # 第二段
    track.append(mido.Message('note_on', note=0, velocity=0, time=0))
    track.append(mido.Message('note_off', note=0, velocity=0, time=480 * 1))
    music(5, a - 1, 1)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(3, a + 0, 1)
    music(3, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(3, a + 0, 1)
    music(3, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.75)
    music(1, a + 0, 0.75)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.75)
    music(2, a + 0, 0.75)
    music(3, a + 0, 0.5)

    music(3, a + 0, 1.5)
    music(5, a - 1, 0.5)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(5, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(3, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.75)
    music(2, a + 0, 0.75)
    music(2, a + 0, 0.5)
    music(2, a + 0, 0.75)
    music(1, a + 0, 0.75)
    music(6, a - 1, 0.5)

    music(2, a + 0, 1.5)
    music(5, a - 1, 0.5)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(3, a + 0, 1)
    music(5, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(3, a + 0, 1)
    music(6, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.75)
    music(1, a + 0, 0.75)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.75)
    music(2, a + 0, 0.75)
    music(3, a + 0, 0.5)

    music(5, a + 0, 1.5)
    music(5, a - 1, 0.5)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(6, a + 0, 1)
    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(3, a + 0, 1)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)

    music(2, a + 0, 0.75)
    music(2, a + 0, 0.75)
    music(2, a + 0, 0.5)
    music(2, a + 0, 0.75)
    music(1, a + 0, 0.75)
    music(6, a - 1, 0.5)

    music(1, a + 0, 1.5)
    music(1, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(7, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.5)

    music(1, a + 1, 0.75)
    music(6, a + 0, 0.75)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)

    music(3, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 1)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)

    music(6, a + 0, 0.75)
    music(6, a + 0, 0.75)
    music(6, a + 0, 0.5)
    music(6, a + 0, 0.75)
    music(5, a + 0, 0.75)
    music(6, a + 0, 0.5)

    music(5, a + 0, 0.5)
    music(3, a + 0, 1.5)
    track.append(mido.Message('note_on', note=0, velocity=0, time=0))
    track.append(mido.Message('note_off', note=0, velocity=0, time=480 * 1))
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(6, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(1, a + 0, 0.5)
    music(1, a + 0, 0.5)
    music(1, a + 1, 0.5)

    music(1, a + 1, 0.75)
    music(1, a + 1, 0.75)
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.75)
    music(1, a + 1, 0.5)

    music(6, a + 0, 1.5)
    music(5, a + 0, 1)
    music(1, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(7, a + 0, 0.5)

    music(1, a + 1, 0.5)
    music(7, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)

    music(3, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 1)
    music(5, a + 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)

    music(6, a + 0, 0.75)
    music(6, a + 0, 0.75)
    music(6, a + 0, 0.5)
    music(6, a + 0, 0.75)
    music(5, a + 0, 0.75)
    music(6, a + 0, 0.5)

    music(5, a + 0, 0.5)
    music(3, a + 0, 1.5)
    track.append(mido.Message('note_on', note=0, velocity=0, time=0))
    track.append(mido.Message('note_off', note=0, velocity=0, time=480 * 1))
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 1)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(3, a + 0, 0.5)

    music(6, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)
    music(1, a + 0, 0.5)
    music(1, a + 1, 2)

    # 尾部
    track.append(mido.Message('note_on', note=0, velocity=0, time=0))
    track.append(mido.Message('note_off', note=0, velocity=0, time=480 * 3))
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.5)
    music(1, a + 1, 0.5)

    music(6, a + 0, 0.5)
    music(5, a + 0, 1)
    music(5, 0, 0.5)
    music(6, a + 0, 0.5)
    music(5, a + 0, 0.5)
    music(3, a + 0, 0.5)
    music(2, a + 0, 0.5)

    music(3, a + 0, 0.5)
    music(2, a + 0, 1)
    music(1, a + 0, 0.5)
    music(6, a - 1, 0.5)
    music(1, a + 0, 0.5)
    music(1, a + 0, 0.5)
    music(2, a + 0, 0.5)

    music(1, a + 0, 2)
    music(1, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.5)
    music(1, a + 1, 0.5)

    music(2, a + 1, 0.5)
    music(1, a + 1, 1)
    music(1, a + 1, 0.5)
    music(2, a + 1, 0.5)
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.5)
    music(1, a + 1, 0.5)

    music(3, a + 1, 0.5)
    music(2, a + 1, 1)
    music(1, a + 1, 0.5)
    music(6, a + 0, 0.5)
    music(1, a + 1, 0.5)
    music(2, a + 1, 1)

    music(1, a + 1, 4)


lemon_music()
mid.save('a2.mid')


def play():
    play_midi('a2.mid')


def show():
    for i in f.readlines():
        print("\033[0;34;40m%s\033[0m" % i)
        time.sleep(len(i) / 3)
        os.system('cls')


if __name__ == '__main__':
    f = open('lyrics.txt', 'r', encoding='utf-8')
    t1 = threading.Thread(target=play)
    t2 = threading.Thread(target=show)
    t1.start()
    t2.start()
    os.remove('a2.mid')

2.文本

歌名:富士山下

演唱:陈奕迅

作词:林夕

作曲:泽日生

代码编写:***

联系方式:***********

拦路雨偏似雪花 饮泣的你冻吗

这风褛我给你磨到有襟花

连掉了渍也不怕 怎么始终牵挂

苦心选中今天想车你回家

原谅我不再送花 伤口应要结疤

花瓣铺满心里坟场才害怕

如若你非我不嫁 彼此终必火化

一生一世等一天需要代价

谁都只得那双手 靠拥抱亦难任你拥有

要拥有必先懂失去怎接受

曾沿着雪路浪游 为何为好事泪流

谁能凭爱意要富士山私有

何不把悲哀感觉 假设是来自你虚构

试管里找不到它染污眼眸

前尘硬化像石头 随缘地抛下便逃走

我绝不罕有 往街里绕过一周 我便化乌有


情人节不要说穿 只敢抚你发端

这种姿态可会令你更心酸

留在汽车里取暖 应该怎么规劝

怎么可以将手腕忍痛划损

人活到几岁算短 失恋只有更短

归家需要几里路谁能预算

忘掉我跟你恩怨 樱花开了几转

东京之旅一早比一世遥远

谁都只得那双手 靠拥抱亦难任你拥有

要拥有必先懂失去怎接受

曾沿着雪路浪游 为何为好事泪流

谁能凭爱意要富士山私有

何不把悲哀感觉 假设是来自你虚构

试管里找不到它染污眼眸

前尘硬化像石头 随缘地抛下便逃走

我绝不罕有 往街里绕过一周 我便化乌有

你还嫌不够 我把这陈年风褛 送赠你解咒

感谢收听!

3.效果图 

 

好的,我可以为您提供一些关于使用Python代码实现Transformer的指导。 首先,您需要安装PyTorch和torchtext库。然后,您可以按照以下步骤实现Transformer模型: 1. 定义输入和输出的词汇表,并使用torchtext库加载数据集。 2. 定义Transformer模型的编码器和解码器部分。 3. 实现自注意力机制(self-attention)和前向神经网络(feed-forward network)。 4. 实现残差连接(residual connection)和层归一化(layer normalization)。 5. 定义Transformer模型的训练和评估过程。 下面是一个简单的示例代码,用于实现一个基本的Transformer模型: ```python import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torchtext.datasets import TranslationDataset, Multi30k from torchtext.data import Field, BucketIterator # 定义输入和输出的词汇表 SRC = Field(tokenize='spacy', tokenizer_language='de', init_token='<sos>', eos_token='<eos>', lower=True) TRG = Field(tokenize='spacy', tokenizer_language='en', init_token='<sos>', eos_token='<eos>', lower=True) # 加载数据集 train_data, valid_data, test_data = Multi30k.splits(exts=('.de', '.en'), fields=(SRC, TRG)) SRC.build_vocab(train_data, min_freq=2) TRG.build_vocab(train_data, min_freq=2) # 定义Transformer模型的编码器和解码器部分 class Encoder(nn.Module): def __init__(self, input_dim, hid_dim, n_layers, n_heads, pf_dim, dropout, device): super().__init__() self.device = device self.tok_embedding = nn.Embedding(input_dim, hid_dim) self.pos_embedding = nn.Embedding(1000, hid_dim) self.layers = nn.ModuleList([EncoderLayer(hid_dim, n_heads, pf_dim, dropout, device) for _ in range(n_layers)]) self.dropout = nn.Dropout(dropout) self.scale = torch.sqrt(torch.FloatTensor([hid_dim])).to(device) def forward(self, src, src_mask): # src: [batch_size, src_len] # src_mask: [batch_size, 1, 1, src_len] batch_size = src.shape[0] src_len = src.shape[1] pos = torch.arange(0, src_len).unsqueeze(0).repeat(batch_size, 1).to(self.device) # pos: [batch_size, src_len] src = self.dropout((self.tok_embedding(src) * self.scale) + self.pos_embedding(pos)) for layer in self.layers: src = layer(src, src_mask) return src class EncoderLayer(nn.Module): def __init__(self, hid_dim, n_heads, pf_dim, dropout, device): super().__init__() self.self_attn_layer_norm = nn.LayerNorm(hid_dim) self.ff_layer_norm = nn.LayerNorm(hid_dim) self.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout, device) self.positionwise_feedforward = PositionwiseFeedforwardLayer(hid_dim, pf_dim, dropout) self.dropout = nn.Dropout(dropout) def forward(self, src, src_mask):
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值