def create_music(prediction): offset = 0 output_notes = [] for data in prediction: if ('.' in data) or data.isdigit(): note_in_chord = data.split('.') notes = [] for current_note in note_in_chord: new_note = note.Note(int(current_note)) # 把当前音符化成整数,在对应midi_number转换成note new_note.storedInstrument = instrument.Piano() # 乐器用钢琴 notes.append(new_note) new_chord = chord.Chord(notes) # 再把notes中的音化成新的和弦 new_chord.offset = offset # 初试定的偏移给和弦的偏移 output_notes.append(new_chord) # 把转化好的和弦传到output_notes中 # 是note格式: else: new_note = note.Note(data) # note直接可以把data变成新的note new_note.offset = offset new_note.storedInstrument = instrument.Piano() # 乐器用钢琴 output_notes.append(new_note) # 把new_note传到output_notes中 # 每次迭代都将偏移增加,防止交叠覆盖 offset += 0.5 midi_stream = stream.Stream(output_notes) midi_stream.write('midi', fp='output24.mid')

时间: 2024-02-15 14:27:26 浏览: 24
这段代码是一个函数,用于根据输入的prediction生成音乐。首先,它定义了一个偏移量(offset)和一个空列表(output_notes),用于存储生成的音符或和弦。然后,它循环遍历prediction中的每个元素。如果元素中包含'.'或者是数字,说明它是和弦格式,就将其中每个音符分离开来,将它们转换为Note对象,再将这些Note对象转换为Chord对象,并加入到output_notes列表中。如果元素不是和弦格式,说明它是单音符,就将它转换为Note对象,并加入到output_notes列表中。每次循环都会更新偏移量(offset)。最后,将output_notes列表转换为一个midi流(stream)对象,再将这个流对象写入到文件'output24.mid'中。
相关问题

def create_music(prediction): # 生成音乐函数,训练不用 """ 用神经网络预测的音乐数据来生成mid文件 """ offset = 0 # 偏移,防止数据覆盖 output_notes = [] # 生成Note或chord对象 for data in prediction: # 如果是chord格式:45.21.78 if ('.' in data) or data.isdigit(): # data中有.或者有数字 note_in_chord = data.split('.') # 用.分隔和弦中的每个音 notes = [] # notes列表接收单音 for current_note in note_in_chord: new_note = note.Note(int(current_note)) # 把当前音符化成整数,在对应midi_number转换成note new_note.storedInstrument = instrument.Piano() # 乐器用钢琴 notes.append(new_note) new_chord = chord.Chord(notes) # 再把notes中的音化成新的和弦 new_chord.offset = offset # 初试定的偏移给和弦的偏移 output_notes.append(new_chord) # 把转化好的和弦传到output_notes中 # 是note格式: else: new_note = note.Note(data) # note直接可以把data变成新的note new_note.offset = offset new_note.storedInstrument = instrument.Piano() # 乐器用钢琴 output_notes.append(new_note) # 把new_note传到output_notes中 # 每次迭代都将偏移增加,防止交叠覆盖 offset += 0.5 # 创建音乐流(stream) midi_stream = stream.Stream(output_notes) # 把上面的循环输出结果传到流 # 写入midi文件 midi_stream.write('midi', fp='output24.mid')

这段代码是用来生成音乐的,输入是一个预测结果(prediction),通过循环遍历每个元素,如果是chord格式(如45.21.78),就把每个音符分离出来,将它们转换成note对象,再把这些note对象转换成一个新的chord对象,然后加入到output_notes列表中;如果是note格式,就直接把它转换成note对象,并加入到output_notes列表中。每次循环都会更新偏移量offset,保证音符不会重叠覆盖。最后把output_notes列表中的所有音符通过Stream对象转换成一个midi文件(output24.mid)。

def generate_midi(generator, output_file, start_sequence): # 加载模型参数 generator.load_weights('weights.hdf5') # 计算音符和和弦的数量 notes = load_midi(start_sequence) pitchnames = sorted(set(notes)) n_vocab = len(set(notes)) # 准备输入序列 sequence_length = 100 note_to_int = dict((note, number) for number, note in enumerate(pitchnames)) network_input = [] for i in range(0, len(notes) - sequence_length, 1): sequence_in = notes[i:i + sequence_length] network_input.append([note_to_int[char] for char in sequence_in]) # 生成 MIDI 文件 start = np.random.randint(0, len(network_input)-1) int_to_note = dict((number, note) for number, note in enumerate(pitchnames)) pattern = network_input[start] prediction_output = [] for note_index in range(500): prediction_input = np.reshape(pattern, (1, len(pattern), 1)) prediction_input = prediction_input / float(n_vocab) prediction = generator.predict(prediction_input, verbose=0) index = np.argmax(prediction) result = int_to_note[index] prediction_output.append(result) pattern.append(index) pattern = pattern[1:len(pattern)] offset = 0 output_notes = [] # 创建音符和和弦对象 for pattern in prediction_output: # 如果是和弦 if ('.' in pattern) or pattern.isdigit(): notes_in_chord = pattern.split('.') notes = [] for current_note in notes_in_chord: new_note = note.Note(int(current_note)) new_note.storedInstrument = instrument.Piano() notes.append(new_note) new_chord = chord.Chord(notes) new_chord.offset = offset output_notes.append(new_chord) # 如果是音符 else: new_note = note.Note(pattern) new_note.offset = offset new_note.storedInstrument = instrument.Piano() output_notes.append(new_note) # 增加偏移量 offset += 0.5 # 创建 MIDI 流对象 midi_stream = stream.Stream(output_notes) # 保存 MIDI 文件 midi_stream.write('midi', fp=output_file)

这段代码是用来生成 MIDI 音乐的,其中使用了一个生成器模型来生成音乐。在生成 MIDI 音乐之前,先加载模型参数,并准备输入序列。接下来,从输入序列中随机选择一个起始点,然后使用生成器模型来预测下一个音符或和弦。生成的音符或和弦会被添加到预测输出列表中,同时也会更新当前输入序列,以便用于下一个预测。最后,将预测输出转换成音符和和弦对象,并将它们添加到 MIDI 流对象中,最终生成 MIDI 文件。

相关推荐

以下代码有什么错误,怎么修改: import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from PIL import Image import matplotlib.pyplot as plt import input_data import model import numpy as np import xlsxwriter num_threads = 4 def evaluate_one_image(): workbook = xlsxwriter.Workbook('formatting.xlsx') worksheet = workbook.add_worksheet('My Worksheet') with tf.Graph().as_default(): BATCH_SIZE = 1 N_CLASSES = 4 image = tf.cast(image_array, tf.float32) image = tf.image.per_image_standardization(image) image = tf.reshape(image, [1, 208, 208, 3]) logit = model.cnn_inference(image, BATCH_SIZE, N_CLASSES) logit = tf.nn.softmax(logit) x = tf.placeholder(tf.float32, shape=[208, 208, 3]) logs_train_dir = 'log/' saver = tf.train.Saver() with tf.Session() as sess: print("从指定路径中加载模型...") ckpt = tf.train.get_checkpoint_state(logs_train_dir) if ckpt and ckpt.model_checkpoint_path: global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] saver.restore(sess, ckpt.model_checkpoint_path) print('模型加载成功, 训练的步数为: %s' % global_step) else: print('模型加载失败,checkpoint文件没找到!') prediction = sess.run(logit, feed_dict={x: image_array}) max_index = np.argmax(prediction) workbook.close() def evaluate_images(test_img): coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for index,img in enumerate(test_img): image = Image.open(img) image = image.resize([208, 208]) image_array = np.array(image) tf.compat.v1.threading.Thread(target=evaluate_one_image, args=(image_array, index)).start() coord.request_stop() coord.join(threads) if __name__ == '__main__': test_dir = 'data/test/' import glob import xlwt test_img = glob.glob(test_dir + '*.jpg') evaluate_images(test_img)

import time import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.examples.tutorials.mnist import input_data import mnist_inference import mnist_train tf.compat.v1.reset_default_graph() EVAL_INTERVAL_SECS = 10 def evaluate(mnist): with tf.Graph().as_default() as g: #定义输入与输出的格式 x = tf.compat.v1.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input') y_ = tf.compat.v1.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input') validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels} #直接调用封装好的函数来计算前向传播的结果 y = mnist_inference.inference(x, None) #计算正确率 correcgt_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correcgt_prediction, tf.float32)) #通过变量重命名的方式加载模型 variable_averages = tf.train.ExponentialMovingAverage(0.99) variable_to_restore = variable_averages.variables_to_restore() saver = tf.train.Saver(variable_to_restore) #每隔10秒调用一次计算正确率的过程以检测训练过程中正确率的变化 while True: with tf.compat.v1.Session() as sess: ckpt = tf.train.get_checkpoint_state(minist_train.MODEL_SAVE_PATH) if ckpt and ckpt.model_checkpoint_path: #load the model saver.restore(sess, ckpt.model_checkpoint_path) global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] accuracy_score = sess.run(accuracy, feed_dict=validate_feed) print("After %s training steps, validation accuracy = %g" % (global_step, accuracy_score)) else: print('No checkpoint file found') return time.sleep(EVAL_INTERVAL_SECS) def main(argv=None): mnist = input_data.read_data_sets(r"D:\Anaconda123\Lib\site-packages\tensorboard\mnist", one_hot=True) evaluate(mnist) if __name__ == '__main__': tf.compat.v1.app.run()对代码进行改进

请修改这一份代码:import random from sklearn import svm from sklearn.metrics import accuracy_score from skimage.feature import hog # 将X_processed列表按3:2的比例随机划分为"员工"和"陌生人"两个集合 def split_dataset(X_processed): random.shuffle(X_processed) split_index = int(len(X_processed) * 3 / 5) employee_set = X_processed[:split_index] stranger_set = X_processed[split_index:] return employee_set, stranger_set # 使用HOG特征提取进行人脸识别训练 def train_face_recognition(employee_set): X = [] = [] for i, face_images in enumerate(employee_set): for face_image in face_images: feature = hog(face_image, orientations=8, pixels_per_cell=(10, 10), cells_per_block=(1, 1), visualize=False) X.append(feature) y.append(i) # i代表员工的标签 clf = svm.SVC() clf.fit(X, y) return clf # 随机抽取一张图片进行识别 def recognize_random_face(clf, X_processed): random_index = random.randint(0, len(X_processed)-1) random_face_images = X_processed[random_index] random_face_image = random.choice(random_face_images) feature = hog(random_face_image, orientations=8, pixels_per_cell=(10, 10), cells_per_block=(1, 1), visualize=False) prediction = clf.predict([feature]) return prediction[0] == random_index # 示例用法 X_processed = [...] # X_processed列表的具体内容 employee_set, stranger_set = split_dataset(X_processed) clf = train_face_recognition(employee_set) result = recognize_random_face(clf, X_processed) print("识别结果:", result),增加如下功能:如果测试时认为图片不属于员工集中的任何一个员工,prediction应该等于0;“陌生人”集合也应当拥有标签,“陌生人”的标签都是0,代表非员工

最新推荐

recommend-type

煤矿水PH值的测定方法.pdf

煤矿水PH值的测定方法.pdf
recommend-type

node-v6.14.3-linux-x64.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

node-v6.10.3-sunos-x64.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

如何用python编写api接口

在Python中编写API接口可以使用多种框架,其中比较流行的有Flask和Django。这里以Flask框架为例,简单介绍如何编写API接口。 1. 安装Flask框架 使用pip命令安装Flask框架: ``` pip install flask ``` 2. 编写API接口 创建一个Python文件,例如app.py,编写以下代码: ```python from flask import Flask, jsonify app = Flask(__name__) @app.route('/api/hello', methods=['GET']) def hello():
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这