Exemple #1
0
def trainandsave():
    # 神经网络结构
    model = model4()
    optimizer = optim.SGD(model.parameters(), lr=0.001,
                          momentum=0.9)  # 学习率为0.001
    criterion = nn.CrossEntropyLoss()  # 损失函数也可以自己定义,我们这里用的交叉熵损失函数
    # 训练部分
    for epoch in range(5):  # 训练的数据量为5个epoch,每个epoch为一个循环
        # 每个epoch要训练所有的图片,每训练完成200张便打印一下训练的效果(loss值)
        running_loss = 0.0  # 定义一个变量方便我们对loss进行输出
        for i in enumerate(x_train, y_train, 0):  # 这里我们遇到了第一步中出现的训练数据,代码传入数据
            # enumerate是python的内置函数,既获得索引也获得数据
            inputs, labels = Variable(x_train), Variable(
                y_train)  # 转换数据格式用Variable

            optimizer.zero_grad()  # 梯度置零,因为反向传播过程中梯度会累加上一次循环的梯度

            # forward + backward + optimize
            outputs = model(inputs)  # 把数据输进CNN网络net
            loss = criterion(outputs, labels)  # 计算损失值
            loss.backward()  # loss反向传播
            optimizer.step()  # 反向传播后参数更新
            running_loss += loss.data[0]  # loss累加
            if i % 200 == 199:
                print('[%d, %5d] loss: %.3f' %
                      (epoch + 1, i + 1,
                       running_loss / 200))  # 然后再除以200,就得到这两百次的平均损失值
                running_loss = 0.0  # 这一个200次结束后,就把running_loss归零,下一个200次继续使用

    print('Finished Training')
    # 保存神经网络
    torch.save(model, 'net.pkl')  # 保存整个神经网络的结构和模型参数
    torch.save(model.state_dict(), 'net_params.pkl')  # 只保存神经网络的模型参数
    def test_equality(self):
        # values doesn't matter, only class and name are checked
        v1 = Variable(self.root, name="abc")
        v2 = Variable(self.root, name="abc")
        self.assertIsNot(v1, v2)
        self.assertEqual(v1, v2)

        v3 = Variable(self.root, name="cba")
        self.assertNotEqual(v1, v3)

        v4 = StringVar(self.root, name="abc")
        self.assertEqual(str(v1), str(v4))
        self.assertNotEqual(v1, v4)

        V = type('Variable', (), {})
        self.assertNotEqual(v1, V())

        self.assertNotEqual(v1, object())
        self.assertEqual(v1, ALWAYS_EQ)

        root2 = tkinter.Tk()
        self.addCleanup(root2.destroy)
        v5 = Variable(root2, name="abc")
        self.assertEqual(str(v1), str(v5))
        self.assertNotEqual(v1, v5)
Exemple #3
0
 def test___eq__(self):
     v1 = Variable(self.root, name='abc')
     v2 = Variable(self.root, name='abc')
     self.assertEqual(v1, v2)
     v3 = Variable(self.root, name='abc')
     v4 = StringVar(self.root, name='abc')
     self.assertNotEqual(v3, v4)
Exemple #4
0
 def test_dont_unset_not_existing(self):
     self.assertFalse(self.info_exists('varname'))
     v1 = Variable(self.root, name='name')
     v2 = Variable(self.root, name='name')
     del v1
     self.assertFalse(self.info_exists('name'))
     del v2
     self.assertFalse(self.info_exists('name'))
Exemple #5
0
    def __init__(self, master=None, value=None, options=[], name=None):
        self._options = []

        Variable.__init__(self, master, value, name)

        for option in options:
            self._options.append(StringVar(value=str(option)))
        self._set_initial(value)
Exemple #6
0
def make_setter(section: str, config: str, variable: tk.Variable) -> None:
    """Create a callback which sets the given config from a variable."""
    def callback(var_name: str, var_ind: str, cback_name: str) -> None:
        """Automatically called when the variable is written to."""
        COMPILE_CFG[section][config] = str(variable.get())
        COMPILE_CFG.save_check()

    variable.trace_add('write', callback)
Exemple #7
0
 def test_dont_unset_not_existing(self):
     self.assertFalse(self.info_exists("varname"))
     v1 = Variable(self.root, name="name")
     v2 = Variable(self.root, name="name")
     del v1
     self.assertFalse(self.info_exists("name"))
     # shouldn't raise exception
     del v2
     self.assertFalse(self.info_exists("name"))
Exemple #8
0
 def test_variable(self):
     self.assertRaises(RuntimeError, Variable)
     root = tkinter.Tk()
     v = Variable()
     v.set("value")
     self.assertEqual(v.get(), "value")
     root.destroy()
     tkinter.NoDefaultRoot()
     self.assertRaises(RuntimeError, Variable)
Exemple #9
0
    def test___eq__(self):
        # values doesn't matter, only class and name are checked
        v1 = Variable(self.root, name="abc")
        v2 = Variable(self.root, name="abc")
        self.assertEqual(v1, v2)

        v3 = Variable(self.root, name="abc")
        v4 = StringVar(self.root, name="abc")
        self.assertNotEqual(v3, v4)
Exemple #10
0
    def __init__(self,
                 master=None,
                 value=None,
                 name=None,
                 max_val=0,
                 max_val_callback=None):
        self._max = max_val
        self._max_val_callback = max_val_callback

        Variable.__init__(self, master, value, name)
Exemple #11
0
class OptionMenuComponent(MediatorComponent):
    """WidgetMediator component that contains an OptionMenu
    """
    # Private Attributes:
    #   - _var: the external mutatable variable for the menu widget
    #   - _om: the OptionMenu shown to the user that displays the selection
    #   - _mediator: the mediator to notify a selection has been made to update other colleages

    _var: Variable
    _om: OptionMenu

    _mediator: MenuMediator

    def __init__(self, parent: Widget, mediator: MenuMediator) -> None:
        self._var = Variable()
        self._mediator = mediator
        self._om = OptionMenu(parent, self._var, "")

    def reset_selection(self) -> None:
        """Sets the option menu variable to an empty string"""
        self._var.set("")

    def set_selection(self, data: list) -> None:
        """Sets the OptionMenu options to data"""
        menu = self._om["menu"]

        _delete_menu_options(menu)

        def click_command(variable: Variable, opt: Any) -> Callable:
            """Return the command to be called when clicking an option item"""
            def wrapper() -> None:
                """Function called when clicking an option item"""
                variable.set(opt)
                self._mediator.update_selection(())

            return wrapper

        data = sorted(set(data))

        menu.add_command(label="", command=click_command(self._var, ""))
        for option in data:
            menu.add_command(label=option,
                             command=click_command(self._var, option))

    def get_widget(self) -> Widget:
        """Return a list containing this OptionMenu"""
        return self._om

    def configure_menu(self, config: str, value: str) -> None:
        """Configures the setting of the composed dOptionMenu"""
        self._om[config] = value

    def get_selected(self) -> Any:
        """Return the current variable's value"""
        return self._var.get()
Exemple #12
0
    def __init__(self, master=None, value=None, name=None):
        """Construct an Loc variable.

        MASTER can be given as master widget.
        VALUE is an optional value (defaults to 0)
        NAME is an optional Tcl name (defaults to PY_VARnum).

        If NAME matches an existing variable and VALUE is omitted
        then the existing value is retained.
        """
        Variable.__init__(self, master, value, name)
Exemple #13
0
def check_tkvar(val: tk.Variable, allow_blank: bool = False):
    """Returns True if calling ``val.get()`` doesn't raise `TclError`."""
    try:
        val.get()
        return True
    except tk.TclError:
        # noinspection PyProtectedMember
        if allow_blank and not val._tk.globalgetvar(val._name).strip():
            return True
        else:
            return False
 def test_dont_unset_not_existing(self):
     self.assertFalse(self.info_exists("varname"))
     v1 = Variable(self.root, name="name")
     v2 = Variable(self.root, name="name")
     del v1
     support.gc_collect()  # For PyPy or other GCs.
     self.assertFalse(self.info_exists("name"))
     # shouldn't raise exception
     del v2
     support.gc_collect()  # For PyPy or other GCs.
     self.assertFalse(self.info_exists("name"))
Exemple #15
0
    def setupOptionsView(self):
        # self.pack() # 若继承 tk.Frame ,此句必须有!
        self.title('管理员操作界面')
        self.geometry("900x600+500+230")
        # 程序参数/数据
        self.tipVar = Variable()
        # self.tipVar.set("当前ATM机内余额为:%.2f" % atm.cardId)
        self.resizable(width=False, height=False)
        # 使用Frame增加一层容器
        fm1 = Frame(self)
        fm2 = Frame(self)
        fm3 = Frame(self)
        fm4 = Frame(self)

        button_image_gif7 = PhotoImage(file="开户按钮.gif")
        Button(fm1, text='开户', font=("宋体", 15), image=button_image_gif7,  width=190, height=45,command=self.createUser).pack(side=TOP, anchor=W,expand=NO, pady =7)
        button_image_gif8 = PhotoImage(file="存款按钮.gif")
        Button(fm1, text='存款', font=("宋体", 15), image=button_image_gif8,  width=190, height=45,command=self.addAcount).pack(side=TOP, anchor=W,expand=NO, pady =7)
        button_image_gif9 = PhotoImage(file="改密按钮.gif")
        Button(fm1, text='改密', font=("宋体", 15), image=button_image_gif9,  width=190, height=45,command=self.modPasswd).pack(side=TOP, anchor=W,expand=NO, pady =7)
        button_image_gif10 = PhotoImage(file="锁定按钮.gif")
        Button(fm1, text='锁卡', font=("宋体", 15), image=button_image_gif10,  width=190, height=45,command=self.lockedCard).pack(side=TOP, anchor=W,expand=NO, pady =7)
        button_image_gif11 = PhotoImage(file="退卡按钮.gif")
        Button(fm1, text='退卡', font=("宋体", 15),image=button_image_gif11,  width=190, height=45,command=self.outPutCard).pack(side=TOP, anchor=W,expand=NO, pady =7)
        fm1.pack(side=LEFT, fill=BOTH, expand=YES, pady=60)

        Label(fm3, text="SUNCK IS A GOOD MAN",
              font=("宋体", 15), width=30, height=7, wraplength=350).pack(side=TOP,padx= 20)
        Label(fm3, textvariable=self.tipVar, font=("宋体", 11), width=40, height=10).pack(side=TOP)
        button_image_gif12 = PhotoImage(file="退出按钮.gif")
        Button(fm4, text='退出', font=("宋体", 15), image=button_image_gif12, width=190, height=45,command=self.shutdown).pack(side=LEFT, anchor=tk.N,expand=NO, padx= 70)
        button_image_gif13 = PhotoImage(file="插卡按钮.gif")
        Button(fm4, text='插卡', font=("宋体", 15), image=button_image_gif13,  width=115, height=27,command=self.putinCard).pack(side=RIGHT, anchor=tk.S,expand=NO,padx= 50)
        fm4.pack(side=tk.BOTTOM,fill= "x", expand=YES)
        fm3.pack(side=LEFT, fill=BOTH, expand=YES)

        button_image_gif14 = PhotoImage(file="转账按钮.gif")
        Button(fm2, text='转账', font=("宋体", 15), image=button_image_gif14,  width=190, height=45,command=self.transAcount).pack(side=TOP, anchor=E,expand=NO, pady =7)
        button_image_gif15 = PhotoImage(file="取款按钮.gif")
        Button(fm2, text='取款', font=("宋体", 15), image=button_image_gif15,  width=190, height=45,command=self.getAcount).pack(side=TOP, anchor=E,expand=NO, pady =7)
        button_image_gif16 = PhotoImage(file="补卡按钮.gif")
        Button(fm2, text='补卡', font=("宋体", 15), image=button_image_gif16,  width=190, height=45,command=self.repairCard).pack(side=TOP, anchor=E,expand=NO, pady =7)
        button_image_gif17 = PhotoImage(file="解锁按钮.gif")
        Button(fm2, text='解锁', font=("宋体", 15), image=button_image_gif17,  width=190, height=45,command=self.unlockedCard).pack(side=TOP, anchor=E,expand=NO, pady =7)
        button_image_gif18 = PhotoImage(file="返回按钮.gif")
        Button(fm2, text='返回', font=("宋体", 15), image=button_image_gif18,  width=190, height=45,command=self.back).pack(side=TOP, anchor=E,expand=NO, pady =3)

        fm2.pack(side=RIGHT, fill=BOTH, expand=YES, pady=60)
        self.mainloop()
Exemple #16
0
    def test___eq__(self):
        # values doesn't matter, only class and name are checked
        v1 = Variable(self.root, name="abc")
        v2 = Variable(self.root, name="abc")
        self.assertIsNot(v1, v2)
        self.assertEqual(v1, v2)

        v3 = StringVar(self.root, name="abc")
        self.assertNotEqual(v1, v3)

        V = type('Variable', (), {})
        self.assertNotEqual(v1, V())

        self.assertNotEqual(v1, object())
        self.assertEqual(v1, ALWAYS_EQ)
Exemple #17
0
    def __init__(self):
        self.var_dest = StringVar()
        self.var_dest.set("")

        self.var_wrap = BooleanVar()
        self.var_wrap.set(True)

        self.lstvar_src = Variable()
        self.lstvar_src.set([])

        self.lstvar_exc = Variable()
        self.lstvar_exc.set([])

        self.var_managed = BooleanVar()
        self.var_managed.set(False)
 def test___del__(self):
     self.assertFalse(self.info_exists("varname"))
     v = Variable(self.root, "sample string", "varname")
     self.assertTrue(self.info_exists("varname"))
     del v
     support.gc_collect()  # For PyPy or other GCs.
     self.assertFalse(self.info_exists("varname"))
Exemple #19
0
 def wrap_cls(_unit: Variable, amount: Variable) -> str:
     unit = _unit.get()
     if unit in size_units:
         return size_units[unit].__name__ + f'({amount.get()})'
     elif unit in time_units:
         return time_units[unit].__name__ + f'({amount.get()})'
     else:
         raise NotImplementedError
Exemple #20
0
 def set(self, value):
     """Set the variable to value, converting iterable to Loc."""
     if not isinstance(value, Loc):
         try:
             value = Loc(*value)
         except TypeError:
             pass
     return Variable.set(self, repr(value))
Exemple #21
0
    def _update_fromvar(self, key: str, var: tk.Variable, *unused):

        # OptionMenu gives us the changes as positional argument,
        # but Checkbutton doesn't
        # This function streamline the process of getting the value,
        # and thus *args is here to catch some additional unused parameters

        conf = {}
        conf[key] = var.get()
        self._update_config(**conf)
Exemple #22
0
    def __init__(self,
                 master: tk_gui.VariableListFrame,
                 values: Union[data.ValueRange, Tuple],
                 variable: tk.Variable,
                 text: str,
                 width=650,
                 execute: Optional[callable] = None):
        super().__init__(master)

        # basic behaviour and layout
        self.transient(master)
        self.protocol('WM_DELETE_WINDOW', self._on_close)
        self.grab_set()
        self.config(background='white')

        # Label and Title
        self.title = 'Set Value'
        ttk.Label(self, text=text).pack()

        # Variable change widget
        if isinstance(values, data.ValueRange):
            tk.Scale(master=self,
                     from_=values.min,
                     to=values.max,
                     resolution=values.step or (values.max - values.min) / 100,
                     orient=tk.HORIZONTAL,
                     variable=variable,
                     length=width,
                     background='white').pack()
        else:
            ttk.Combobox(master=self,
                         textvariable=variable,
                         values=values,
                         background='white').pack()

        self.variable = variable
        self.original_value = variable.get()

        # Button(s)
        button_frame = ttk.Frame(self)
        button_frame.pack()
        if execute:

            @tk_gui.message_box_on_error
            def command_ok():
                self.destroy()
                self.grab_release()
                execute(variable.get())
        else:
            command_ok = self.destroy

        ttk.Button(button_frame, text='Done', command=command_ok) \
            .grid(row=0, column=1, padx=30, pady=10)
        ttk.Button(button_frame, text='Cancel', command=self._on_close) \
            .grid(row=0, column=0)
Exemple #23
0
    def __init__(self):
        self.xmly = ximalaya()
        self.window = Tk()
        self.window.title("下载")
        self.window.geometry("670x600+700+300")
        # width x height + left + top
        var = Variable()
        var.set("http://www.ximalaya.com/67241256/album/10352095/")  # 设置文本框中的值
        self.entry = Entry(self.window, textvariable=var)
        self.entry.place(x=10, y=10, width=600, height=25)
        # self.entry.pack()

        self.submit_btn = Button(self.window, text="下载", command=self.submit)
        self.submit_btn.place(x=610, y=10, width=50, height=25)

        self.title_label = Label(self.window, text="结果:")
        self.title_label.place(x=10, y=55)

        self.result_text = Text(self.window, background="#ccc")
        self.result_text.place(x=10, y=75, width=650, height=500)
Exemple #24
0
 def test_null_in_name(self):
     with self.assertRaises(ValueError):
         Variable(self.root, name='var\x00name')
     with self.assertRaises(ValueError):
         self.root.globalsetvar('var\x00name', "value")
     with self.assertRaises(ValueError):
         self.root.globalsetvar(b'var\x00name', "value")
     with self.assertRaises(ValueError):
         self.root.setvar('var\x00name', "value")
     with self.assertRaises(ValueError):
         self.root.setvar(b'var\x00name', "value")
Exemple #25
0
def test():
    model = reload_net()
    imshow(torchvision.utils.make_grid(x_valid,
                                       nrow=5))  # nrow是每行显示的图片数量,缺省值为8
    print('GroundTruth: ',
          " ".join('%5s' % classes[y_valid[j]]
                   for j in range(25)))  # 打印前25个GT(test集里图片的标签)
    outputs = model(Variable(x_train))
    _, predicted = torch.max(outputs.data, 1)

    print('Predicted: ',
          " ".join('%5s' % classes[predicted[j]] for j in range(25)))
Exemple #26
0
class Prop:
    def __init__(self, initialValue=None, callback=None):
        self._var = Variable(value=initialValue)
        if callback is not None:
            self._var.trace(mode='w', callback=callback)

    def get(self):
        return self._var.get()

    def set(self, value):
        self._var.set(value)

    def on_change(self, listener):
        def update(*dummy):
            listener(self._var.get())
            self._var.trace('w', update)
Exemple #27
0
def tkVariable(var: Variable, key: str, default=None):
    """
    将tkinter的var绑定到缓存
    :param var:
    :param key:
    :param default:
    :return:
    """
    _cache = cache.get(key, default=None)
    if _cache is None:
        if default is not None:
            var.set(default)
    else:
        var.set(_cache)
    var.trace('w', lambda a, b, c: cache.set(key, var.get()))
Exemple #28
0
    def __init__(self,
                 master=None,
                 select_callback=None,
                 delete_callback=None):
        Frame.__init__(self, master)

        self._select_callback = select_callback
        self._delete_callback = delete_callback

        choices = Variable(self)
        self.listbox = Listbox(self, listvariable=choices, selectmode='single')
        self.listbox.pack()

        buttons_frame = Frame(self)
        Button(buttons_frame, text="Select",
               command=self.get_selected_element).pack(side=RIGHT)
        Button(buttons_frame,
               text="Delete",
               command=self.delete_selected_element).pack(side=RIGHT)
        buttons_frame.pack()
Exemple #29
0
 epoches = 40
 model = autoencoder()  #调用模型
 train_data = get_data()  #取数据
 criterion = nn.MSELoss()  #评估标准:MSE
 optimizier = optim.Adam(model.parameters(),
                         lr=lr,
                         weight_decay=weight_decay)  #优化器
 if torch.cuda.is_available():
     model.cuda()
 for epoch in range(epoches):  #循环epoch,设置学习率
     if epoch in [epoches * 0.25, epoches * 0.5]:
         for param_group in optimizier.param_groups:
             param_group['lr'] *= 0.1
     for img, _ in train_data:
         img = img.view(img.size(0), -1)
         img = Variable(img.cuda())
         #forward
         _, output = model(img)  #把数据放入模型
         loss = criterion(output, img)  #损失
         #backward
         optimizier.zero_grad()
         loss.backward()
         optimizier.step()
     print('epoch=', epoch, loss.data.float())
     for param_group in optimizier.param_groups:
         print(param_group['lr'])
     if (epoch + 1) % 5 == 0:
         pic = to_img(output.cpu().data)
         if not os.path.exists('./simple_autoencoder'):  #判断该路径是否存在
             os.mkdir(pic, './simple_autoencoder/image_{}.png'.format(
                 epoch + 1))  #如果不存在则将处理后的数据放入该路径
Exemple #30
0
 def test_invalid_name(self):
     with self.assertRaises(TypeError):
         Variable(self.root, name=123)